| 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/pgenlib_write.h" |
| 19 |
#include "plink2_compress_stream.h" |
| 20 |
#include "plink2_data.h" |
| 21 |
#include "plink2_merge.h" |
| 22 |
#include "plink2_psam.h" |
| 23 |
#include "plink2_pvar.h" |
| 24 |
|
| 25 |
#ifdef __cplusplus |
| 26 |
namespace plink2 { |
| 27 |
#endif |
| 28 |
|
| 29 |
void InitPmerge(PmergeInfo* pmerge_info_ptr) { |
| 30 |
pmerge_info_ptr->flags = kfPmerge0; |
| 31 |
pmerge_info_ptr->list_mode = kPmergeListModePfile; |
| 32 |
pmerge_info_ptr->merge_mode = kMergeModeNmMatch; |
| 33 |
pmerge_info_ptr->merge_parents_mode = kMergePhenoModeNmMatch; |
| 34 |
pmerge_info_ptr->merge_sex_mode = kMergePhenoModeNmMatch; |
| 35 |
pmerge_info_ptr->merge_pheno_mode = kMergePhenoModeNmMatch; |
| 36 |
pmerge_info_ptr->merge_xheader_mode = kMergeXheaderModeFirst; |
| 37 |
pmerge_info_ptr->merge_qual_mode = kMergeQualModeMin; |
| 38 |
pmerge_info_ptr->merge_filter_mode = kMergeFilterModeNmFirst; |
| 39 |
pmerge_info_ptr->merge_info_mode = kMergeInfoCmModeNmFirst; |
| 40 |
pmerge_info_ptr->merge_cm_mode = kMergeInfoCmModeNmFirst; |
| 41 |
pmerge_info_ptr->merge_pheno_sort = kSortNone; |
| 42 |
pmerge_info_ptr->merge_info_sort = kSortNone; |
| 43 |
pmerge_info_ptr->max_allele_ct = 0; |
| 44 |
pmerge_info_ptr->pgen_fname = nullptr; |
| 45 |
pmerge_info_ptr->pvar_fname = nullptr; |
| 46 |
pmerge_info_ptr->psam_fname = nullptr; |
| 47 |
pmerge_info_ptr->list_fname = nullptr; |
| 48 |
pmerge_info_ptr->list_base_dir = nullptr; |
| 49 |
} |
| 50 |
|
| 51 |
void CleanupPmerge(PmergeInfo* pmerge_info_ptr) { |
| 52 |
free_cond(pmerge_info_ptr->pgen_fname); |
| 53 |
free_cond(pmerge_info_ptr->pvar_fname); |
| 54 |
free_cond(pmerge_info_ptr->psam_fname); |
| 55 |
free_cond(pmerge_info_ptr->list_fname); |
| 56 |
free_cond(pmerge_info_ptr->list_base_dir); |
| 57 |
} |
| 58 |
|
| 59 |
void InitPgenDiff(PgenDiffInfo* pgen_diff_info_ptr) { |
| 60 |
pgen_diff_info_ptr->flags = kfPgenDiff0; |
| 61 |
pgen_diff_info_ptr->dosage_hap_tol = kDosageMissing; |
| 62 |
pgen_diff_info_ptr->pgen_fname = nullptr; |
| 63 |
pgen_diff_info_ptr->pvar_fname = nullptr; |
| 64 |
pgen_diff_info_ptr->psam_fname = nullptr; |
| 65 |
} |
| 66 |
|
| 67 |
void CleanupPgenDiff(PgenDiffInfo* pgen_diff_info_ptr) { |
| 68 |
free_cond(pgen_diff_info_ptr->pgen_fname); |
| 69 |
free_cond(pgen_diff_info_ptr->pvar_fname); |
| 70 |
free_cond(pgen_diff_info_ptr->psam_fname); |
| 71 |
} |
| 72 |
|
| 73 |
typedef struct PmergeInputFilesetLlStruct { |
| 74 |
struct PmergeInputFilesetLlStruct* next; |
| 75 |
// Heap-allocated iff temporary |
| 76 |
char* pgen_fname; |
| 77 |
char* pvar_fname; |
| 78 |
char* psam_fname; |
| 79 |
char* pgen_locked_fname; |
| 80 |
|
| 81 |
uint32_t read_sample_ct; |
| 82 |
uint32_t write_sample_ct; |
| 83 |
uint32_t read_variant_ct; |
| 84 |
// accounts for --chr, negative bp, same-ID + same-position |
| 85 |
uint32_t write_variant_ct; |
| 86 |
// Also accounts for --merge-max-alleles. Separate from write_variant_ct |
| 87 |
// since, for large --pmerge-list jobs, we may need to write a tombstone for |
| 88 |
// variants doomed to fail the --merge-max-alleles filter. |
| 89 |
// We compute this upfront to make PmergeConcat() more efficient, since |
| 90 |
// that's the most common use case. |
| 91 |
uint32_t write_nondoomed_variant_ct; |
| 92 |
uint32_t max_pvar_line_blen; |
| 93 |
uint32_t max_single_pos_ct; |
| 94 |
uintptr_t max_single_pos_blen; // includes chrom/pos, could remove later |
| 95 |
char* first_varid; // heap-allocated |
| 96 |
char* last_varid; // heap-allocated |
| 97 |
uint32_t first_pos; |
| 98 |
uint32_t last_pos; |
| 99 |
ChrIdx first_chr_idx; |
| 100 |
ChrIdx last_chr_idx; |
| 101 |
uint32_t read_max_nonpass_filter_ct; |
| 102 |
AlleleCode read_max_allele_ct; |
| 103 |
AlleleCode write_nondoomed_max_allele_ct; |
| 104 |
unsigned char nm_qual_exists; |
| 105 |
unsigned char nm_filter_exists; |
| 106 |
unsigned char nm_info_exists; |
| 107 |
unsigned char pvar_info_pr_exists; |
| 108 |
unsigned char nz_cm_present; |
| 109 |
|
| 110 |
// initialized by ScanPgenHeaders() |
| 111 |
unsigned char nonref_flags_storage; |
| 112 |
unsigned char vrtype_8bit_needed; |
| 113 |
|
| 114 |
// Note that this struct is allocated on bigstack, rather than the heap, iff |
| 115 |
// the fileset is not temporary. |
| 116 |
unsigned char is_temporary; |
| 117 |
} PmergeInputFilesetLl; |
| 118 |
|
| 119 |
// Allocates at end of bigstack. |
| 120 |
PmergeInputFilesetLl* AllocFilesetLlEntry(PmergeInputFilesetLl*** filesets_endpp) { |
| 121 |
const uintptr_t alloc_size = RoundUpPow2(sizeof(PmergeInputFilesetLl), kEndAllocAlign); |
| 122 |
if (unlikely(S_CAST(uintptr_t, g_bigstack_end - g_bigstack_base) < alloc_size)) { |
| 123 |
return nullptr; |
| 124 |
} |
| 125 |
g_bigstack_end -= alloc_size; |
| 126 |
PmergeInputFilesetLl* new_entry = R_CAST(PmergeInputFilesetLl*, g_bigstack_end); |
| 127 |
new_entry->next = nullptr; |
| 128 |
**filesets_endpp = new_entry; |
| 129 |
*filesets_endpp = &(new_entry->next); |
| 130 |
return new_entry; |
| 131 |
} |
| 132 |
|
| 133 |
PglErr LoadPmergeList(const char* list_fname, const char* list_base_dir, PmergeListMode mode, uint32_t main_fileset_present, PmergeInputFilesetLl*** filesets_endpp, uintptr_t* fileset_ctp) { |
| 134 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 135 |
uintptr_t line_idx = 0; |
| 136 |
PglErr reterr = kPglRetSuccess; |
| 137 |
TextStream txs; |
| 138 |
PreinitTextStream(&txs); |
| 139 |
{ |
| 140 |
reterr = InitTextStream(list_fname, kTextStreamBlenFast, 1, &txs); |
| 141 |
if (unlikely(reterr)) { |
| 142 |
goto LoadPmergeList_ret_TSTREAM_FAIL; |
| 143 |
} |
| 144 |
const char* pgen_suffix; |
| 145 |
const char* pvar_suffix; |
| 146 |
const char* psam_suffix; |
| 147 |
switch (mode) { |
| 148 |
case kPmergeListModeBfile: |
| 149 |
pgen_suffix = ".bed"; |
| 150 |
pvar_suffix = ".bim"; |
| 151 |
psam_suffix = ".fam"; |
| 152 |
break; |
| 153 |
case kPmergeListModeBpfile: |
| 154 |
pgen_suffix = ".pgen"; |
| 155 |
pvar_suffix = ".bim"; |
| 156 |
psam_suffix = ".fam"; |
| 157 |
break; |
| 158 |
case kPmergeListModePfile: |
| 159 |
pgen_suffix = ".pgen"; |
| 160 |
pvar_suffix = ".pvar"; |
| 161 |
psam_suffix = ".psam"; |
| 162 |
break; |
| 163 |
default: |
| 164 |
assert(mode == kPmergeListModePfileVzs); |
| 165 |
pgen_suffix = ".pgen"; |
| 166 |
pvar_suffix = ".pvar.zst"; |
| 167 |
psam_suffix = ".psam"; |
| 168 |
break; |
| 169 |
} |
| 170 |
const uint32_t pgen_blen = strlen(pgen_suffix) + 1; |
| 171 |
const uint32_t pvar_blen = strlen(pvar_suffix) + 1; |
| 172 |
const uint32_t psam_blen = strlen(psam_suffix) + 1; |
| 173 |
uint32_t base_dir_slen = 0; |
| 174 |
if (list_base_dir) { |
| 175 |
base_dir_slen = strlen(list_base_dir); |
| 176 |
} |
| 177 |
const uint32_t max_single_token_slen = kPglFnamesize - 1 - MAXV(pgen_blen, pvar_blen) - base_dir_slen; |
| 178 |
while (1) { |
| 179 |
const char* first_token_start = TextGet(&txs); |
| 180 |
if (!first_token_start) { |
| 181 |
break; |
| 182 |
} |
| 183 |
++line_idx; |
| 184 |
PmergeInputFilesetLl* cur_entry = AllocFilesetLlEntry(filesets_endpp); |
| 185 |
if (unlikely(!cur_entry)) { |
| 186 |
goto LoadPmergeList_ret_NOMEM; |
| 187 |
} |
| 188 |
cur_entry->is_temporary = 0; |
| 189 |
cur_entry->pgen_locked_fname = nullptr; |
| 190 |
cur_entry->first_varid = nullptr; |
| 191 |
cur_entry->last_varid = nullptr; |
| 192 |
const char* first_token_end = CurTokenEnd(first_token_start); |
| 193 |
const uint32_t first_token_slen = first_token_end - first_token_start; |
| 194 |
const char* second_token_start = FirstNonTspace(first_token_end); |
| 195 |
if (IsEolnKns(*second_token_start)) { |
| 196 |
// Expand single token, using the --pmerge-list mode. |
| 197 |
if (unlikely(first_token_slen > max_single_token_slen)) { |
| 198 |
logerrprintf("Error: Entry on line %" PRIuPTR " of --pmerge-list file is too long.\n", line_idx); |
| 199 |
goto LoadPmergeList_ret_INCONSISTENT_INPUT; |
| 200 |
} |
| 201 |
char* fname_iter; |
| 202 |
if (unlikely(bigstack_end_alloc_c((first_token_slen + base_dir_slen) * 3 + pgen_blen + pvar_blen + psam_blen, &fname_iter))) { |
| 203 |
goto LoadPmergeList_ret_NOMEM; |
| 204 |
} |
| 205 |
cur_entry->pgen_fname = fname_iter; |
| 206 |
if (base_dir_slen) { |
| 207 |
fname_iter = memcpya(fname_iter, list_base_dir, base_dir_slen); |
| 208 |
} |
| 209 |
fname_iter = memcpya(fname_iter, first_token_start, first_token_slen); |
| 210 |
fname_iter = memcpya(fname_iter, pgen_suffix, pgen_blen); |
| 211 |
cur_entry->pvar_fname = fname_iter; |
| 212 |
if (base_dir_slen) { |
| 213 |
fname_iter = memcpya(fname_iter, list_base_dir, base_dir_slen); |
| 214 |
} |
| 215 |
fname_iter = memcpya(fname_iter, first_token_start, first_token_slen); |
| 216 |
fname_iter = memcpya(fname_iter, pvar_suffix, pvar_blen); |
| 217 |
cur_entry->psam_fname = fname_iter; |
| 218 |
if (base_dir_slen) { |
| 219 |
fname_iter = memcpya(fname_iter, list_base_dir, base_dir_slen); |
| 220 |
} |
| 221 |
fname_iter = memcpya(fname_iter, first_token_start, first_token_slen); |
| 222 |
memcpy(fname_iter, psam_suffix, psam_blen); |
| 223 |
} else { |
| 224 |
const char* second_token_end = CurTokenEnd(second_token_start); |
| 225 |
const char* third_token_start = FirstNonTspace(second_token_end); |
| 226 |
if (unlikely(IsEolnKns(*third_token_start))) { |
| 227 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --pmerge-list has exactly two tokens; 1 or 3 expected.\n", line_idx); |
| 228 |
goto LoadPmergeList_ret_MALFORMED_INPUT_WW; |
| 229 |
} |
| 230 |
const char* third_token_end = CurTokenEnd(third_token_start); |
| 231 |
const char* fourth_token_start = FirstNonTspace(third_token_end); |
| 232 |
if (unlikely(!IsEolnKns(*fourth_token_start))) { |
| 233 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --pmerge-list has more than 3 tokens.\n", line_idx); |
| 234 |
goto LoadPmergeList_ret_MALFORMED_INPUT_WW; |
| 235 |
} |
| 236 |
const uint32_t second_token_slen = second_token_end - second_token_start; |
| 237 |
const uint32_t third_token_slen = third_token_end - third_token_start; |
| 238 |
if (unlikely((first_token_slen >= kPglFnamesize) || |
| 239 |
(second_token_slen >= kPglFnamesize) || |
| 240 |
(third_token_slen >= kPglFnamesize))) { |
| 241 |
logerrprintf("Error: Filename on line %" PRIuPTR " of --pmerge-list file is too long.\n", line_idx); |
| 242 |
goto LoadPmergeList_ret_INCONSISTENT_INPUT; |
| 243 |
} |
| 244 |
char* fname_iter; |
| 245 |
if (unlikely(bigstack_end_alloc_c(base_dir_slen * 3 + first_token_slen + second_token_slen + third_token_slen + 3, &fname_iter))) { |
| 246 |
goto LoadPmergeList_ret_NOMEM; |
| 247 |
} |
| 248 |
cur_entry->pgen_fname = fname_iter; |
| 249 |
if (base_dir_slen) { |
| 250 |
fname_iter = memcpya(fname_iter, list_base_dir, base_dir_slen); |
| 251 |
} |
| 252 |
fname_iter = memcpyax(fname_iter, first_token_start, first_token_slen, '\0'); |
| 253 |
cur_entry->pvar_fname = fname_iter; |
| 254 |
if (base_dir_slen) { |
| 255 |
fname_iter = memcpya(fname_iter, list_base_dir, base_dir_slen); |
| 256 |
} |
| 257 |
fname_iter = memcpyax(fname_iter, second_token_start, second_token_slen, '\0'); |
| 258 |
cur_entry->psam_fname = fname_iter; |
| 259 |
if (base_dir_slen) { |
| 260 |
fname_iter = memcpya(fname_iter, list_base_dir, base_dir_slen); |
| 261 |
} |
| 262 |
memcpyx(fname_iter, third_token_start, third_token_slen, '\0'); |
| 263 |
} |
| 264 |
} |
| 265 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 266 |
goto LoadPmergeList_ret_TSTREAM_FAIL; |
| 267 |
} |
| 268 |
const uintptr_t fileset_ct = main_fileset_present + line_idx; |
| 269 |
if (fileset_ct < 2) { |
| 270 |
logerrputs("Error: --pmerge-list requires at least two filesets to be specified.\n"); |
| 271 |
goto LoadPmergeList_ret_INCONSISTENT_INPUT; |
| 272 |
} |
| 273 |
*fileset_ctp = fileset_ct; |
| 274 |
logprintf("--pmerge-list: %" PRIuPTR " filesets specified%s.\n", fileset_ct, main_fileset_present? " (including main fileset)" : ""); |
| 275 |
} |
| 276 |
while (0) { |
| 277 |
LoadPmergeList_ret_NOMEM: |
| 278 |
reterr = kPglRetNomem; |
| 279 |
break; |
| 280 |
LoadPmergeList_ret_TSTREAM_FAIL: |
| 281 |
TextStreamErrPrint("--pmerge-list file", &txs); |
| 282 |
break; |
| 283 |
LoadPmergeList_ret_MALFORMED_INPUT_WW: |
| 284 |
WordWrapB(0); |
| 285 |
logerrputsb(); |
| 286 |
reterr = kPglRetMalformedInput; |
| 287 |
break; |
| 288 |
LoadPmergeList_ret_INCONSISTENT_INPUT: |
| 289 |
reterr = kPglRetInconsistentInput; |
| 290 |
break; |
| 291 |
} |
| 292 |
CleanupTextStream2(list_fname, &txs, &reterr); |
| 293 |
BigstackReset(bigstack_mark); |
| 294 |
return reterr; |
| 295 |
} |
| 296 |
|
| 297 |
// Permanent allocations are at end of bigstack. |
| 298 |
PglErr MergePsams(const PmergeInfo* pmip, const char* sample_sort_fname, const char* missing_catname, MiscFlags misc_flags, SortMode sample_sort_mode, FamCol fam_cols, int32_t missing_pheno, uint32_t max_thread_ct, char* outname, char* outname_end, PmergeInputFilesetLl* filesets, SampleIdInfo* siip, uint32_t* sample_ctp, uint32_t* linebuf_capacityp) { |
| 299 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 300 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 301 |
uintptr_t line_idx = 0; |
| 302 |
const char* cur_fname = nullptr; |
| 303 |
PglErr reterr = kPglRetSuccess; |
| 304 |
TextStream txs; |
| 305 |
PreinitTextStream(&txs); |
| 306 |
{ |
| 307 |
// First pass: determine sample IDs and phenotype set. |
| 308 |
// Intermission: sort sample and phenotype IDs. |
| 309 |
// Second pass: populate data structure, then call WritePsam(). |
| 310 |
|
| 311 |
// Allocate a single linebuf that's used in all first-pass loads, so that |
| 312 |
// we can have the pheno strset grow from bigstack_end down in an |
| 313 |
// unfragmented manner. |
| 314 |
uintptr_t linebuf_capacity = MINV(kMaxLongLine, bigstack_left() / 4) + kDecompressChunkSize; |
| 315 |
char* linebuf; |
| 316 |
if (unlikely(bigstack_end_alloc_c(linebuf_capacity, &linebuf))) { |
| 317 |
goto MergePsams_ret_NOMEM; |
| 318 |
} |
| 319 |
// If --sample-inner-join is specified, we append raw null-terminated |
| 320 |
// sample-ID strings to the bottom of bigstack while scanning the first |
| 321 |
// file, construct the usual non-resizable string-hash-table data structure |
| 322 |
// when we're done. Each ID then has a 0-based index, and we use |
| 323 |
// sample_include/cur_sample_include to track which sample IDs are present |
| 324 |
// in all files from that point on. |
| 325 |
// Otherwise, we add sample IDs to the resizable sample_id_strset data |
| 326 |
// structure and wait till we've processed all files before ordering the |
| 327 |
// elements. |
| 328 |
// Analogous thing happens for phenotype names if --pheno-inner-join is |
| 329 |
// specified. Phenotype-name data structure grows down from the top of |
| 330 |
// bigstack. |
| 331 |
const PmergeFlags flags = pmip->flags; |
| 332 |
char* first_sample_ids_start = nullptr; |
| 333 |
const char** first_sample_ids = nullptr; |
| 334 |
uint32_t* first_sample_ids_htable = nullptr; |
| 335 |
uintptr_t* sample_include = nullptr; |
| 336 |
uintptr_t* cur_sample_include = nullptr; |
| 337 |
char** sample_id_strset = nullptr; |
| 338 |
uint32_t first_sample_id_ct = 0; |
| 339 |
uint32_t sample_id_table_size = 512; |
| 340 |
if (flags & kfPmergeSampleInnerJoin) { |
| 341 |
first_sample_ids_start = R_CAST(char*, g_bigstack_base); |
| 342 |
// - arena_bottom tracks the current append point |
| 343 |
// - first_sample_ids, first_sample_ids_htable, sample_include, |
| 344 |
// cur_sample_include allocated after we're done scanning first file |
| 345 |
// - sample_id_table_size set to first_sample_ids_htable size at that |
| 346 |
// point |
| 347 |
} else { |
| 348 |
if (unlikely(bigstack_calloc_cp(sample_id_table_size, &sample_id_strset))) { |
| 349 |
goto MergePsams_ret_NOMEM; |
| 350 |
} |
| 351 |
} |
| 352 |
const char** first_pheno_names = nullptr; |
| 353 |
uint32_t* first_pheno_names_htable = nullptr; |
| 354 |
uintptr_t* pheno_include = nullptr; |
| 355 |
uintptr_t* cur_pheno_include = nullptr; |
| 356 |
char** pheno_strset = nullptr; |
| 357 |
uint32_t first_pheno_ct = 0; |
| 358 |
uint32_t pheno_names_table_size = 512; |
| 359 |
if (!(flags & kfPmergePhenoInnerJoin)) { |
| 360 |
if (unlikely(bigstack_end_calloc_cp(pheno_names_table_size, &pheno_strset))) { |
| 361 |
goto MergePsams_ret_NOMEM; |
| 362 |
} |
| 363 |
} |
| 364 |
unsigned char* arena_bottom = g_bigstack_base; |
| 365 |
unsigned char* arena_top = g_bigstack_end; |
| 366 |
|
| 367 |
const uint32_t decompress_thread_ct = MAXV(max_thread_ct - 1, 1); |
| 368 |
// possible todo: track seen realpaths, skip duplicates |
| 369 |
PmergeInputFilesetLl* filesets_iter = filesets; |
| 370 |
char* idbuf = g_textbuf; |
| 371 |
uint32_t max_line_blen = 0; |
| 372 |
uint32_t max_sample_id_blen_m2 = 2; |
| 373 |
uintptr_t max_sid_blen = 0; |
| 374 |
uintptr_t max_paternal_id_blen = 2; |
| 375 |
uintptr_t max_maternal_id_blen = 2; |
| 376 |
uintptr_t max_pheno_name_blen = 0; |
| 377 |
uint32_t sample_ct = 0; |
| 378 |
uint32_t pheno_ct = 0; |
| 379 |
do { |
| 380 |
cur_fname = filesets_iter->psam_fname; |
| 381 |
reterr = TextStreamOpenEx(cur_fname, kMaxLongLine, linebuf_capacity, decompress_thread_ct, nullptr, linebuf, &txs); |
| 382 |
if (unlikely(reterr)) { |
| 383 |
goto MergePsams_ret_TSTREAM_FAIL; |
| 384 |
} |
| 385 |
// Worth optimizing this more than most text-reading loops, since we may |
| 386 |
// be processing a LOT of files. |
| 387 |
const char* line_start = TextLineEnd(&txs); |
| 388 |
for (line_idx = 1; ; ++line_idx) { |
| 389 |
if (unlikely(!TextGetUnsafe2K(&txs, &line_start))) { |
| 390 |
if (TextStreamErrcode2(&txs, &reterr)) { |
| 391 |
goto MergePsams_ret_TSTREAM_FAIL; |
| 392 |
} |
| 393 |
logerrprintfww("Error: No samples in %s.\n", cur_fname); |
| 394 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 395 |
} |
| 396 |
if ((line_start[0] != '#') || tokequal_k(&(line_start[1]), "FID") || tokequal_k(&(line_start[1]), "IID")) { |
| 397 |
break; |
| 398 |
} |
| 399 |
const char* line_end = AdvPastDelim(line_start, '\n'); |
| 400 |
const uint32_t line_blen = line_end - line_start; |
| 401 |
if (max_line_blen < line_blen) { |
| 402 |
max_line_blen = line_blen; |
| 403 |
} |
| 404 |
line_start = line_end; |
| 405 |
} |
| 406 |
uint32_t sid_present = 0; |
| 407 |
uint32_t postid_pat_col_idx = 0; |
| 408 |
uint32_t postid_mat_col_idx = 0; |
| 409 |
uint32_t fid_present; |
| 410 |
if (line_start[0] == '#') { |
| 411 |
const char* iid_end = &(line_start[4]); |
| 412 |
fid_present = (line_start[1] == 'F'); |
| 413 |
if (fid_present) { |
| 414 |
const char* iid_start = FirstNonTspace(iid_end); |
| 415 |
iid_end = FirstPrechar(iid_start, 33); |
| 416 |
if (unlikely(!strequal_k(iid_start, "IID", iid_end - iid_start))) { |
| 417 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 418 |
} |
| 419 |
} |
| 420 |
const char* token_start = FirstNonTspace(iid_end); |
| 421 |
if (tokequal_k(token_start, "SID")) { |
| 422 |
sid_present = 1; |
| 423 |
token_start = FirstNonTspace(&(token_start[3])); |
| 424 |
} |
| 425 |
const char* token_end; |
| 426 |
for (uint32_t postid_col_idx = 1; !IsEolnKns(*token_start); token_start = FirstNonTspace(token_end), ++postid_col_idx) { |
| 427 |
token_end = CurTokenEnd(token_start); |
| 428 |
const uint32_t token_slen = token_end - token_start; |
| 429 |
if (token_slen == 3) { |
| 430 |
if (unlikely(memequal_sk(token_start, "FID"))) { |
| 431 |
if (fid_present) { |
| 432 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate FID column in %s.\n", cur_fname); |
| 433 |
} else { |
| 434 |
snprintf(g_logbuf, kLogbufSize, "Error: Improperly positioned FID column in %s (must be first).\n", cur_fname); |
| 435 |
} |
| 436 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 437 |
} |
| 438 |
if (unlikely(memequal_sk(token_start, "IID"))) { |
| 439 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate IID column in %s.\n", cur_fname); |
| 440 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 441 |
} |
| 442 |
if (unlikely(memequal_sk(token_start, "SID"))) { |
| 443 |
if (sid_present) { |
| 444 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate SID column in %s.\n", cur_fname); |
| 445 |
} else { |
| 446 |
snprintf(g_logbuf, kLogbufSize, "Error: Improperly positioned SID column in %s (must immediately follow IID).\n", cur_fname); |
| 447 |
} |
| 448 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 449 |
} |
| 450 |
if (memequal_sk(token_start, "PAT")) { |
| 451 |
if (unlikely(postid_pat_col_idx)) { |
| 452 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate PAT column in %s.\n", cur_fname); |
| 453 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 454 |
} |
| 455 |
postid_pat_col_idx = postid_col_idx; |
| 456 |
continue; |
| 457 |
} |
| 458 |
if (memequal_sk(token_start, "MAT")) { |
| 459 |
if (unlikely(postid_mat_col_idx)) { |
| 460 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate MAT column in %s.\n", cur_fname); |
| 461 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 462 |
} |
| 463 |
postid_mat_col_idx = postid_col_idx; |
| 464 |
continue; |
| 465 |
} |
| 466 |
if (memequal_sk(token_start, "SEX")) { |
| 467 |
continue; |
| 468 |
} |
| 469 |
} else if (token_slen > kMaxIdBlen) { |
| 470 |
logerrputs("Error: Phenotype names are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 471 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 472 |
} |
| 473 |
if (pheno_strset) { |
| 474 |
if (token_slen >= max_pheno_name_blen) { |
| 475 |
max_pheno_name_blen = token_slen + 1; |
| 476 |
} |
| 477 |
if (unlikely(StrsetAddEndResize(arena_bottom, token_start, token_slen, kMaxPhenoCt * 2, &pheno_strset, &pheno_names_table_size, &pheno_ct, &arena_top))) { |
| 478 |
if (pheno_ct == kMaxPhenoCt) { |
| 479 |
logerrputs("Error: " PROG_NAME_STR " does not support more than " MAX_PHENO_CT_STR " phenotypes.\n"); |
| 480 |
goto MergePsams_ret_INCONSISTENT_INPUT; |
| 481 |
} |
| 482 |
goto MergePsams_ret_NOMEM; |
| 483 |
} |
| 484 |
} else { |
| 485 |
// max_pheno_name_blen calculation deferred since any name may not |
| 486 |
// appear in a later file |
| 487 |
if (!first_pheno_names_htable) { |
| 488 |
// StoreStringAtEnd(), without dst assignment |
| 489 |
if (unlikely(PtrWSubCk(arena_bottom, token_slen + 1, &arena_top))) { |
| 490 |
goto MergePsams_ret_NOMEM; |
| 491 |
} |
| 492 |
memcpyx(arena_top, token_start, token_slen, '\0'); |
| 493 |
++first_pheno_ct; |
| 494 |
} else if (pheno_ct) { |
| 495 |
const uint32_t pheno_idx = IdHtableFindNnt(token_start, first_pheno_names, first_pheno_names_htable, token_slen, pheno_names_table_size); |
| 496 |
if (pheno_idx != UINT32_MAX) { |
| 497 |
if (unlikely(IsSet(cur_pheno_include, pheno_idx))) { |
| 498 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate phenotype name '%s' in %s.\n", first_pheno_names[pheno_idx], cur_fname); |
| 499 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 500 |
} |
| 501 |
SetBit(pheno_idx, cur_pheno_include); |
| 502 |
} |
| 503 |
} |
| 504 |
} |
| 505 |
} |
| 506 |
if ((!postid_pat_col_idx) != (!postid_mat_col_idx)) { |
| 507 |
snprintf(g_logbuf, kLogbufSize, "Error: %s has a '%cAT' column without a '%cAT' column; either both or neither must be present.\n", cur_fname, postid_pat_col_idx? 'P' : 'M', postid_pat_col_idx? 'M' : 'P'); |
| 508 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 509 |
} |
| 510 |
const char* line_end = AdvPastDelim(token_start, '\n'); |
| 511 |
const uint32_t line_blen = line_end - line_start; |
| 512 |
if (max_line_blen < line_blen) { |
| 513 |
max_line_blen = line_blen; |
| 514 |
} |
| 515 |
line_start = line_end; |
| 516 |
++line_idx; |
| 517 |
if (unlikely(!TextGetUnsafe2K(&txs, &line_start))) { |
| 518 |
if (TextStreamErrcode2(&txs, &reterr)) { |
| 519 |
goto MergePsams_ret_TSTREAM_FAIL; |
| 520 |
} |
| 521 |
logerrprintfww("Error: No samples in %s.\n", cur_fname); |
| 522 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 523 |
} |
| 524 |
} else { |
| 525 |
// .fam |
| 526 |
fid_present = (fam_cols / kfFamCol1) & 1; |
| 527 |
if (fam_cols & kfFamCol34) { |
| 528 |
postid_pat_col_idx = 1; |
| 529 |
postid_mat_col_idx = 2; |
| 530 |
} |
| 531 |
if (fam_cols & kfFamCol6) { |
| 532 |
if (pheno_strset) { |
| 533 |
if (unlikely(StrsetAddEndResize(arena_bottom, "PHENO1", strlen("PHENO1"), kMaxPhenoCt * 2, &pheno_strset, &pheno_names_table_size, &pheno_ct, &arena_top))) { |
| 534 |
if (pheno_ct == kMaxPhenoCt) { |
| 535 |
logerrputs("Error: " PROG_NAME_STR " does not support more than " MAX_PHENO_CT_STR " phenotypes.\n"); |
| 536 |
goto MergePsams_ret_INCONSISTENT_INPUT; |
| 537 |
} |
| 538 |
goto MergePsams_ret_NOMEM; |
| 539 |
} |
| 540 |
if (strlen("PHENO1") >= max_pheno_name_blen) { |
| 541 |
max_pheno_name_blen = strlen("PHENO1") + 1; |
| 542 |
} |
| 543 |
} else { |
| 544 |
if (!first_pheno_names_htable) { |
| 545 |
if (unlikely(PtrWSubCk(arena_bottom, strlen("PHENO1") + 1, &arena_top))) { |
| 546 |
goto MergePsams_ret_NOMEM; |
| 547 |
} |
| 548 |
strcpy_k(R_CAST(char*, arena_top), "PHENO1"); |
| 549 |
first_pheno_ct = 1; |
| 550 |
} else if (pheno_ct) { |
| 551 |
const uint32_t pheno_idx = IdHtableFind("PHENO1", TO_CONSTCPCONSTP(first_pheno_names), first_pheno_names_htable, strlen("PHENO1"), pheno_names_table_size); |
| 552 |
if (pheno_idx != UINT32_MAX) { |
| 553 |
SetBit(pheno_idx, cur_pheno_include); |
| 554 |
} |
| 555 |
} |
| 556 |
} |
| 557 |
} |
| 558 |
} |
| 559 |
uint32_t first_parent_postid_col_idx = postid_pat_col_idx; |
| 560 |
uint32_t parent_col_skip = postid_mat_col_idx - postid_pat_col_idx; |
| 561 |
uintptr_t first_parent_max_blen = max_paternal_id_blen; |
| 562 |
uintptr_t second_parent_max_blen = max_maternal_id_blen; |
| 563 |
if (postid_mat_col_idx < postid_pat_col_idx) { |
| 564 |
first_parent_postid_col_idx = postid_mat_col_idx; |
| 565 |
parent_col_skip = -parent_col_skip; |
| 566 |
first_parent_max_blen = max_maternal_id_blen; |
| 567 |
second_parent_max_blen = max_paternal_id_blen; |
| 568 |
} |
| 569 |
const char* fid_start = &(g_one_char_strs[96]); |
| 570 |
uint32_t fid_slen = 1; |
| 571 |
const char* sid_start = &(g_one_char_strs[96]); |
| 572 |
uint32_t sid_slen = 1; |
| 573 |
while (1) { |
| 574 |
const char* token_start = line_start; |
| 575 |
if (fid_present) { |
| 576 |
fid_start = line_start; |
| 577 |
const char* fid_end = CurTokenEnd(fid_start); |
| 578 |
fid_slen = fid_end - fid_start; |
| 579 |
token_start = FirstNonTspace(fid_end); |
| 580 |
if (unlikely(IsEolnKns(*token_start))) { |
| 581 |
goto MergePsams_ret_MISSING_TOKENS; |
| 582 |
} |
| 583 |
} |
| 584 |
const char* iid_start = token_start; |
| 585 |
const char* iid_end = CurTokenEnd(iid_start); |
| 586 |
const char* token_end = iid_end; |
| 587 |
const uint32_t iid_slen = iid_end - iid_start; |
| 588 |
if (sid_present) { |
| 589 |
sid_start = FirstNonTspace(iid_end); |
| 590 |
token_end = CurTokenEnd(sid_start); |
| 591 |
sid_slen = token_end - sid_start; |
| 592 |
if ((sid_slen > 1) || (sid_start[0] != '0')) { |
| 593 |
if (sid_slen >= max_sid_blen) { |
| 594 |
if (unlikely(sid_slen > kMaxIdBlen)) { |
| 595 |
logerrputs("Error: SIDs are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 596 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 597 |
} |
| 598 |
max_sid_blen = sid_slen + 1; |
| 599 |
} |
| 600 |
} |
| 601 |
} |
| 602 |
if (fid_slen + iid_slen > max_sample_id_blen_m2) { |
| 603 |
max_sample_id_blen_m2 = fid_slen + iid_slen; |
| 604 |
if (unlikely(max_sample_id_blen_m2 > 2 * kMaxIdSlen)) { |
| 605 |
logerrputs("Error: FIDs and IIDs are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 606 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 607 |
} |
| 608 |
} |
| 609 |
char* id_iter = memcpyax(idbuf, fid_start, fid_slen, '\t'); |
| 610 |
id_iter = memcpyax(id_iter, iid_start, iid_slen, '\t'); |
| 611 |
id_iter = memcpya(id_iter, sid_start, sid_slen); |
| 612 |
*id_iter = '\0'; |
| 613 |
const uint32_t id_slen = id_iter - idbuf; |
| 614 |
if (sample_id_strset) { |
| 615 |
if (unlikely(StrsetAddResize(arena_top, idbuf, id_slen, 2U * 0x7ffffffe, sample_id_strset, &sample_id_table_size, &sample_ct, &arena_bottom))) { |
| 616 |
if (sample_ct == kPglMaxSampleCt) { |
| 617 |
logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 2 samples.\n"); |
| 618 |
goto MergePsams_ret_INCONSISTENT_INPUT; |
| 619 |
} |
| 620 |
goto MergePsams_ret_NOMEM; |
| 621 |
} |
| 622 |
} else { |
| 623 |
if (!first_sample_ids_htable) { |
| 624 |
if (unlikely(id_slen >= S_CAST(uintptr_t, arena_top - arena_bottom))) { |
| 625 |
goto MergePsams_ret_NOMEM; |
| 626 |
} |
| 627 |
arena_bottom = memcpyua(arena_bottom, idbuf, id_slen + 1); |
| 628 |
if (unlikely(first_sample_id_ct == kPglMaxSampleCt)) { |
| 629 |
logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 2 samples.\n"); |
| 630 |
goto MergePsams_ret_INCONSISTENT_INPUT; |
| 631 |
} |
| 632 |
++first_sample_id_ct; |
| 633 |
} else { |
| 634 |
const uint32_t sample_idx = IdHtableFind(idbuf, first_sample_ids, first_sample_ids_htable, id_slen, sample_id_table_size); |
| 635 |
if (sample_idx != UINT32_MAX) { |
| 636 |
if (unlikely(IsSet(cur_sample_include, sample_idx))) { |
| 637 |
TabsToSpaces(idbuf); |
| 638 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in %s.\n", idbuf, cur_fname); |
| 639 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 640 |
} |
| 641 |
SetBit(sample_idx, cur_sample_include); |
| 642 |
} |
| 643 |
} |
| 644 |
} |
| 645 |
if (first_parent_postid_col_idx) { |
| 646 |
const char* first_parent_start = NextTokenMult(token_end, first_parent_postid_col_idx); |
| 647 |
if (unlikely(!first_parent_start)) { |
| 648 |
goto MergePsams_ret_MISSING_TOKENS; |
| 649 |
} |
| 650 |
const char* first_parent_end = CurTokenEnd(first_parent_start); |
| 651 |
const uintptr_t first_parent_slen = first_parent_end - first_parent_start; |
| 652 |
if (first_parent_slen >= first_parent_max_blen) { |
| 653 |
if (unlikely(first_parent_slen > kMaxIdSlen)) { |
| 654 |
logerrputs("Error: FIDs and IIDs are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 655 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 656 |
} |
| 657 |
first_parent_max_blen = first_parent_slen + 1; |
| 658 |
} |
| 659 |
const char* second_parent_start = NextTokenMult(first_parent_end, parent_col_skip); |
| 660 |
if (unlikely(!second_parent_start)) { |
| 661 |
goto MergePsams_ret_MISSING_TOKENS; |
| 662 |
} |
| 663 |
token_end = CurTokenEnd(second_parent_start); |
| 664 |
const uintptr_t second_parent_slen = token_end - second_parent_start; |
| 665 |
if (second_parent_slen >= second_parent_max_blen) { |
| 666 |
if (unlikely(second_parent_slen > kMaxIdSlen)) { |
| 667 |
logerrputs("Error: FIDs and IIDs are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 668 |
goto MergePsams_ret_MALFORMED_INPUT; |
| 669 |
} |
| 670 |
second_parent_max_blen = second_parent_slen + 1; |
| 671 |
} |
| 672 |
} |
| 673 |
const char* line_end = AdvPastDelim(token_end, '\n'); |
| 674 |
const uint32_t line_blen = line_end - line_start; |
| 675 |
if (max_line_blen < line_blen) { |
| 676 |
max_line_blen = line_blen; |
| 677 |
} |
| 678 |
line_start = line_end; |
| 679 |
++line_idx; |
| 680 |
if (!TextGetUnsafe2K(&txs, &line_start)) { |
| 681 |
break; |
| 682 |
} |
| 683 |
if (unlikely(line_start[0] == '#')) { |
| 684 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and if a #FID/IID header line is present it must denote the end of the header block.)\n", line_idx, cur_fname); |
| 685 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 686 |
} |
| 687 |
} |
| 688 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 689 |
goto MergePsams_ret_TSTREAM_FAIL; |
| 690 |
} |
| 691 |
if (unlikely(CleanupTextStream2(cur_fname, &txs, &reterr))) { |
| 692 |
goto MergePsams_ret_1; |
| 693 |
} |
| 694 |
if (postid_pat_col_idx) { |
| 695 |
if (postid_mat_col_idx > postid_pat_col_idx) { |
| 696 |
max_paternal_id_blen = first_parent_max_blen; |
| 697 |
max_maternal_id_blen = second_parent_max_blen; |
| 698 |
} else { |
| 699 |
max_paternal_id_blen = second_parent_max_blen; |
| 700 |
max_maternal_id_blen = first_parent_max_blen; |
| 701 |
} |
| 702 |
} |
| 703 |
if (first_sample_ids_start) { |
| 704 |
const uint32_t first_sample_ctl = BitCtToWordCt(first_sample_id_ct); |
| 705 |
if (filesets_iter == filesets) { |
| 706 |
ArenaBaseSet(arena_bottom, &arena_bottom); |
| 707 |
sample_id_table_size = GetHtableFastSize(first_sample_id_ct); |
| 708 |
if (unlikely((arena_bottom > arena_top) || |
| 709 |
arena_alloc_kcp(arena_top, first_sample_id_ct, &arena_bottom, &first_sample_ids) || |
| 710 |
arena_alloc_u32(arena_top, sample_id_table_size, &arena_bottom, &first_sample_ids_htable) || |
| 711 |
arena_alloc_w(arena_top, first_sample_ctl, &arena_bottom, &sample_include) || |
| 712 |
arena_alloc_w(arena_top, first_sample_ctl, &arena_bottom, &cur_sample_include))) { |
| 713 |
goto MergePsams_ret_NOMEM; |
| 714 |
} |
| 715 |
SetAllU32Arr(sample_id_table_size, first_sample_ids_htable); |
| 716 |
SetAllBits(first_sample_id_ct, sample_include); |
| 717 |
const char* first_sample_ids_iter = first_sample_ids_start; |
| 718 |
for (uint32_t sample_idx = 0; sample_idx != first_sample_id_ct; ++sample_idx) { |
| 719 |
first_sample_ids[sample_idx] = first_sample_ids_iter; |
| 720 |
const uint32_t slen = strlen(first_sample_ids_iter); |
| 721 |
if (unlikely(IdHtableAdd(first_sample_ids_iter, first_sample_ids, slen, sample_id_table_size, sample_idx, first_sample_ids_htable) != UINT32_MAX)) { |
| 722 |
char* mutable_id = K_CAST(char*, first_sample_ids_iter); |
| 723 |
TabsToSpaces(mutable_id); |
| 724 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in %s.\n", mutable_id, cur_fname); |
| 725 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 726 |
} |
| 727 |
first_sample_ids_iter = &(first_sample_ids_iter[slen + 1]); |
| 728 |
} |
| 729 |
} else { |
| 730 |
BitvecAnd(cur_sample_include, first_sample_ctl, sample_include); |
| 731 |
if (unlikely(AllWordsAreZero(sample_include, first_sample_ctl))) { |
| 732 |
snprintf(g_logbuf, kLogbufSize, "Error: No common samples in --pmerge%s --sample-inner-join job.\n", pmip->list_fname? "-list" : ""); |
| 733 |
goto MergePsams_ret_MALFORMED_INPUT_2; |
| 734 |
} |
| 735 |
} |
| 736 |
ZeroWArr(first_sample_ctl, cur_sample_include); |
| 737 |
} |
| 738 |
if (!pheno_strset) { |
| 739 |
const uint32_t first_pheno_ctl = BitCtToWordCt(first_pheno_ct); |
| 740 |
if (filesets_iter == filesets) { |
| 741 |
// must handle pheno_ct == 0 |
| 742 |
// (only really need to set first_pheno_names_htable to non-null in |
| 743 |
// that case, since that's how we currently recognize we aren't |
| 744 |
// processing the first .psam file) |
| 745 |
const char* pheno_names_iter = R_CAST(char*, arena_top); |
| 746 |
ArenaEndSet(arena_top, &arena_top); |
| 747 |
pheno_names_table_size = GetHtableFastSize(first_pheno_ct); |
| 748 |
if (unlikely(arena_end_alloc_kcp(arena_bottom, first_pheno_ct, &arena_top, &first_pheno_names) || |
| 749 |
arena_end_alloc_u32(arena_bottom, pheno_names_table_size, &arena_top, &first_pheno_names_htable) || |
| 750 |
arena_end_alloc_w(arena_bottom, first_pheno_ctl, &arena_top, &pheno_include) || |
| 751 |
arena_end_alloc_w(arena_bottom, first_pheno_ctl, &arena_top, &cur_pheno_include))) { |
| 752 |
goto MergePsams_ret_NOMEM; |
| 753 |
} |
| 754 |
SetAllU32Arr(pheno_names_table_size, first_pheno_names_htable); |
| 755 |
SetAllBits(first_pheno_ct, pheno_include); |
| 756 |
ZeroWArr(first_pheno_ctl, cur_pheno_include); |
| 757 |
pheno_ct = first_pheno_ct; |
| 758 |
for (uint32_t pheno_idx = 0; pheno_idx != first_pheno_ct; ++pheno_idx) { |
| 759 |
first_pheno_names[pheno_idx] = pheno_names_iter; |
| 760 |
const uint32_t slen = strlen(pheno_names_iter); |
| 761 |
if (unlikely(IdHtableAdd(pheno_names_iter, first_pheno_names, slen, pheno_names_table_size, pheno_idx, first_pheno_names_htable) != UINT32_MAX)) { |
| 762 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate phenotype name '%s' in %s.\n", pheno_names_iter, cur_fname); |
| 763 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 764 |
} |
| 765 |
pheno_names_iter = &(pheno_names_iter[slen + 1]); |
| 766 |
} |
| 767 |
} else if (pheno_ct) { |
| 768 |
BitvecAnd(cur_pheno_include, first_pheno_ctl, pheno_include); |
| 769 |
pheno_ct = PopcountWords(pheno_include, first_pheno_ctl); |
| 770 |
ZeroWArr(first_pheno_ctl, cur_pheno_include); |
| 771 |
} |
| 772 |
} |
| 773 |
filesets_iter = filesets_iter->next; |
| 774 |
} while (filesets_iter); |
| 775 |
// Intermission: |
| 776 |
// 1. Move final set of phenotype ID strings to bottom, compute |
| 777 |
// max_pheno_name_blen if --pheno-inner-join. |
| 778 |
// 2. Compute max_sample_id_blen and max_sid_blen if --sample-inner-join. |
| 779 |
// 3. Free all end-of-bigstack allocations. |
| 780 |
// 4. Construct SampleIdInfo at end of bigstack, to be returned. |
| 781 |
// 5. Construct pheno_names, hash tables. |
| 782 |
char* pheno_names = nullptr; |
| 783 |
uint32_t* pheno_names_htable = nullptr; |
| 784 |
uint32_t* sample_id_htable; |
| 785 |
uintptr_t max_sample_id_blen; |
| 786 |
uint32_t sample_ctl; |
| 787 |
{ |
| 788 |
char* pheno_names_tmp_start = R_CAST(char*, arena_bottom); |
| 789 |
char* pheno_names_tmp_end; |
| 790 |
if (pheno_strset) { |
| 791 |
const uintptr_t byte_ct = R_CAST(unsigned char*, pheno_strset) - arena_top; |
| 792 |
memmove(pheno_names_tmp_start, arena_top, byte_ct); |
| 793 |
pheno_names_tmp_end = &(pheno_names_tmp_start[byte_ct]); |
| 794 |
} else { |
| 795 |
max_pheno_name_blen = 0; |
| 796 |
char* pheno_names_write_iter = pheno_names_tmp_start; |
| 797 |
if (pheno_ct) { |
| 798 |
if (S_CAST(uintptr_t, first_pheno_names[0] - pheno_names_write_iter) < kMaxIdBlen) { |
| 799 |
// ensure memcpy is safe |
| 800 |
goto MergePsams_ret_NOMEM; |
| 801 |
} |
| 802 |
uintptr_t pheno_uidx_base = 0; |
| 803 |
uintptr_t cur_bits = pheno_include[0]; |
| 804 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 805 |
const uint32_t pheno_uidx = BitIter1(pheno_include, &pheno_uidx_base, &cur_bits); |
| 806 |
const char* cur_pheno_name = first_pheno_names[pheno_uidx]; |
| 807 |
const uint32_t blen = 1 + strlen(cur_pheno_name); |
| 808 |
if (blen > max_pheno_name_blen) { |
| 809 |
max_pheno_name_blen = blen; |
| 810 |
} |
| 811 |
pheno_names_write_iter = memcpya(pheno_names_write_iter, cur_pheno_name, blen); |
| 812 |
} |
| 813 |
} |
| 814 |
pheno_names_tmp_end = pheno_names_write_iter; |
| 815 |
} |
| 816 |
BigstackBaseSet(pheno_names_tmp_end); |
| 817 |
|
| 818 |
if (sample_id_strset) { |
| 819 |
max_sample_id_blen = max_sample_id_blen_m2 + 2; |
| 820 |
} else { |
| 821 |
const uint32_t first_sample_ctl = BitCtToWordCt(first_sample_id_ct); |
| 822 |
sample_ct = PopcountWords(sample_include, first_sample_ctl); |
| 823 |
max_sample_id_blen = 4; |
| 824 |
max_sid_blen = 0; |
| 825 |
uintptr_t sample_uidx_base = 0; |
| 826 |
uintptr_t cur_bits = sample_include[0]; |
| 827 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 828 |
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 829 |
const char* cur_sample_id = first_sample_ids[sample_uidx]; |
| 830 |
const char* iid_end = AdvToDelim(AdvPastDelim(cur_sample_id, '\t'), '\t'); |
| 831 |
const uint32_t sample_id_blen_m1 = iid_end - cur_sample_id; |
| 832 |
if (max_sample_id_blen <= sample_id_blen_m1) { |
| 833 |
max_sample_id_blen = sample_id_blen_m1 + 1; |
| 834 |
} |
| 835 |
const char* sid_start = &(iid_end[1]); |
| 836 |
const uint32_t sid_slen = strlen(sid_start); |
| 837 |
if ((sid_slen > 1) || (sid_start[0] != '0')) { |
| 838 |
if (max_sid_blen <= sid_slen) { |
| 839 |
max_sid_blen = sid_slen + 1; |
| 840 |
} |
| 841 |
} |
| 842 |
} |
| 843 |
} |
| 844 |
// defensive |
| 845 |
linebuf = nullptr; |
| 846 |
first_pheno_names = nullptr; |
| 847 |
first_pheno_names_htable = nullptr; |
| 848 |
pheno_include = nullptr; |
| 849 |
cur_pheno_include = nullptr; |
| 850 |
pheno_strset = nullptr; |
| 851 |
|
| 852 |
sample_ctl = BitCtToWordCt(sample_ct); |
| 853 |
siip->flags = kfSampleIdFidPresent | kfSampleIdParentsPresent; |
| 854 |
if (misc_flags & kfMiscStrictSid0) { |
| 855 |
// affects --indiv-sort |
| 856 |
siip->flags |= kfSampleIdStrictSid0; |
| 857 |
} |
| 858 |
siip->max_sample_id_blen = max_sample_id_blen; |
| 859 |
siip->max_sid_blen = max_sid_blen; |
| 860 |
siip->sids = nullptr; |
| 861 |
if (max_sid_blen) { |
| 862 |
if (unlikely(bigstack_end_alloc_c(max_sid_blen * sample_ct, &(siip->sids)))) { |
| 863 |
goto MergePsams_ret_NOMEM; |
| 864 |
} |
| 865 |
} |
| 866 |
// place this below optional siip->sids, so that |
| 867 |
// BigstackEndSet(siip->sample_ids) is always correct on success |
| 868 |
if (unlikely(bigstack_end_alloc_c(max_sample_id_blen * sample_ct, &(siip->sample_ids)))) { |
| 869 |
goto MergePsams_ret_NOMEM; |
| 870 |
} |
| 871 |
if (pheno_ct) { |
| 872 |
pheno_names_table_size = GetHtableFastSize(pheno_ct); |
| 873 |
if (unlikely(bigstack_end_alloc_c(max_pheno_name_blen * pheno_ct, &pheno_names) || |
| 874 |
bigstack_end_alloc_u32(pheno_names_table_size, &pheno_names_htable))) { |
| 875 |
goto MergePsams_ret_NOMEM; |
| 876 |
} |
| 877 |
} |
| 878 |
|
| 879 |
char* sample_ids_write_iter = siip->sample_ids; |
| 880 |
if (sample_id_strset) { |
| 881 |
const char* sample_ids_read_iter = R_CAST(char*, &(sample_id_strset[sample_id_table_size])); |
| 882 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 883 |
const char* iid_end = AdvToDelim(AdvPastDelim(sample_ids_read_iter, '\t'), '\t'); |
| 884 |
memcpyx(sample_ids_write_iter, sample_ids_read_iter, iid_end - sample_ids_read_iter, '\0'); |
| 885 |
sample_ids_write_iter = &(sample_ids_write_iter[max_sample_id_blen]); |
| 886 |
const char* sid_end = strnul(iid_end); |
| 887 |
if (max_sid_blen) { |
| 888 |
const uint32_t sid_blen = sid_end - iid_end; |
| 889 |
const char* sid_start = &(iid_end[1]); |
| 890 |
memcpy(&(siip->sids[sample_idx * max_sid_blen]), sid_start, sid_blen); |
| 891 |
} |
| 892 |
sample_ids_read_iter = &(sid_end[1]); |
| 893 |
} |
| 894 |
} else { |
| 895 |
uintptr_t sample_uidx_base = 0; |
| 896 |
uintptr_t cur_bits = sample_include[0]; |
| 897 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 898 |
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 899 |
const char* cur_sample_id = first_sample_ids[sample_uidx]; |
| 900 |
const char* iid_end = AdvToDelim(AdvPastDelim(cur_sample_id, '\t'), '\t'); |
| 901 |
memcpyx(sample_ids_write_iter, cur_sample_id, iid_end - cur_sample_id, '\0'); |
| 902 |
sample_ids_write_iter = &(sample_ids_write_iter[max_sample_id_blen]); |
| 903 |
if (max_sid_blen) { |
| 904 |
const char* sid_start = &(iid_end[1]); |
| 905 |
strcpy(&(siip->sids[sample_idx * max_sid_blen]), sid_start); |
| 906 |
} |
| 907 |
} |
| 908 |
} |
| 909 |
|
| 910 |
// defensive |
| 911 |
first_sample_ids_start = nullptr; |
| 912 |
first_sample_ids = nullptr; |
| 913 |
first_sample_ids_htable = nullptr; |
| 914 |
sample_include = nullptr; |
| 915 |
sample_id_strset = nullptr; |
| 916 |
g_bigstack_base = bigstack_mark; |
| 917 |
|
| 918 |
if (pheno_ct) { |
| 919 |
const char* pheno_names_read_iter = pheno_names_tmp_start; |
| 920 |
// phenotypes are stored in reverse |
| 921 |
char* pheno_names_write_iter = &(pheno_names[pheno_ct * max_pheno_name_blen]); |
| 922 |
for (uint32_t pheno_idx = pheno_ct; pheno_idx; ) { |
| 923 |
--pheno_idx; |
| 924 |
pheno_names_write_iter -= max_pheno_name_blen; |
| 925 |
const uint32_t slen = strlen(pheno_names_read_iter); |
| 926 |
memcpy(pheno_names_write_iter, pheno_names_read_iter, slen + 1); |
| 927 |
pheno_names_read_iter = &(pheno_names_read_iter[slen + 1]); |
| 928 |
} |
| 929 |
const SortMode pheno_sort_mode = pmip->merge_pheno_sort; |
| 930 |
if (pheno_sort_mode == kSortAscii) { |
| 931 |
qsort(pheno_names, pheno_ct, max_pheno_name_blen, strcmp_overread_casted); |
| 932 |
} else if (pheno_sort_mode == kSortNatural) { |
| 933 |
qsort(pheno_names, pheno_ct, max_pheno_name_blen, strcmp_natural); |
| 934 |
} |
| 935 |
|
| 936 |
SetAllU32Arr(pheno_names_table_size, pheno_names_htable); |
| 937 |
pheno_names_read_iter = pheno_names; |
| 938 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 939 |
const uint32_t slen = strlen(pheno_names_read_iter); |
| 940 |
HtableAddNondup(pheno_names_read_iter, slen, pheno_names_table_size, pheno_idx, pheno_names_htable); |
| 941 |
pheno_names_read_iter = &(pheno_names_read_iter[max_pheno_name_blen]); |
| 942 |
} |
| 943 |
} |
| 944 |
|
| 945 |
if (unlikely(bigstack_alloc_w(sample_ctl, &sample_include))) { |
| 946 |
goto MergePsams_ret_NOMEM; |
| 947 |
} |
| 948 |
SetAllBits(sample_ct, sample_include); |
| 949 |
char* sample_ids = siip->sample_ids; |
| 950 |
char* sids = siip->sids; |
| 951 |
if (sample_sort_mode != kSortNone) { |
| 952 |
if (sample_sort_mode == kSortFile) { |
| 953 |
// yes, this is a bit circuitous |
| 954 |
unsigned char* bigstack_end_mark2 = g_bigstack_end; |
| 955 |
uint32_t* new_sample_idx_to_old; |
| 956 |
char* sample_ids_tmp; |
| 957 |
if (unlikely(bigstack_end_alloc_u32(sample_ct, &new_sample_idx_to_old) || |
| 958 |
bigstack_end_alloc_c(sample_ct * max_sample_id_blen, &sample_ids_tmp))) { |
| 959 |
goto MergePsams_ret_NOMEM; |
| 960 |
} |
| 961 |
char* sids_tmp = nullptr; |
| 962 |
if (max_sid_blen) { |
| 963 |
if (unlikely(bigstack_end_alloc_c(sample_ct * max_sid_blen, &sids_tmp))) { |
| 964 |
goto MergePsams_ret_NOMEM; |
| 965 |
} |
| 966 |
} |
| 967 |
reterr = SampleSortFileMap(sample_include, siip, sample_sort_fname, sample_ct, sample_ct, &new_sample_idx_to_old); |
| 968 |
if (unlikely(reterr)) { |
| 969 |
goto MergePsams_ret_1; |
| 970 |
} |
| 971 |
char* new_sample_ids_iter = sample_ids_tmp; |
| 972 |
char* new_sids_iter = sids_tmp; |
| 973 |
for (uint32_t new_idx = 0; new_idx != sample_ct; ++new_idx) { |
| 974 |
const uint32_t old_idx = new_sample_idx_to_old[new_idx]; |
| 975 |
strcpy(new_sample_ids_iter, &(sample_ids[old_idx * max_sample_id_blen])); |
| 976 |
new_sample_ids_iter = &(new_sample_ids_iter[max_sample_id_blen]); |
| 977 |
if (sids) { |
| 978 |
strcpy(new_sids_iter, &(sids[old_idx * max_sid_blen])); |
| 979 |
new_sids_iter = &(new_sids_iter[max_sid_blen]); |
| 980 |
} |
| 981 |
} |
| 982 |
memcpy(sample_ids, sample_ids_tmp, sample_ct * max_sample_id_blen); |
| 983 |
if (sids) { |
| 984 |
memcpy(sids, sids_tmp, sample_ct * max_sid_blen); |
| 985 |
} |
| 986 |
BigstackEndReset(bigstack_end_mark2); |
| 987 |
} else if (sample_sort_mode == kSortAscii) { |
| 988 |
qsort(siip->sample_ids, sample_ct, max_sample_id_blen, strcmp_overread_casted); |
| 989 |
} else { |
| 990 |
// natural-sort, even if sample_sort_mode == kSort0 |
| 991 |
qsort(siip->sample_ids, sample_ct, max_sample_id_blen, strcmp_natural); |
| 992 |
} |
| 993 |
} |
| 994 |
|
| 995 |
sample_id_table_size = GetHtableFastSize(sample_ct); |
| 996 |
if (unlikely(bigstack_alloc_u32(sample_id_table_size, &sample_id_htable))) { |
| 997 |
goto MergePsams_ret_NOMEM; |
| 998 |
} |
| 999 |
InitXidHtable(siip, sample_ct, sample_id_table_size, sample_id_htable, idbuf); |
| 1000 |
} |
| 1001 |
linebuf_capacity = MAXV(max_line_blen, kDecompressMinBlen) + kDecompressChunkSize; |
| 1002 |
*linebuf_capacityp = linebuf_capacity; |
| 1003 |
// max_{p,m}aternal_id_blen may be overestimated in --sample-inner-join |
| 1004 |
// case, but that's harmless since we free this strbox soon enough |
| 1005 |
ParentalIdInfo parental_id_info; |
| 1006 |
uintptr_t* sex_nm; |
| 1007 |
uintptr_t* sex_male; |
| 1008 |
if (unlikely(bigstack_alloc_c(sample_ct * max_paternal_id_blen, &parental_id_info.paternal_ids) || |
| 1009 |
bigstack_alloc_c(sample_ct * max_maternal_id_blen, &parental_id_info.maternal_ids) || |
| 1010 |
bigstack_calloc_w(sample_ctl, &sex_nm) || |
| 1011 |
bigstack_calloc_w(sample_ctl, &sex_male))) { |
| 1012 |
goto MergePsams_ret_NOMEM; |
| 1013 |
} |
| 1014 |
{ |
| 1015 |
char* paternal_ids_iter = parental_id_info.paternal_ids; |
| 1016 |
char* maternal_ids_iter = parental_id_info.maternal_ids; |
| 1017 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 1018 |
strcpy_k(paternal_ids_iter, "0"); |
| 1019 |
paternal_ids_iter = &(paternal_ids_iter[max_paternal_id_blen]); |
| 1020 |
strcpy_k(maternal_ids_iter, "0"); |
| 1021 |
maternal_ids_iter = &(maternal_ids_iter[max_maternal_id_blen]); |
| 1022 |
} |
| 1023 |
} |
| 1024 |
parental_id_info.max_paternal_id_blen = max_paternal_id_blen; |
| 1025 |
parental_id_info.max_maternal_id_blen = max_maternal_id_blen; |
| 1026 |
|
| 1027 |
// unlike core pheno_cols, this just lives on bigstack |
| 1028 |
PhenoCol* pheno_cols = nullptr; |
| 1029 |
|
| 1030 |
if (pheno_ct) { |
| 1031 |
if (unlikely(BIGSTACK_ALLOC_X(PhenoCol, pheno_ct, &pheno_cols))) { |
| 1032 |
goto MergePsams_ret_NOMEM; |
| 1033 |
} |
| 1034 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 1035 |
// we don't really distinguish between case/control and quantitative |
| 1036 |
// phenotypes here (just use data.qt in both cases), and it should be |
| 1037 |
// ok to overallocate a bit in the categorical-phenotype case |
| 1038 |
if (unlikely(bigstack_calloc_w(sample_ctl, &(pheno_cols[pheno_idx].nonmiss)) || |
| 1039 |
bigstack_alloc_d(sample_ct, &(pheno_cols[pheno_idx].data.qt)))) { |
| 1040 |
goto MergePsams_ret_NOMEM; |
| 1041 |
} |
| 1042 |
// We use kPhenoDtypeCc instead of kPhenoTypeOther to indicate "type |
| 1043 |
// not yet known", since that lets us leave it unchanged if all values |
| 1044 |
// are missing. |
| 1045 |
pheno_cols[pheno_idx].type_code = kPhenoDtypeCc; |
| 1046 |
// defensive, nonnull_category_ct is ignored by WritePsam() except in |
| 1047 |
// the 'SEX' phenotype case which can't happen here |
| 1048 |
pheno_cols[pheno_idx].category_names = nullptr; |
| 1049 |
pheno_cols[pheno_idx].nonnull_category_ct = 0; |
| 1050 |
} |
| 1051 |
} |
| 1052 |
unsigned char* bigstack_mark2 = g_bigstack_base; |
| 1053 |
const uint32_t kNonphenoPostIdColCt = 3; |
| 1054 |
const uint32_t max_col_ct = pheno_ct + kNonphenoPostIdColCt; |
| 1055 |
// note that ZeroWArr(pheno_ctl, pheno_include) is safe when pheno_ct == 0 |
| 1056 |
const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct); |
| 1057 |
const double missing_phenod = missing_pheno? S_CAST(double, missing_pheno) : HUGE_VAL; |
| 1058 |
uint32_t* col_skips; |
| 1059 |
uint32_t* col_types; |
| 1060 |
const char** token_ptrs; |
| 1061 |
uint32_t* token_slens; |
| 1062 |
if (unlikely(bigstack_alloc_u32(max_col_ct, &col_skips) || |
| 1063 |
bigstack_alloc_u32(max_col_ct, &col_types) || |
| 1064 |
bigstack_alloc_kcp(max_col_ct, &token_ptrs) || |
| 1065 |
bigstack_alloc_u32(max_col_ct, &token_slens) || |
| 1066 |
bigstack_alloc_w(pheno_ctl, &pheno_include) || |
| 1067 |
bigstack_alloc_c(linebuf_capacity, &linebuf))) { |
| 1068 |
goto MergePsams_ret_NOMEM; |
| 1069 |
} |
| 1070 |
// bugfix (22 Mar 2022): We've only checked for duplicate sample IDs in the |
| 1071 |
// --sample-inner-join case. The current implementation does not support |
| 1072 |
// them, so we must error out in the non-sample-inner-join case too. |
| 1073 |
// |
| 1074 |
// We may want to support duplicate sample IDs here in the future; they are |
| 1075 |
// supported by plink 1.x merge, after all, and the online documentation |
| 1076 |
// even explicitly recommends merging a dataset with itself in one |
| 1077 |
// scenario. (If we do, it should work regardless of --sample-inner-join |
| 1078 |
// state.) |
| 1079 |
cur_sample_include = nullptr; |
| 1080 |
if (!(flags & kfPmergeSampleInnerJoin)) { |
| 1081 |
if (unlikely(bigstack_alloc_w(sample_ctl, &cur_sample_include))) { |
| 1082 |
goto MergePsams_ret_NOMEM; |
| 1083 |
} |
| 1084 |
} |
| 1085 |
// sample-major, PAT before MAT |
| 1086 |
const MergePhenoMode merge_parents_mode = pmip->merge_parents_mode; |
| 1087 |
uintptr_t* parents_locked = nullptr; |
| 1088 |
if (merge_parents_mode != kMergePhenoModeNmFirst) { |
| 1089 |
if (unlikely(bigstack_calloc_w(BitCtToWordCt(2 * sample_ct), &parents_locked))) { |
| 1090 |
goto MergePsams_ret_NOMEM; |
| 1091 |
} |
| 1092 |
} |
| 1093 |
const MergePhenoMode merge_sex_mode = pmip->merge_sex_mode; |
| 1094 |
uintptr_t* sex_locked = nullptr; |
| 1095 |
if (merge_sex_mode != kMergePhenoModeNmFirst) { |
| 1096 |
if (unlikely(bigstack_calloc_w(sample_ctl, &sex_locked))) { |
| 1097 |
goto MergePsams_ret_NOMEM; |
| 1098 |
} |
| 1099 |
} |
| 1100 |
// phenotype-major |
| 1101 |
const MergePhenoMode merge_pheno_mode = pmip->merge_pheno_mode; |
| 1102 |
uintptr_t* pheno_locked = nullptr; |
| 1103 |
if (pheno_ct && (merge_pheno_mode != kMergePhenoModeNmFirst)) { |
| 1104 |
// no need to check for overflow in 32-bit case since we would have |
| 1105 |
// already run out of memory on data.qt allocations |
| 1106 |
const uintptr_t bit_ct = S_CAST(uintptr_t, pheno_ct) * sample_ct; |
| 1107 |
if (unlikely(bigstack_calloc_w(BitCtToWordCt(bit_ct), &pheno_locked))) { |
| 1108 |
goto MergePsams_ret_NOMEM; |
| 1109 |
} |
| 1110 |
} |
| 1111 |
// When --1 isn't specified, we need to be careful when interpreting |
| 1112 |
// zeroes: if the phenotype winds up being quantitative, zero is a regular |
| 1113 |
// value, but if it's binary, it's a missing value. |
| 1114 |
// Except in the trivial "--merge-pheno-mode first" case, we treat it as a |
| 1115 |
// missing value during the main pass, but set the relevant pheno_zero_seen |
| 1116 |
// bit if that phenotype cell isn't locked yet. |
| 1117 |
// We then correct the final phenotype values at the end, when we know |
| 1118 |
// whether each column will appear to be binary or quantitative in the |
| 1119 |
// merged .psam. |
| 1120 |
// Note that it is possible for a quantitative column to degrade to a |
| 1121 |
// binary column due to e.g. conflicts knocking out all values not in {-9, |
| 1122 |
// 0, 1, 2}. There isn't much we can do about that here, though. |
| 1123 |
const uint32_t affection_01 = (misc_flags / kfMiscAffection01) & 1; |
| 1124 |
uintptr_t* pheno_zero_seen = nullptr; |
| 1125 |
if (pheno_ct && (!affection_01) && (merge_pheno_mode != kMergePhenoModeFirst)) { |
| 1126 |
const uintptr_t bit_ct = S_CAST(uintptr_t, pheno_ct) * sample_ct; |
| 1127 |
if (unlikely(bigstack_calloc_w(BitCtToWordCt(bit_ct), &pheno_zero_seen))) { |
| 1128 |
goto MergePsams_ret_NOMEM; |
| 1129 |
} |
| 1130 |
} |
| 1131 |
|
| 1132 |
if (pheno_ct) { |
| 1133 |
logprintf("--pmerge%s: %u sample%s and %u phenotype%s present.\n", pmip->list_fname? "-list" : "", sample_ct, (sample_ct == 1)? "" : "s", pheno_ct, (pheno_ct == 1)? "" : "s"); |
| 1134 |
} else { |
| 1135 |
logprintf("--pmerge%s: %u sample%s present.\n", pmip->list_fname? "-list" : "", sample_ct, (sample_ct == 1)? "" : "s"); |
| 1136 |
} |
| 1137 |
// [category_names] [category_names_htable] [strings] |
| 1138 |
// ^ ^ ^ ^ |
| 1139 |
// | | | | |
| 1140 |
// g_bigstack_base arena_bottom arena_top g_bigstack_end |
| 1141 |
// |
| 1142 |
// category-name strings are allocated at the end of bigstack, and need to |
| 1143 |
// remain allocated until WritePsam() returns. |
| 1144 |
// category_names_htable is repositioned, resized, and rebuilt whenever |
| 1145 |
// category_names would otherwise overflow. |
| 1146 |
// No other allocations allowed past this point, until WritePsam() call. |
| 1147 |
const char** category_names = nullptr; |
| 1148 |
uint32_t* category_names_htable = nullptr; |
| 1149 |
uint32_t category_names_ct = 0; |
| 1150 |
// category_names_capacity == category_names_htable_size / 2 |
| 1151 |
uint32_t category_names_htable_size = 0; |
| 1152 |
arena_top = g_bigstack_end; |
| 1153 |
if (pheno_ct) { |
| 1154 |
category_names_htable_size = 512; |
| 1155 |
if (unlikely(bigstack_alloc_kcp(category_names_htable_size / 2, &category_names) || |
| 1156 |
bigstack_alloc_u32(category_names_htable_size, &category_names_htable))) { |
| 1157 |
goto MergePsams_ret_NOMEM; |
| 1158 |
} |
| 1159 |
SetAllU32Arr(category_names_htable_size, category_names_htable); |
| 1160 |
// copy into arena so overread is safe |
| 1161 |
const uint32_t missing_catname_slen = strlen(missing_catname); |
| 1162 |
if (unlikely(StoreStringAtEndK(g_bigstack_base, missing_catname, missing_catname_slen, &arena_top, &(category_names[0])))) { |
| 1163 |
goto MergePsams_ret_NOMEM; |
| 1164 |
} |
| 1165 |
const uint32_t hashval = Hashceil(missing_catname, missing_catname_slen, category_names_htable_size); |
| 1166 |
category_names_htable[0] = hashval; |
| 1167 |
category_names_ct = 1; |
| 1168 |
} |
| 1169 |
arena_bottom = g_bigstack_base; |
| 1170 |
filesets_iter = filesets; |
| 1171 |
do { |
| 1172 |
cur_fname = filesets_iter->psam_fname; |
| 1173 |
reterr = TextStreamOpenEx(cur_fname, kMaxLongLine, linebuf_capacity, decompress_thread_ct, nullptr, linebuf, &txs); |
| 1174 |
if (unlikely(reterr)) { |
| 1175 |
goto MergePsams_ret_TSTREAM_REWIND_FAIL; |
| 1176 |
} |
| 1177 |
const char* line_start = TextLineEnd(&txs); |
| 1178 |
for (line_idx = 1; ; ++line_idx) { |
| 1179 |
if (unlikely(!TextGetUnsafe2K(&txs, &line_start))) { |
| 1180 |
reterr = TextStreamRawErrcode(&txs); |
| 1181 |
goto MergePsams_ret_TSTREAM_REWIND_FAIL; |
| 1182 |
} |
| 1183 |
if ((line_start[0] != '#') || tokequal_k(&(line_start[1]), "FID") || tokequal_k(&(line_start[1]), "IID")) { |
| 1184 |
break; |
| 1185 |
} |
| 1186 |
line_start = AdvPastDelim(line_start, '\n'); |
| 1187 |
} |
| 1188 |
if (cur_sample_include) { |
| 1189 |
ZeroWArr(sample_ctl, cur_sample_include); |
| 1190 |
} |
| 1191 |
ZeroWArr(pheno_ctl, pheno_include); |
| 1192 |
uint32_t sid_present = 0; |
| 1193 |
uint32_t parents_present = 0; |
| 1194 |
uint32_t sex_present = 0; |
| 1195 |
uint32_t relevant_postid_col_ct = 0; |
| 1196 |
uint32_t fid_present; |
| 1197 |
col_types[0] = 0; |
| 1198 |
if (line_start[0] == '#') { |
| 1199 |
fid_present = (line_start[1] == 'F'); |
| 1200 |
uint32_t col_idx = 1; |
| 1201 |
const char* token_iter = FirstNonTspace(&(line_start[4])); |
| 1202 |
if (fid_present) { |
| 1203 |
token_iter = FirstNonTspace(CurTokenEnd(token_iter)); |
| 1204 |
++col_idx; |
| 1205 |
} |
| 1206 |
sid_present = tokequal_k(token_iter, "SID"); |
| 1207 |
if (sid_present) { |
| 1208 |
token_iter = FirstNonTspace(CurTokenEnd(token_iter)); |
| 1209 |
++col_idx; |
| 1210 |
} |
| 1211 |
for (; ; ++col_idx) { |
| 1212 |
if (IsEolnKns(*token_iter)) { |
| 1213 |
break; |
| 1214 |
} |
| 1215 |
const char* token_end = CurTokenEnd(token_iter); |
| 1216 |
const uint32_t token_slen = token_end - token_iter; |
| 1217 |
uint32_t cur_col_type = UINT32_MAX; |
| 1218 |
if (token_slen == 3) { |
| 1219 |
if (memequal_sk(token_iter, "PAT")) { |
| 1220 |
cur_col_type = 0; |
| 1221 |
parents_present = 1; |
| 1222 |
} else if (memequal_sk(token_iter, "MAT")) { |
| 1223 |
cur_col_type = 1; |
| 1224 |
} else if (memequal_sk(token_iter, "SEX")) { |
| 1225 |
cur_col_type = 2; |
| 1226 |
sex_present = 1; |
| 1227 |
} |
| 1228 |
} |
| 1229 |
const char* cur_token_start = token_iter; |
| 1230 |
token_iter = FirstNonTspace(token_end); |
| 1231 |
if (cur_col_type == UINT32_MAX) { |
| 1232 |
if (token_slen < max_pheno_name_blen) { |
| 1233 |
cur_col_type = StrboxHtableFindNnt(cur_token_start, pheno_names, pheno_names_htable, max_pheno_name_blen, token_slen, pheno_names_table_size); |
| 1234 |
} |
| 1235 |
if (cur_col_type == UINT32_MAX) { |
| 1236 |
continue; |
| 1237 |
} |
| 1238 |
SetBit(cur_col_type, pheno_include); |
| 1239 |
cur_col_type += kNonphenoPostIdColCt; |
| 1240 |
} |
| 1241 |
col_skips[relevant_postid_col_ct] = col_idx; |
| 1242 |
col_types[relevant_postid_col_ct++] = cur_col_type; |
| 1243 |
} |
| 1244 |
if (relevant_postid_col_ct) { |
| 1245 |
for (uint32_t rp_col_idx = relevant_postid_col_ct - 1; rp_col_idx; --rp_col_idx) { |
| 1246 |
col_skips[rp_col_idx] -= col_skips[rp_col_idx - 1]; |
| 1247 |
} |
| 1248 |
} |
| 1249 |
line_start = AdvPastDelim(token_iter, '\n'); |
| 1250 |
++line_idx; |
| 1251 |
} else { |
| 1252 |
// .fam |
| 1253 |
fid_present = (fam_cols / kfFamCol1) & 1; |
| 1254 |
uint32_t prev_col_idx = 0; |
| 1255 |
uint32_t col_idx = fid_present + 1; |
| 1256 |
if (fam_cols & kfFamCol34) { |
| 1257 |
col_skips[relevant_postid_col_ct] = col_idx - prev_col_idx; |
| 1258 |
col_types[relevant_postid_col_ct++] = 0; |
| 1259 |
col_skips[relevant_postid_col_ct] = 1; |
| 1260 |
col_types[relevant_postid_col_ct++] = 1; |
| 1261 |
parents_present = 1; |
| 1262 |
prev_col_idx = col_idx + 1; |
| 1263 |
col_idx += 2; |
| 1264 |
} |
| 1265 |
if (fam_cols & kfFamCol5) { |
| 1266 |
col_skips[relevant_postid_col_ct] = col_idx - prev_col_idx; |
| 1267 |
col_types[relevant_postid_col_ct++] = 2; |
| 1268 |
sex_present = 1; |
| 1269 |
prev_col_idx = col_idx; |
| 1270 |
++col_idx; |
| 1271 |
} |
| 1272 |
if (fam_cols & kfFamCol6) { |
| 1273 |
col_skips[relevant_postid_col_ct] = col_idx - prev_col_idx; |
| 1274 |
const uint32_t pheno_idx = StrboxHtableFind("PHENO1", pheno_names, pheno_names_htable, max_pheno_name_blen, strlen("PHENO1"), pheno_names_table_size); |
| 1275 |
col_types[relevant_postid_col_ct++] = kNonphenoPostIdColCt + pheno_idx; |
| 1276 |
SetBit(pheno_idx, pheno_include); |
| 1277 |
} |
| 1278 |
} |
| 1279 |
|
| 1280 |
const uintptr_t line_idx_body_start = line_idx; |
| 1281 |
const uint32_t cur_pheno_ct = PopcountWords(pheno_include, pheno_ctl); |
| 1282 |
uint32_t write_sample_ct = 0; |
| 1283 |
const char* line_iter; |
| 1284 |
for (; TextGetUnsafe2K(&txs, &line_start); line_start = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 1285 |
line_iter = line_start; |
| 1286 |
if (relevant_postid_col_ct) { |
| 1287 |
line_iter = TokenLexK(line_start, col_types, col_skips, relevant_postid_col_ct, token_ptrs, token_slens); |
| 1288 |
if (unlikely(!line_iter)) { |
| 1289 |
goto MergePsams_ret_MISSING_TOKENS; |
| 1290 |
} |
| 1291 |
} |
| 1292 |
uint32_t sample_idx; |
| 1293 |
if (unlikely(LookupXidHtable(line_start, siip, sample_id_htable, sample_id_table_size, fid_present, sid_present, &sample_idx, idbuf))) { |
| 1294 |
goto MergePsams_ret_REWIND_FAIL; |
| 1295 |
} |
| 1296 |
if (sample_idx == UINT32_MAX) { |
| 1297 |
continue; |
| 1298 |
} |
| 1299 |
if (cur_sample_include) { |
| 1300 |
if (IsSet(cur_sample_include, sample_idx)) { |
| 1301 |
TabsToSpaces(idbuf); |
| 1302 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in %s.\n", idbuf, cur_fname); |
| 1303 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 1304 |
} |
| 1305 |
SetBit(sample_idx, cur_sample_include); |
| 1306 |
} |
| 1307 |
++write_sample_ct; |
| 1308 |
if (parents_present) { |
| 1309 |
char* dad_id_dst = &(parental_id_info.paternal_ids[sample_idx * max_paternal_id_blen]); |
| 1310 |
char* mom_id_dst = &(parental_id_info.maternal_ids[sample_idx * max_maternal_id_blen]); |
| 1311 |
if (parents_locked) { |
| 1312 |
if (!IsSet(parents_locked, sample_idx * 2)) { |
| 1313 |
const char* dad_id = token_ptrs[0]; |
| 1314 |
const uint32_t dad_slen = token_slens[0]; |
| 1315 |
if (merge_parents_mode == kMergePhenoModeNmMatch) { |
| 1316 |
if (((dad_slen != 1) || (dad_id[0] != '0')) && (!strequal_unsafe(dad_id_dst, dad_id, dad_slen))) { |
| 1317 |
if (strequal_k_unsafe(dad_id_dst, "0")) { |
| 1318 |
memcpyx(dad_id_dst, dad_id, dad_slen, '\0'); |
| 1319 |
} else { |
| 1320 |
strcpy_k(dad_id_dst, "0"); |
| 1321 |
SetBit(sample_idx * 2, parents_locked); |
| 1322 |
} |
| 1323 |
} |
| 1324 |
} else { |
| 1325 |
memcpyx(dad_id_dst, dad_id, dad_slen, '\0'); |
| 1326 |
SetBit(sample_idx * 2, parents_locked); |
| 1327 |
} |
| 1328 |
} |
| 1329 |
if (!IsSet(parents_locked, sample_idx * 2 + 1)) { |
| 1330 |
const char* mom_id = token_ptrs[1]; |
| 1331 |
const uint32_t mom_slen = token_slens[1]; |
| 1332 |
if (merge_parents_mode == kMergePhenoModeNmMatch) { |
| 1333 |
if (((mom_slen != 1) || (mom_id[0] != '0')) && (!strequal_unsafe(mom_id_dst, mom_id, mom_slen))) { |
| 1334 |
if (strequal_k_unsafe(mom_id_dst, "0")) { |
| 1335 |
memcpyx(mom_id_dst, mom_id, mom_slen, '\0'); |
| 1336 |
} else { |
| 1337 |
strcpy_k(mom_id_dst, "0"); |
| 1338 |
SetBit(sample_idx * 2, parents_locked); |
| 1339 |
} |
| 1340 |
} |
| 1341 |
} else { |
| 1342 |
memcpyx(mom_id_dst, mom_id, mom_slen, '\0'); |
| 1343 |
SetBit(sample_idx * 2 + 1, parents_locked); |
| 1344 |
} |
| 1345 |
} |
| 1346 |
} else { |
| 1347 |
// nm-first, skip if not missing |
| 1348 |
if (strequal_k_unsafe(dad_id_dst, "0")) { |
| 1349 |
memcpyx(dad_id_dst, token_ptrs[0], token_slens[0], '\0'); |
| 1350 |
} |
| 1351 |
if (strequal_k_unsafe(mom_id_dst, "0")) { |
| 1352 |
memcpyx(mom_id_dst, token_ptrs[1], token_slens[1], '\0'); |
| 1353 |
} |
| 1354 |
} |
| 1355 |
} |
| 1356 |
if (sex_present) { |
| 1357 |
if (!sex_locked) { |
| 1358 |
if (!IsSet(sex_nm, sample_idx)) { |
| 1359 |
// nm-first and previously missing |
| 1360 |
const uint32_t cur_sex_code = (token_slens[2] == 1)? CharToSex(token_ptrs[2][0]) : 0; |
| 1361 |
if (cur_sex_code) { |
| 1362 |
SetBit(sample_idx, sex_nm); |
| 1363 |
AssignBit(sample_idx, cur_sex_code & 1, sex_male); |
| 1364 |
} |
| 1365 |
} |
| 1366 |
} else { |
| 1367 |
if (!IsSet(sex_locked, sample_idx)) { |
| 1368 |
const uint32_t cur_sex_code = (token_slens[2] == 1)? CharToSex(token_ptrs[2][0]) : 0; |
| 1369 |
if (merge_sex_mode == kMergePhenoModeNmMatch) { |
| 1370 |
if (cur_sex_code) { |
| 1371 |
if (!IsSet(sex_nm, sample_idx)) { |
| 1372 |
SetBit(sample_idx, sex_nm); |
| 1373 |
AssignBit(sample_idx, cur_sex_code & 1, sex_male); |
| 1374 |
} else { |
| 1375 |
if (IsSet(sex_male, sample_idx) != (cur_sex_code & 1)) { |
| 1376 |
ClearBit(sample_idx, sex_nm); |
| 1377 |
ClearBit(sample_idx, sex_male); |
| 1378 |
SetBit(sample_idx, sex_locked); |
| 1379 |
} |
| 1380 |
} |
| 1381 |
} |
| 1382 |
} else { |
| 1383 |
// first |
| 1384 |
AssignBit(sample_idx, (cur_sex_code + 1) / 2, sex_nm); |
| 1385 |
AssignBit(sample_idx, cur_sex_code & 1, sex_male); |
| 1386 |
SetBit(sample_idx, sex_locked); |
| 1387 |
} |
| 1388 |
} |
| 1389 |
} |
| 1390 |
} |
| 1391 |
if (cur_pheno_ct) { |
| 1392 |
uintptr_t pheno_uidx_base = 0; |
| 1393 |
uintptr_t cur_bits = pheno_include[0]; |
| 1394 |
for (uint32_t cur_pheno_idx = 0; cur_pheno_idx != cur_pheno_ct; ++cur_pheno_idx) { |
| 1395 |
const uintptr_t pheno_uidx = BitIter1(pheno_include, &pheno_uidx_base, &cur_bits); |
| 1396 |
PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]); |
| 1397 |
if (((!pheno_locked) && IsSet(cur_pheno_col->nonmiss, sample_idx)) || (pheno_locked && IsSet(pheno_locked, sample_idx + pheno_uidx * sample_ct))) { |
| 1398 |
continue; |
| 1399 |
} |
| 1400 |
const uint32_t col_type_idx = pheno_uidx + kNonphenoPostIdColCt; |
| 1401 |
const char* cur_phenostr = token_ptrs[col_type_idx]; |
| 1402 |
double dxx; |
| 1403 |
const char* cur_phenostr_end = ScanadvDouble(cur_phenostr, &dxx); |
| 1404 |
if (!cur_phenostr_end) { |
| 1405 |
const uint32_t slen = token_slens[col_type_idx]; |
| 1406 |
if (IsNanStr(cur_phenostr, slen)) { |
| 1407 |
dxx = missing_phenod; |
| 1408 |
} else { |
| 1409 |
// categorical case |
| 1410 |
if (cur_pheno_col->type_code != kPhenoDtypeCat) { |
| 1411 |
if (unlikely(cur_pheno_col->type_code == kPhenoDtypeQt)) { |
| 1412 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' entry on line %" PRIuPTR " of %s is categorical, while an earlier entry is numeric/'NA'.\n", &(pheno_names[pheno_uidx * max_pheno_name_blen]), line_idx, cur_fname); |
| 1413 |
goto MergePsams_ret_INCONSISTENT_INPUT_WW; |
| 1414 |
} |
| 1415 |
cur_pheno_col->type_code = kPhenoDtypeCat; |
| 1416 |
ZeroU32Arr(sample_ct, cur_pheno_col->data.cat); |
| 1417 |
} |
| 1418 |
uint32_t catname_idx = IdHtableFindNnt(cur_phenostr, category_names, category_names_htable, slen, category_names_htable_size); |
| 1419 |
if (catname_idx == UINT32_MAX) { |
| 1420 |
if (category_names_ct * 2 == category_names_htable_size) { |
| 1421 |
// resize |
| 1422 |
if (unlikely(S_CAST(uintptr_t, arena_top - arena_bottom) < category_names_ct * (2 * sizeof(int32_t) + sizeof(intptr_t)))) { |
| 1423 |
goto MergePsams_ret_NOMEM; |
| 1424 |
} |
| 1425 |
uint32_t next_capacity = category_names_ct * 2; |
| 1426 |
if (next_capacity >= 0x80000000U) { |
| 1427 |
if (unlikely(next_capacity != 0x80000000U)) { |
| 1428 |
logerrputs("Error: This implementation of --pmerge[-list] is limited to ~2^31 distinct\ncategory names.\n"); |
| 1429 |
reterr = kPglRetNotYetSupported; |
| 1430 |
goto MergePsams_ret_1; |
| 1431 |
} |
| 1432 |
next_capacity = 0x7fffffff; |
| 1433 |
} |
| 1434 |
category_names_htable = R_CAST(uint32_t*, &(category_names[next_capacity])); |
| 1435 |
category_names_htable_size = 2 * next_capacity; |
| 1436 |
SetAllU32Arr(category_names_htable_size, category_names_htable); |
| 1437 |
arena_bottom = R_CAST(unsigned char*, &(category_names_htable[category_names_htable_size])); |
| 1438 |
for (uint32_t category_idx = 0; category_idx != category_names_ct; ++category_idx) { |
| 1439 |
const char* cur_cat_name = category_names[category_idx]; |
| 1440 |
HtableAddNondup(cur_cat_name, strlen(cur_cat_name), category_names_htable_size, category_idx, category_names_htable); |
| 1441 |
} |
| 1442 |
} |
| 1443 |
catname_idx = category_names_ct; |
| 1444 |
if (unlikely(StoreStringAtEndK(arena_bottom, cur_phenostr, slen, &arena_top, &(category_names[catname_idx])))) { |
| 1445 |
goto MergePsams_ret_NOMEM; |
| 1446 |
} |
| 1447 |
++category_names_ct; |
| 1448 |
HtableAddNondup(cur_phenostr, slen, category_names_htable_size, catname_idx, category_names_htable); |
| 1449 |
} |
| 1450 |
if (!pheno_locked) { |
| 1451 |
// nm-first and previously missing |
| 1452 |
if (catname_idx) { |
| 1453 |
SetBit(sample_idx, cur_pheno_col->nonmiss); |
| 1454 |
cur_pheno_col->data.cat[sample_idx] = catname_idx; |
| 1455 |
} |
| 1456 |
} else { |
| 1457 |
if (merge_pheno_mode == kMergePhenoModeNmMatch) { |
| 1458 |
if (catname_idx) { |
| 1459 |
const uint32_t prev_catname_idx = cur_pheno_col->data.cat[sample_idx]; |
| 1460 |
if (prev_catname_idx != catname_idx) { |
| 1461 |
if (!prev_catname_idx) { |
| 1462 |
SetBit(sample_idx, cur_pheno_col->nonmiss); |
| 1463 |
cur_pheno_col->data.cat[sample_idx] = catname_idx; |
| 1464 |
} else { |
| 1465 |
ClearBit(sample_idx, cur_pheno_col->nonmiss); |
| 1466 |
cur_pheno_col->data.cat[sample_idx] = 0; |
| 1467 |
SetBit(sample_idx + pheno_uidx * sample_ct, pheno_locked); |
| 1468 |
} |
| 1469 |
} |
| 1470 |
} |
| 1471 |
} else { |
| 1472 |
// first |
| 1473 |
if (catname_idx) { |
| 1474 |
SetBit(sample_idx, cur_pheno_col->nonmiss); |
| 1475 |
cur_pheno_col->data.cat[sample_idx] = catname_idx; |
| 1476 |
} |
| 1477 |
SetBit(sample_idx + pheno_uidx * sample_ct, pheno_locked); |
| 1478 |
} |
| 1479 |
} |
| 1480 |
continue; |
| 1481 |
} |
| 1482 |
} else { |
| 1483 |
if (unlikely(!IsSpaceOrEoln(*cur_phenostr_end))) { |
| 1484 |
cur_phenostr_end = CurTokenEnd(cur_phenostr_end); |
| 1485 |
*K_CAST(char*, cur_phenostr_end) = '\0'; |
| 1486 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid numeric token '%s' on line %" PRIuPTR " of %s.\n", cur_phenostr, line_idx, cur_fname); |
| 1487 |
goto MergePsams_ret_MALFORMED_INPUT_WW; |
| 1488 |
} |
| 1489 |
} |
| 1490 |
if (unlikely(cur_pheno_col->type_code == kPhenoDtypeCat)) { |
| 1491 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' entry on line %" PRIuPTR " of %s is numeric/'NA', while an earlier entry is categorical.\n", &(pheno_names[pheno_uidx * max_pheno_name_blen]), line_idx, cur_fname); |
| 1492 |
goto MergePsams_ret_INCONSISTENT_INPUT_WW; |
| 1493 |
} |
| 1494 |
cur_pheno_col->type_code = kPhenoDtypeQt; |
| 1495 |
if (!pheno_locked) { |
| 1496 |
// nm-first |
| 1497 |
if (dxx != missing_phenod) { |
| 1498 |
if ((dxx == 0.0) && pheno_zero_seen) { |
| 1499 |
SetBit(sample_idx + pheno_uidx * sample_ct, pheno_zero_seen); |
| 1500 |
} else { |
| 1501 |
cur_pheno_col->data.qt[sample_idx] = dxx; |
| 1502 |
SetBit(sample_idx, cur_pheno_col->nonmiss); |
| 1503 |
} |
| 1504 |
} |
| 1505 |
} else { |
| 1506 |
if (merge_pheno_mode == kMergePhenoModeNmMatch) { |
| 1507 |
if (dxx != missing_phenod) { |
| 1508 |
if ((dxx == 0.0) && pheno_zero_seen) { |
| 1509 |
SetBit(sample_idx + pheno_uidx * sample_ct, pheno_zero_seen); |
| 1510 |
} else if (!IsSet(cur_pheno_col->nonmiss, sample_idx)) { |
| 1511 |
SetBit(sample_idx, cur_pheno_col->nonmiss); |
| 1512 |
cur_pheno_col->data.qt[sample_idx] = dxx; |
| 1513 |
} else { |
| 1514 |
if (dxx != cur_pheno_col->data.qt[sample_idx]) { |
| 1515 |
ClearBit(sample_idx, cur_pheno_col->nonmiss); |
| 1516 |
SetBit(sample_idx + pheno_uidx * sample_ct, pheno_locked); |
| 1517 |
} |
| 1518 |
} |
| 1519 |
} |
| 1520 |
} else { |
| 1521 |
if (dxx != missing_phenod) { |
| 1522 |
SetBit(sample_idx, cur_pheno_col->nonmiss); |
| 1523 |
cur_pheno_col->data.qt[sample_idx] = dxx; |
| 1524 |
} |
| 1525 |
SetBit(sample_idx + pheno_uidx * sample_ct, pheno_locked); |
| 1526 |
} |
| 1527 |
} |
| 1528 |
} |
| 1529 |
} |
| 1530 |
} |
| 1531 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 1532 |
goto MergePsams_ret_TSTREAM_FAIL; |
| 1533 |
} |
| 1534 |
if (unlikely(CleanupTextStream2(cur_fname, &txs, &reterr))) { |
| 1535 |
goto MergePsams_ret_1; |
| 1536 |
} |
| 1537 |
filesets_iter->read_sample_ct = line_idx - line_idx_body_start; |
| 1538 |
filesets_iter->write_sample_ct = write_sample_ct; |
| 1539 |
filesets_iter = filesets_iter->next; |
| 1540 |
} while (filesets_iter); |
| 1541 |
BigstackReset(bigstack_mark2); |
| 1542 |
BigstackEndSet(arena_top); |
| 1543 |
if (pheno_ct) { |
| 1544 |
if (category_names) { |
| 1545 |
const char** category_names_final = R_CAST(const char**, g_bigstack_base); |
| 1546 |
BigstackBaseSet(&(category_names_final[category_names_ct])); |
| 1547 |
memmove(category_names_final, category_names, category_names_ct * sizeof(intptr_t)); |
| 1548 |
category_names = category_names_final; |
| 1549 |
} |
| 1550 |
for (uintptr_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 1551 |
PhenoCol* pheno_col = &(pheno_cols[pheno_idx]); |
| 1552 |
if (pheno_col->type_code == kPhenoDtypeQt) { |
| 1553 |
uintptr_t* nonmiss = pheno_col->nonmiss; |
| 1554 |
double* qt = pheno_col->data.qt; |
| 1555 |
const uint32_t sample_nm_ct = PopcountWords(nonmiss, sample_ctl); |
| 1556 |
uintptr_t sample_uidx_base = 0; |
| 1557 |
uintptr_t cur_bits = nonmiss[0]; |
| 1558 |
uint32_t sample_idx = 0; |
| 1559 |
if (!affection_01) { |
| 1560 |
if (merge_pheno_mode == kMergePhenoModeFirst) { |
| 1561 |
// 1. Check for values outside {0, 1, 2, missing}. |
| 1562 |
// 2. If none exist, convert zeroes to missing. |
| 1563 |
for (; sample_idx != sample_nm_ct; ++sample_idx) { |
| 1564 |
const uint32_t sample_uidx = BitIter1(nonmiss, &sample_uidx_base, &cur_bits); |
| 1565 |
const double dxx = qt[sample_uidx]; |
| 1566 |
if ((dxx != 0.0) && (dxx != 1.0) && (dxx != 2.0)) { |
| 1567 |
break; |
| 1568 |
} |
| 1569 |
} |
| 1570 |
if (!(sample_idx != sample_nm_ct)) { |
| 1571 |
// Could use explicit word-based iteration instead. |
| 1572 |
sample_uidx_base = 0; |
| 1573 |
cur_bits = nonmiss[0]; |
| 1574 |
for (sample_idx = 0; sample_idx != sample_nm_ct; ++sample_idx) { |
| 1575 |
const uint32_t sample_uidx = BitIter1(nonmiss, &sample_uidx_base, &cur_bits); |
| 1576 |
if (qt[sample_uidx] == 0.0) { |
| 1577 |
ClearBit(sample_uidx, nonmiss); |
| 1578 |
} |
| 1579 |
} |
| 1580 |
} |
| 1581 |
} else { |
| 1582 |
// 1. Check for values outside {1, 2, missing}. |
| 1583 |
// 2. If at least one exists, patch in zeroes. (In nm-match |
| 1584 |
// case, when a nonmissing value is in the cell but a zero was |
| 1585 |
// also observed, convert to missing.) |
| 1586 |
for (; sample_idx != sample_nm_ct; ++sample_idx) { |
| 1587 |
const uint32_t sample_uidx = BitIter1(nonmiss, &sample_uidx_base, &cur_bits); |
| 1588 |
const double dxx = qt[sample_uidx]; |
| 1589 |
if ((dxx != 1.0) && (dxx != 2.0)) { |
| 1590 |
break; |
| 1591 |
} |
| 1592 |
} |
| 1593 |
if (sample_idx != sample_nm_ct) { |
| 1594 |
const uintptr_t bit_offset = pheno_idx * sample_ct; |
| 1595 |
const uint32_t zero_ct = PopcountBitRange(pheno_zero_seen, bit_offset, bit_offset + sample_ct); |
| 1596 |
if (zero_ct) { |
| 1597 |
uintptr_t zero_seen_uidx_base; |
| 1598 |
BitIter1Start(pheno_zero_seen, bit_offset, &zero_seen_uidx_base, &cur_bits); |
| 1599 |
if (merge_pheno_mode == kMergePhenoModeNmMatch) { |
| 1600 |
for (uint32_t zero_idx = 0; zero_idx != zero_ct; ++zero_idx) { |
| 1601 |
const uintptr_t sample_uidx = BitIter1(pheno_zero_seen, &zero_seen_uidx_base, &cur_bits) - bit_offset; |
| 1602 |
if (IsSet(nonmiss, sample_uidx)) { |
| 1603 |
ClearBit(sample_uidx, nonmiss); |
| 1604 |
} else { |
| 1605 |
SetBit(sample_uidx, nonmiss); |
| 1606 |
qt[sample_uidx] = 0.0; |
| 1607 |
} |
| 1608 |
} |
| 1609 |
} else { |
| 1610 |
// nm-first |
| 1611 |
for (uint32_t zero_idx = 0; zero_idx != zero_ct; ++zero_idx) { |
| 1612 |
const uintptr_t sample_uidx = BitIter1(pheno_zero_seen, &zero_seen_uidx_base, &cur_bits) - bit_offset; |
| 1613 |
SetBit(sample_uidx, nonmiss); |
| 1614 |
qt[sample_uidx] = 0.0; |
| 1615 |
} |
| 1616 |
} |
| 1617 |
} |
| 1618 |
} |
| 1619 |
} |
| 1620 |
} else { |
| 1621 |
// 1. Check for values outside {0, 1, missing}. |
| 1622 |
// 2. If none exist, convert to {1, 2, missing}. |
| 1623 |
for (; sample_idx != sample_nm_ct; ++sample_idx) { |
| 1624 |
const uint32_t sample_uidx = BitIter1(nonmiss, &sample_uidx_base, &cur_bits); |
| 1625 |
const double dxx = qt[sample_uidx]; |
| 1626 |
if ((dxx != 0.0) && (dxx != 1.0)) { |
| 1627 |
break; |
| 1628 |
} |
| 1629 |
} |
| 1630 |
if (!(sample_idx != sample_nm_ct)) { |
| 1631 |
sample_uidx_base = 0; |
| 1632 |
cur_bits = nonmiss[0]; |
| 1633 |
for (sample_idx = 0; sample_idx != sample_nm_ct; ++sample_idx) { |
| 1634 |
const uint32_t sample_uidx = BitIter1(nonmiss, &sample_uidx_base, &cur_bits); |
| 1635 |
qt[sample_uidx] += 1.0; |
| 1636 |
} |
| 1637 |
} |
| 1638 |
} |
| 1639 |
} else if (pheno_col->type_code == kPhenoDtypeCat) { |
| 1640 |
pheno_col->category_names = category_names; |
| 1641 |
} |
| 1642 |
} |
| 1643 |
} |
| 1644 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".psam"); |
| 1645 |
reterr = WritePsam(outname, sample_include, siip, &parental_id_info, sex_nm, sex_male, pheno_cols, pheno_names, nullptr, "NA", sample_ct, pheno_ct, max_pheno_name_blen, kfPsamColDefault, 0); |
| 1646 |
if (unlikely(reterr)) { |
| 1647 |
goto MergePsams_ret_1; |
| 1648 |
} |
| 1649 |
logprintfww("--pmerge%s: Merged .psam written to %s .\n", pmip->list_fname? "-list" : "", outname); |
| 1650 |
*sample_ctp = sample_ct; |
| 1651 |
ArenaEndSet(siip->sample_ids, &bigstack_end_mark); |
| 1652 |
} |
| 1653 |
while (0) { |
| 1654 |
MergePsams_ret_NOMEM: |
| 1655 |
reterr = kPglRetNomem; |
| 1656 |
break; |
| 1657 |
MergePsams_ret_TSTREAM_REWIND_FAIL: |
| 1658 |
TextStreamErrPrintRewind(cur_fname, &txs, &reterr); |
| 1659 |
break; |
| 1660 |
MergePsams_ret_TSTREAM_FAIL: |
| 1661 |
TextStreamErrPrint(cur_fname, &txs); |
| 1662 |
break; |
| 1663 |
MergePsams_ret_REWIND_FAIL: |
| 1664 |
logerrprintfww(kErrprintfRewind, cur_fname); |
| 1665 |
reterr = kPglRetRewindFail; |
| 1666 |
break; |
| 1667 |
MergePsams_ret_MISSING_TOKENS: |
| 1668 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, cur_fname); |
| 1669 |
MergePsams_ret_MALFORMED_INPUT_WW: |
| 1670 |
WordWrapB(0); |
| 1671 |
MergePsams_ret_MALFORMED_INPUT_2: |
| 1672 |
logerrputsb(); |
| 1673 |
MergePsams_ret_MALFORMED_INPUT: |
| 1674 |
reterr = kPglRetMalformedInput; |
| 1675 |
break; |
| 1676 |
MergePsams_ret_INCONSISTENT_INPUT_WW: |
| 1677 |
WordWrapB(0); |
| 1678 |
logerrputsb(); |
| 1679 |
MergePsams_ret_INCONSISTENT_INPUT: |
| 1680 |
reterr = kPglRetInconsistentInput; |
| 1681 |
break; |
| 1682 |
} |
| 1683 |
MergePsams_ret_1: |
| 1684 |
CleanupTextStream2(cur_fname, &txs, &reterr); |
| 1685 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 1686 |
return reterr; |
| 1687 |
} |
| 1688 |
|
| 1689 |
// This executes before ScanPvarsAndMergeHeader(), so we know whether to write |
| 1690 |
// an INFO/PR header line even when it doesn't appear in any input .pvar. |
| 1691 |
PglErr ScanPgenHeaders(uint32_t is_list, MiscFlags misc_flags, PmergeInputFilesetLl* filesets) { |
| 1692 |
const char* read_pgen_fname = nullptr; |
| 1693 |
PglErr reterr = kPglRetSuccess; |
| 1694 |
PgenFileInfo pgfi; |
| 1695 |
PreinitPgfi(&pgfi); |
| 1696 |
{ |
| 1697 |
const uint32_t real_ref_alleles = (misc_flags / kfMiscRealRefAlleles) & 1; |
| 1698 |
PmergeInputFilesetLl* filesets_iter = filesets; |
| 1699 |
do { |
| 1700 |
read_pgen_fname = filesets_iter->pgen_fname; |
| 1701 |
PgenHeaderCtrl header_ctrl; |
| 1702 |
uintptr_t cur_alloc_cacheline_ct; // unused |
| 1703 |
reterr = PgfiInitPhase1(read_pgen_fname, nullptr, UINT32_MAX, filesets_iter->read_sample_ct, &header_ctrl, &pgfi, &cur_alloc_cacheline_ct, g_logbuf); |
| 1704 |
if (unlikely(reterr)) { |
| 1705 |
if (reterr == kPglRetSampleMajorBed) { |
| 1706 |
snprintf(g_logbuf, kLogbufSize, "Error: %s is a sample-major .bed file; this is not supported by --pmerge%s. Retry after converting it to a .pgen.\n", read_pgen_fname, is_list? "-list" : ""); |
| 1707 |
goto ScanPgenHeaders_ret_INCONSISTENT_INPUT_WW; |
| 1708 |
} |
| 1709 |
WordWrapB(0); |
| 1710 |
logerrputsb(); |
| 1711 |
goto ScanPgenHeaders_ret_1; |
| 1712 |
} |
| 1713 |
uint32_t vrtype_8bit_needed = 0; |
| 1714 |
uint32_t nonref_flags_storage; |
| 1715 |
if (pgfi.const_vrtype == kPglVrtypePlink1) { |
| 1716 |
nonref_flags_storage = 2 - real_ref_alleles; |
| 1717 |
} else { |
| 1718 |
nonref_flags_storage = header_ctrl >> 6; |
| 1719 |
if (pgfi.const_vrtype == UINT32_MAX) { |
| 1720 |
if (((header_ctrl & 12) == 4) || ((header_ctrl & 15) > 9)) { |
| 1721 |
vrtype_8bit_needed = 1; |
| 1722 |
} |
| 1723 |
} else if (pgfi.const_vrtype > 15) { |
| 1724 |
vrtype_8bit_needed = 1; |
| 1725 |
} |
| 1726 |
} |
| 1727 |
filesets_iter->nonref_flags_storage = nonref_flags_storage; |
| 1728 |
filesets_iter->vrtype_8bit_needed = vrtype_8bit_needed; |
| 1729 |
if (unlikely(CleanupPgfi2(read_pgen_fname, &pgfi, &reterr))) { |
| 1730 |
goto ScanPgenHeaders_ret_1; |
| 1731 |
} |
| 1732 |
filesets_iter = filesets_iter->next; |
| 1733 |
} while (filesets_iter); |
| 1734 |
} |
| 1735 |
while (0) { |
| 1736 |
ScanPgenHeaders_ret_INCONSISTENT_INPUT_WW: |
| 1737 |
WordWrapB(0); |
| 1738 |
logerrputsb(); |
| 1739 |
reterr = kPglRetInconsistentInput; |
| 1740 |
break; |
| 1741 |
} |
| 1742 |
ScanPgenHeaders_ret_1: |
| 1743 |
CleanupPgfi2(read_pgen_fname, &pgfi, &reterr); |
| 1744 |
return reterr; |
| 1745 |
} |
| 1746 |
|
| 1747 |
typedef struct RescanOnePosRecordStruct { |
| 1748 |
uint32_t rec_blen; |
| 1749 |
AlleleCode allele_ct; |
| 1750 |
char variant_id[]; // null-terminated, followed by null-terminated REF, ALT |
| 1751 |
} RescanOnePosRecord; |
| 1752 |
|
| 1753 |
typedef struct RescanOnePosContextStruct { |
| 1754 |
RescanOnePosRecord* first_record; |
| 1755 |
uint32_t write_allele_ct_max; |
| 1756 |
uint32_t sort_vars_ascii; |
| 1757 |
uint32_t multiallelics_already_joined; |
| 1758 |
char input_missing_geno_char; |
| 1759 |
uint32_t write_doomed_variant_ct; |
| 1760 |
uint32_t write_nondoomed_max_allele_ct; |
| 1761 |
uint32_t first_chr_idx; |
| 1762 |
uint32_t first_bp; |
| 1763 |
char** first_varid_ptr; |
| 1764 |
const char* cur_fname; |
| 1765 |
const ChrInfo* cip; |
| 1766 |
} RescanOnePosContext; |
| 1767 |
|
| 1768 |
PglErr RescanOnePos(unsigned char* arena_top, uint32_t batch_size, uint32_t prev_chr_code, uint32_t prev_bp, unsigned char* arena_bottom, RescanOnePosContext* ctxp, uint32_t* nonwrite_variant_ctp) { |
| 1769 |
char* first_varid; |
| 1770 |
if (batch_size == 1) { |
| 1771 |
// Fast path for common case. |
| 1772 |
RescanOnePosRecord* first_record = ctxp->first_record; |
| 1773 |
const uint32_t prev_allele_ct = first_record->allele_ct; |
| 1774 |
if (prev_allele_ct != 2) { |
| 1775 |
if (prev_allele_ct > ctxp->write_allele_ct_max) { |
| 1776 |
ctxp->write_doomed_variant_ct += 1; |
| 1777 |
} else if (prev_allele_ct > ctxp->write_nondoomed_max_allele_ct) { |
| 1778 |
ctxp->write_nondoomed_max_allele_ct = prev_allele_ct; |
| 1779 |
} |
| 1780 |
} |
| 1781 |
if (ctxp->first_bp != UINT32_MAX) { |
| 1782 |
return kPglRetSuccess; |
| 1783 |
} |
| 1784 |
first_varid = first_record->variant_id; |
| 1785 |
} else { |
| 1786 |
if (!batch_size) { |
| 1787 |
return kPglRetSuccess; |
| 1788 |
} |
| 1789 |
// Sort variant IDs in ASCII or natural order depending on |
| 1790 |
// --sort-vars setting, then count number of alleles in merged |
| 1791 |
// variant when duplicates are present. |
| 1792 |
const uintptr_t bytes_to_round_up = (-R_CAST(uintptr_t, arena_bottom)) % sizeof(intptr_t); |
| 1793 |
const uintptr_t extra_bytes_needed = bytes_to_round_up + batch_size * sizeof(intptr_t); |
| 1794 |
if (unlikely(S_CAST(uintptr_t, arena_top - arena_bottom) < extra_bytes_needed)) { |
| 1795 |
return kPglRetNomem; |
| 1796 |
} |
| 1797 |
char** sorted_variant_ids = R_CAST(char**, &(arena_bottom[bytes_to_round_up])); |
| 1798 |
arena_bottom = &(arena_bottom[extra_bytes_needed]); |
| 1799 |
RescanOnePosRecord* record_iter = ctxp->first_record; |
| 1800 |
for (uint32_t uii = 0; uii != batch_size; ++uii) { |
| 1801 |
const uintptr_t rec_blen = record_iter->rec_blen; |
| 1802 |
sorted_variant_ids[uii] = record_iter->variant_id; |
| 1803 |
record_iter = R_CAST(RescanOnePosRecord*, &(R_CAST(unsigned char*, record_iter)[rec_blen])); |
| 1804 |
} |
| 1805 |
if (ctxp->sort_vars_ascii) { |
| 1806 |
StrptrArrSortOverread(batch_size, K_CAST(const char**, sorted_variant_ids)); |
| 1807 |
} else { |
| 1808 |
StrptrArrNsort(batch_size, K_CAST(const char**, sorted_variant_ids)); |
| 1809 |
} |
| 1810 |
char* cur_variant_id = sorted_variant_ids[0]; |
| 1811 |
uint32_t variant_idx_start = 0; |
| 1812 |
uint32_t next_allele_ct = container_of(cur_variant_id, RescanOnePosRecord, variant_id)->allele_ct; |
| 1813 |
uintptr_t allele_ct_limit = next_allele_ct; |
| 1814 |
for (uint32_t variant_idx_end = 1; ; ++variant_idx_end) { |
| 1815 |
if (!(variant_idx_end == batch_size)) { |
| 1816 |
char* next_variant_id = sorted_variant_ids[variant_idx_end]; |
| 1817 |
next_allele_ct = container_of(next_variant_id, RescanOnePosRecord, variant_id)->allele_ct; |
| 1818 |
if (strequal_overread(cur_variant_id, next_variant_id)) { |
| 1819 |
allele_ct_limit += next_allele_ct; |
| 1820 |
continue; |
| 1821 |
} |
| 1822 |
} |
| 1823 |
uint32_t merged_allele_ct = allele_ct_limit; |
| 1824 |
const uint32_t extra_read_variant_ct = variant_idx_end - variant_idx_start - 1; |
| 1825 |
if (extra_read_variant_ct) { |
| 1826 |
*nonwrite_variant_ctp += extra_read_variant_ct; |
| 1827 |
|
| 1828 |
// Count the number of distinct alleles across this group of |
| 1829 |
// same-position, same-ID variants by creating a strptr array and |
| 1830 |
// sorting it. (Could try a char** hash table instead if this is ever |
| 1831 |
// a bottleneck, but that seems exceedingly unlikely.) |
| 1832 |
unsigned char* arena_bottom_tmp = arena_bottom; |
| 1833 |
const char** alleles; |
| 1834 |
if (unlikely(arena_alloc_kcp(arena_top, allele_ct_limit, &arena_bottom_tmp, &alleles))) { |
| 1835 |
return kPglRetNomem; |
| 1836 |
} |
| 1837 |
const uint32_t variant_id_blen = strlen(cur_variant_id) + 1; |
| 1838 |
const char input_missing_geno_char = ctxp->input_missing_geno_char; |
| 1839 |
const char** alleles_iter = alleles; |
| 1840 |
uintptr_t missing_allele_ct = 0; |
| 1841 |
for (uint32_t variant_idx = variant_idx_start; variant_idx != variant_idx_end; ++variant_idx) { |
| 1842 |
char* tmp_variant_id = sorted_variant_ids[variant_idx]; |
| 1843 |
char* ref_allele = &(tmp_variant_id[variant_id_blen]); |
| 1844 |
if (((ref_allele[0] == '.') || (ref_allele[0] == input_missing_geno_char)) && (ref_allele[1] == '\0')) { |
| 1845 |
++missing_allele_ct; |
| 1846 |
} else { |
| 1847 |
*alleles_iter++ = ref_allele; |
| 1848 |
} |
| 1849 |
|
| 1850 |
const uint32_t extra_alt_ct = container_of(tmp_variant_id, RescanOnePosRecord, variant_id)->allele_ct - 2; |
| 1851 |
char* alt_iter = &(strnul(ref_allele)[1]); |
| 1852 |
for (uint32_t extra_alt_idx = 0; extra_alt_idx != extra_alt_ct; ++extra_alt_idx) { |
| 1853 |
char* cur_alt_end = AdvToDelim(alt_iter, ','); |
| 1854 |
*cur_alt_end = '\0'; |
| 1855 |
// Missing allele prohibited here. |
| 1856 |
*alleles_iter++ = alt_iter; |
| 1857 |
alt_iter = &(cur_alt_end[1]); |
| 1858 |
} |
| 1859 |
if (((alt_iter[0] == '.') || (alt_iter[0] == input_missing_geno_char)) && (alt_iter[1] == '\0')) { |
| 1860 |
++missing_allele_ct; |
| 1861 |
} else { |
| 1862 |
*alleles_iter++ = alt_iter; |
| 1863 |
} |
| 1864 |
} |
| 1865 |
allele_ct_limit -= missing_allele_ct; |
| 1866 |
StrptrArrSortOverread(allele_ct_limit, alleles); |
| 1867 |
merged_allele_ct = 0; |
| 1868 |
if (allele_ct_limit) { |
| 1869 |
merged_allele_ct = 1; |
| 1870 |
for (uintptr_t ulii = 1; ulii != allele_ct_limit; ++ulii) { |
| 1871 |
if (!strequal_overread(alleles[ulii], alleles[ulii - 1])) { |
| 1872 |
++merged_allele_ct; |
| 1873 |
} |
| 1874 |
} |
| 1875 |
} |
| 1876 |
// bugfix (8 Sep 2021): incorrect to perform this check if variant is |
| 1877 |
// being filtered out by --merge-max-alleles setting |
| 1878 |
if ((!ctxp->multiallelics_already_joined) && (merged_allele_ct <= ctxp->write_allele_ct_max)) { |
| 1879 |
const uint32_t merged_variant_ct = variant_idx_end - variant_idx_start; |
| 1880 |
if ((allele_ct_limit == merged_variant_ct * 2) && (merged_allele_ct == merged_variant_ct + 1) && (!missing_allele_ct)) { |
| 1881 |
// If all REF alleles are equal, sound the alarm. |
| 1882 |
char* first_ref_allele = &(sorted_variant_ids[variant_idx_start][variant_id_blen]); |
| 1883 |
const uint32_t ref_blen = strlen(first_ref_allele) + 1; |
| 1884 |
uint32_t variant_idx = variant_idx_start + 1; |
| 1885 |
for (; variant_idx != variant_idx_end; ++variant_idx) { |
| 1886 |
char* ref_allele = &(sorted_variant_ids[variant_idx][variant_id_blen]); |
| 1887 |
if (!memequal(ref_allele, first_ref_allele, ref_blen)) { |
| 1888 |
break; |
| 1889 |
} |
| 1890 |
} |
| 1891 |
if (unlikely(variant_idx == variant_idx_end)) { |
| 1892 |
const uint32_t variant_id_slen = variant_id_blen - 1; |
| 1893 |
char* write_iter = strcpya_k(g_logbuf, "Error: The biallelic variants with ID '"); |
| 1894 |
write_iter = memcpya(write_iter, cur_variant_id, variant_id_slen); |
| 1895 |
write_iter = strcpya_k(write_iter, "' at position "); |
| 1896 |
write_iter = chrtoa(ctxp->cip, prev_chr_code, write_iter); |
| 1897 |
*write_iter++ = ':'; |
| 1898 |
write_iter = u32toa(prev_bp, write_iter); |
| 1899 |
write_iter = strcpya_k(write_iter, " in "); |
| 1900 |
write_iter = strcpya(write_iter, ctxp->cur_fname); |
| 1901 |
write_iter = strcpya_k(write_iter, " appear to be the components of a 'split' multiallelic variant; if so, it must be 'joined' (with e.g. \"bcftools norm -m\") before a correct merge can occur. Alternatively, you can keep the variants separate by assigning them distinct IDs; unless you have very long indels, adding --set-all-var-ids"); |
| 1902 |
if (strequal_k(cur_variant_id, ".", variant_id_slen)) { |
| 1903 |
write_iter = strcpya(write_iter, " or --set-missing-var-ids"); |
| 1904 |
} |
| 1905 |
strcpy_k(write_iter, " to your merge command is a simple way to do this.\n"); |
| 1906 |
WordWrapB(0); |
| 1907 |
logerrputsb(); |
| 1908 |
return kPglRetInconsistentInput; |
| 1909 |
} |
| 1910 |
} |
| 1911 |
} |
| 1912 |
} |
| 1913 |
if (merged_allele_ct > 2) { |
| 1914 |
if (merged_allele_ct > ctxp->write_allele_ct_max) { |
| 1915 |
if (unlikely(ctxp->write_allele_ct_max == kPglMaxAlleleCt)) { |
| 1916 |
char* write_iter = strcpya_k(g_logbuf, "Error: Too many alleles for variant '"); |
| 1917 |
write_iter = strcpya(write_iter, cur_variant_id); |
| 1918 |
write_iter = strcpya_k(write_iter, "' at position "); |
| 1919 |
write_iter = chrtoa(ctxp->cip, prev_chr_code, write_iter); |
| 1920 |
*write_iter++ = ':'; |
| 1921 |
write_iter = u32toa(prev_bp, write_iter); |
| 1922 |
write_iter = strcpya_k(write_iter, " in "); |
| 1923 |
write_iter = strcpya(write_iter, ctxp->cur_fname); |
| 1924 |
strcpy_k(write_iter, ". (This " PROG_NAME_STR " build is limited to " PGL_MAX_ALLELE_CT_STR ".)\n"); |
| 1925 |
WordWrapB(0); |
| 1926 |
logerrputsb(); |
| 1927 |
return kPglRetNotYetSupported; |
| 1928 |
} |
| 1929 |
ctxp->write_doomed_variant_ct += 1; |
| 1930 |
} else if (merged_allele_ct > ctxp->write_nondoomed_max_allele_ct) { |
| 1931 |
ctxp->write_nondoomed_max_allele_ct = merged_allele_ct; |
| 1932 |
} |
| 1933 |
} |
| 1934 |
if (variant_idx_end == batch_size) { |
| 1935 |
break; |
| 1936 |
} |
| 1937 |
cur_variant_id = sorted_variant_ids[variant_idx_end]; |
| 1938 |
variant_idx_start = variant_idx_end; |
| 1939 |
allele_ct_limit = next_allele_ct; |
| 1940 |
} |
| 1941 |
|
| 1942 |
if (ctxp->first_bp != UINT32_MAX) { |
| 1943 |
return kPglRetSuccess; |
| 1944 |
} |
| 1945 |
first_varid = sorted_variant_ids[0]; |
| 1946 |
} |
| 1947 |
ctxp->first_chr_idx = prev_chr_code; |
| 1948 |
ctxp->first_bp = prev_bp; |
| 1949 |
const uint32_t first_id_blen = strlen(first_varid) + 1; |
| 1950 |
if (unlikely(pgl_malloc(first_id_blen, ctxp->first_varid_ptr))) { |
| 1951 |
return kPglRetNomem; |
| 1952 |
} |
| 1953 |
memcpy(*(ctxp->first_varid_ptr), first_varid, first_id_blen); |
| 1954 |
// Only need to natural-sort first and last positions. We manually reset |
| 1955 |
// this before any possibly-last call. |
| 1956 |
ctxp->sort_vars_ascii = 1; |
| 1957 |
return kPglRetSuccess; |
| 1958 |
} |
| 1959 |
|
| 1960 |
BoolErr ScrapeLastVarid(const RescanOnePosContext* ctxp, unsigned char* arena_bottom, uint32_t batch_size, char** last_varid_ptr) { |
| 1961 |
char* last_varid; |
| 1962 |
if (batch_size == 1) { |
| 1963 |
last_varid = ctxp->first_record->variant_id; |
| 1964 |
} else { |
| 1965 |
// See middle of RescanOnePos(). We look up the last element of the |
| 1966 |
// sorted_variant_ids array it created. |
| 1967 |
const uintptr_t bytes_to_round_up = (-R_CAST(uintptr_t, arena_bottom)) % sizeof(intptr_t); |
| 1968 |
char** sorted_variant_ids = R_CAST(char**, &(arena_bottom[bytes_to_round_up])); |
| 1969 |
last_varid = sorted_variant_ids[batch_size - 1]; |
| 1970 |
} |
| 1971 |
const uint32_t last_id_blen = strlen(last_varid) + 1; |
| 1972 |
free_cond(*last_varid_ptr); |
| 1973 |
if (unlikely(pgl_malloc(last_id_blen, last_varid_ptr))) { |
| 1974 |
return 1; |
| 1975 |
} |
| 1976 |
memcpy(*last_varid_ptr, last_varid, last_id_blen); |
| 1977 |
return 0; |
| 1978 |
} |
| 1979 |
|
| 1980 |
// cip->chr_file_order is filled with the final chromosome sort order. |
| 1981 |
// info_keys, pointed-to InfoVtype entries, and info_keys_htable are allocated |
| 1982 |
// at the end of bigstack. |
| 1983 |
static_assert(kCompressStreamBlock <= kDecompressChunkSize, "ScanPvarsAndMergeHeader() needs to be updated."); |
| 1984 |
PglErr ScanPvarsAndMergeHeader(const PmergeInfo* pmip, const char* missing_varid_match, MiscFlags misc_flags, uint32_t missing_varid_match_slen, char input_missing_geno_char, uint32_t max_thread_ct, SortMode sort_vars_mode, VaridTemplate* varid_templatep, VaridTemplate* varid_multi_templatep, VaridTemplate* varid_multi_nonsnp_templatep, char* outname, char* outname_end, PmergeInputFilesetLl** filesets_ptr, ChrInfo* cip, uintptr_t* fileset_ctp, uint32_t* info_has_g_keyp, const char* const** info_keys_ptr, uint32_t* info_key_ctp, uint32_t** info_keys_htablep, uint32_t* info_keys_htable_sizep, uint32_t* info_conflict_presentp) { |
| 1985 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1986 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 1987 |
const char* cur_fname = nullptr; |
| 1988 |
PglErr reterr = kPglRetSuccess; |
| 1989 |
char* cswritep = nullptr; |
| 1990 |
uintptr_t line_idx = 0; |
| 1991 |
CompressStreamState css; |
| 1992 |
PreinitCstream(&css); |
| 1993 |
TextStream txs; |
| 1994 |
PreinitTextStream(&txs); |
| 1995 |
{ |
| 1996 |
char* chr_output_name_buf = nullptr; |
| 1997 |
char* variant_id_buf = nullptr; |
| 1998 |
if (varid_templatep) { |
| 1999 |
// Don't know max_chr_blen yet. |
| 2000 |
if (unlikely(bigstack_end_alloc_c(kMaxIdBlen, &chr_output_name_buf))) { |
| 2001 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2002 |
} |
| 2003 |
varid_templatep->chr_output_name_buf = chr_output_name_buf; |
| 2004 |
uint32_t max_base_len = varid_templatep->base_len; |
| 2005 |
if (varid_multi_templatep) { |
| 2006 |
varid_multi_templatep->chr_output_name_buf = chr_output_name_buf; |
| 2007 |
if (varid_multi_templatep->base_len > max_base_len) { |
| 2008 |
max_base_len = varid_multi_templatep->base_len; |
| 2009 |
} |
| 2010 |
} |
| 2011 |
if (varid_multi_nonsnp_templatep) { |
| 2012 |
varid_multi_nonsnp_templatep->chr_output_name_buf = chr_output_name_buf; |
| 2013 |
if (varid_multi_nonsnp_templatep->base_len > max_base_len) { |
| 2014 |
max_base_len = varid_multi_nonsnp_templatep->base_len; |
| 2015 |
} |
| 2016 |
} |
| 2017 |
// strlen(CHROM) <= kMaxIdSlen + 3 (don't want to worry about "chr") |
| 2018 |
// strlen(POS) <= 10 |
| 2019 |
// also need null-terminator |
| 2020 |
if (unlikely(bigstack_end_alloc_c(kMaxIdSlen + 14 + 2 * varid_templatep->new_id_max_allele_slen, &variant_id_buf))) { |
| 2021 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2022 |
} |
| 2023 |
} |
| 2024 |
// We represent the chromosome-ordering graph as follows: |
| 2025 |
// - chr_outedges[] is indexed by chr_idx. When each chromosome is first |
| 2026 |
// seen, chr_outedges[x] is set to an empty bitarray allocated off the |
| 2027 |
// end of the arena. An x -> y edge is tracked by setting bit y in |
| 2028 |
// chr_outedges[x]. |
| 2029 |
// - chr_inedge_cts[] is also indexed by chr_idx, and tracks how many |
| 2030 |
// in-edges each chromosome has. |
| 2031 |
// TODO: this is unsuitable for files with a huge number of contigs; linked |
| 2032 |
// lists should work better in practice |
| 2033 |
uintptr_t* chr_present; |
| 2034 |
uintptr_t** chr_outedges; |
| 2035 |
uint32_t* chr_inedge_cts; |
| 2036 |
if (unlikely(bigstack_end_calloc_w(BitCtToWordCt(kMaxContigs), &chr_present) || |
| 2037 |
bigstack_end_calloc_wp(kMaxContigs, &chr_outedges) || |
| 2038 |
bigstack_end_calloc_u32(kMaxContigs, &chr_inedge_cts))) { |
| 2039 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2040 |
} |
| 2041 |
|
| 2042 |
const uintptr_t linebuf_capacity = MINV(kMaxLongLine, bigstack_left() / 4) + kDecompressChunkSize; |
| 2043 |
char* linebuf; |
| 2044 |
if (unlikely(bigstack_alloc_c(linebuf_capacity, &linebuf))) { |
| 2045 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2046 |
} |
| 2047 |
|
| 2048 |
const MergeXheaderMode merge_xheader_mode = pmip->merge_xheader_mode; |
| 2049 |
// Each entry is an xheader key, followed by a null terminator, followed by |
| 2050 |
// either the null-terminated remainder of the header line or a single |
| 2051 |
// ASCII code 1 to indicate a mismatch. The latter includes the original |
| 2052 |
// punctuation character ('=', ',', or '>') ending the key, but not the |
| 2053 |
// final newline. |
| 2054 |
// For '##' header lines where the first '=' character is followed by a |
| 2055 |
// '<', the key is everything from the second '#' up to the first comma in |
| 2056 |
// the '<' (or '>' if there is none) in the '<' expression; otherwise, the |
| 2057 |
// key is everything from the second '#' up to the '='. |
| 2058 |
// If there is no '=' character, or the header line starts with only one |
| 2059 |
// '#', the key is the entire line (excluding the newline) and the value is |
| 2060 |
// empty. |
| 2061 |
char** xheader_entries = nullptr; |
| 2062 |
uint32_t* xheader_entries_htable = nullptr; |
| 2063 |
uint32_t xheader_entry_ct = 0; |
| 2064 |
// xheader_entry_capacity == xheader_entry_htable_size / 2 |
| 2065 |
uint32_t xheader_entry_htable_size = 0; |
| 2066 |
if (merge_xheader_mode != kMergeXheaderModeErase) { |
| 2067 |
xheader_entry_htable_size = 512; |
| 2068 |
if (unlikely(bigstack_alloc_cp(xheader_entry_htable_size / 2, &xheader_entries) || |
| 2069 |
bigstack_alloc_u32(xheader_entry_htable_size, &xheader_entries_htable))) { |
| 2070 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2071 |
} |
| 2072 |
SetAllU32Arr(xheader_entry_htable_size, xheader_entries_htable); |
| 2073 |
} |
| 2074 |
unsigned char* arena_bottom = g_bigstack_base; |
| 2075 |
unsigned char* arena_top = g_bigstack_end; |
| 2076 |
|
| 2077 |
const uintptr_t fileset_ct = *fileset_ctp; |
| 2078 |
const uint32_t decompress_thread_ct = MAXV(max_thread_ct - 1, 1); |
| 2079 |
RescanOnePosContext ctx; |
| 2080 |
ctx.write_allele_ct_max = pmip->max_allele_ct? pmip->max_allele_ct : kPglMaxAlleleCt; |
| 2081 |
ctx.sort_vars_ascii = (sort_vars_mode == kSortAscii); |
| 2082 |
ctx.multiallelics_already_joined = (pmip->flags / kfPmergeMultiallelicsAlreadyJoined) & 1; |
| 2083 |
ctx.input_missing_geno_char = input_missing_geno_char; |
| 2084 |
ctx.cip = cip; |
| 2085 |
// For each .pvar, need to determine: |
| 2086 |
// - variant_ct |
| 2087 |
// - write_variant_ct (same as variant_ct unless chromosome filter or |
| 2088 |
// negative POS) |
| 2089 |
// - write_nondoomed_variant_ct (--merge-max-alleles applied) |
| 2090 |
// - max_line_blen |
| 2091 |
// - max_single_pos_ct |
| 2092 |
// - max_single_pos_blen |
| 2093 |
// - first and last (chr_idx, pos, varid) |
| 2094 |
// - nm_{qual,filter,info}_present, nz_cm_present |
| 2095 |
// - write_max_allele_ct |
| 2096 |
// possible todo: track seen realpaths, skip duplicates |
| 2097 |
// possible todo: after merging headers, split workspace into equal-size |
| 2098 |
// pieces and optimistically scan .pvar bodies in parallel. |
| 2099 |
// Any file that cannot be processed with the smaller |
| 2100 |
// per-thread workspace is retried afterward with the |
| 2101 |
// workspace merged again. cip and the chromosome-ordering |
| 2102 |
// graph would be shared and protected by a mutex; the |
| 2103 |
// string representation of the last-seen chromosome code |
| 2104 |
// would be cached to reduce the need for cip |
| 2105 |
// lookups/updates, and the chromosome-ordering graph would |
| 2106 |
// be heap-allocated using a sparse representation (unless |
| 2107 |
// we don't care about supporting higher compile-time |
| 2108 |
// kMaxContigs values, then we can just allocate a ~500MB |
| 2109 |
// matrix). |
| 2110 |
// Lots of overlap with LoadPvar(). |
| 2111 |
PmergeInputFilesetLl** filesets_iterp = filesets_ptr; |
| 2112 |
// Chromosome set must be either defined on the command line, or there must |
| 2113 |
// be equivalent chrSet header lines in *all* .pvar files. |
| 2114 |
ChrsetSource orig_chrset_source = cip->chrset_source; |
| 2115 |
uintptr_t null_fileset_ct = 0; |
| 2116 |
uint32_t info_pr_exists = 0; |
| 2117 |
uint32_t info_pr_nonflag_exists = 0; |
| 2118 |
uint32_t max_xheader_line_blen = 0; |
| 2119 |
uint32_t at_least_one_info_exists = 0; |
| 2120 |
uint32_t max_allele_overflow_slen = 0; |
| 2121 |
uintptr_t info_conflict_ct = 0; |
| 2122 |
for (uintptr_t fileset_idx = 0; fileset_idx != fileset_ct; ++fileset_idx) { |
| 2123 |
PmergeInputFilesetLl* cur_fileset = *filesets_iterp; |
| 2124 |
cur_fname = cur_fileset->pvar_fname; |
| 2125 |
reterr = TextStreamOpenEx(cur_fname, kMaxLongLine, linebuf_capacity, decompress_thread_ct, nullptr, linebuf, &txs); |
| 2126 |
if (unlikely(reterr)) { |
| 2127 |
goto ScanPvarsAndMergeHeader_ret_TSTREAM_FAIL; |
| 2128 |
} |
| 2129 |
uint32_t max_line_blen = 0; |
| 2130 |
char* line_start = TextLineEnd(&txs); |
| 2131 |
uint32_t info_pr_exists_here = 0; |
| 2132 |
uint32_t chrset_seen_in_this_file = 0; |
| 2133 |
for (line_idx = 1; ; ++line_idx) { |
| 2134 |
if (unlikely(!TextGetUnsafe2(&txs, &line_start))) { |
| 2135 |
if (TextStreamErrcode2(&txs, &reterr)) { |
| 2136 |
goto ScanPvarsAndMergeHeader_ret_TSTREAM_FAIL; |
| 2137 |
} |
| 2138 |
logerrprintf("Error: No variants in %s.\n", cur_fname); |
| 2139 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT; |
| 2140 |
} |
| 2141 |
if ((line_start[0] != '#') || tokequal_k(line_start, "#CHROM")) { |
| 2142 |
break; |
| 2143 |
} |
| 2144 |
char* key_start = &(line_start[1]); |
| 2145 |
// Contents of ##chrSet and ##INFO=<ID=PR,...> header lines matter even |
| 2146 |
// when we're not propagating the header. |
| 2147 |
if (StrStartsWithUnsafe(key_start, "#chrSet=<")) { |
| 2148 |
if (unlikely(chrset_seen_in_this_file)) { |
| 2149 |
snprintf(g_logbuf, kLogbufSize, "Error: Multiple ##chrSet header lines in %s.\n", cur_fname); |
| 2150 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2151 |
} |
| 2152 |
reterr = ReadChrsetHeaderLine(&(key_start[strlen("#chrSet=<")]), cur_fname, misc_flags, line_idx, cip); |
| 2153 |
if (unlikely(reterr)) { |
| 2154 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2155 |
} |
| 2156 |
if (cip->chrset_source != kChrsetSourceCmdline) { |
| 2157 |
if (unlikely(fileset_idx && (cip->chrset_source == kChrsetSourceDefault))) { |
| 2158 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENTLY_PRESENT_CHRSET; |
| 2159 |
} |
| 2160 |
orig_chrset_source = kChrsetSourceAnotherFile; |
| 2161 |
cip->chrset_source = kChrsetSourceCmdline; |
| 2162 |
} |
| 2163 |
chrset_seen_in_this_file = 1; |
| 2164 |
} |
| 2165 |
if (StrStartsWithUnsafe(key_start, "#INFO=<")) { |
| 2166 |
char* info_read_iter = &(key_start[strlen("#INFO=<")]); |
| 2167 |
char* idval; |
| 2168 |
uint32_t id_slen; |
| 2169 |
if (unlikely(HkvlineId(&info_read_iter, &idval, &id_slen))) { |
| 2170 |
snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s is malformed.\n", line_idx, cur_fname); |
| 2171 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2172 |
} |
| 2173 |
if (strequal_k(idval, "PR", id_slen)) { |
| 2174 |
char* typestr; |
| 2175 |
uint32_t type_slen; |
| 2176 |
if (unlikely(HkvlineFind(info_read_iter, "Type", &typestr, &type_slen))) { |
| 2177 |
snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s is malformed.\n", line_idx, cur_fname); |
| 2178 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2179 |
} |
| 2180 |
if (strequal_k(typestr, "Flag", type_slen)) { |
| 2181 |
if (unlikely(info_pr_nonflag_exists)) { |
| 2182 |
// Other conflicting keys can be skipped under |
| 2183 |
// "--merge-info-mode nm-match", but we don't want to remove |
| 2184 |
// the INFO/PR key if it's present. |
| 2185 |
logerrputs("Error: Inconsistent INFO/PR header lines across --pmerge[-list] files.\n"); |
| 2186 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT; |
| 2187 |
} |
| 2188 |
info_pr_exists = 1; |
| 2189 |
info_pr_exists_here = 1; |
| 2190 |
line_start = AdvPastDelim(&(typestr[type_slen]), '\n'); |
| 2191 |
continue; |
| 2192 |
} |
| 2193 |
if (unlikely(info_pr_exists)) { |
| 2194 |
logerrputs("Error: Inconsistent INFO/PR header lines across --pmerge[-list] files.\n"); |
| 2195 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT; |
| 2196 |
} |
| 2197 |
info_pr_nonflag_exists = 1; |
| 2198 |
} |
| 2199 |
if (!xheader_entries_htable) { |
| 2200 |
line_start = AdvPastDelim(info_read_iter, '\n'); |
| 2201 |
continue; |
| 2202 |
} |
| 2203 |
} else { |
| 2204 |
// if the "pvar file" was actually a VCF, suppress the same lines |
| 2205 |
// we'd suppress when importing with --vcf. |
| 2206 |
if ((!xheader_entries_htable) || |
| 2207 |
StrStartsWithUnsafe(key_start, "#fileformat=") || |
| 2208 |
StrStartsWithUnsafe(key_start, "#fileDate=") || |
| 2209 |
StrStartsWithUnsafe(key_start, "#source=") || |
| 2210 |
StrStartsWithUnsafe(key_start, "#FORMAT=")) { |
| 2211 |
line_start = AdvPastDelim(line_start, '\n'); |
| 2212 |
continue; |
| 2213 |
} |
| 2214 |
} |
| 2215 |
char* value_start; |
| 2216 |
char* value_end; |
| 2217 |
if (line_start[1] != '#') { |
| 2218 |
value_start = AdvToDelim(key_start, '\n'); |
| 2219 |
value_end = value_start; |
| 2220 |
} else { |
| 2221 |
value_start = strchrnul_n(&(key_start[1]), '='); |
| 2222 |
if (*value_start == '\n') { |
| 2223 |
value_end = value_start; |
| 2224 |
} else { |
| 2225 |
if (value_start[1] == '<') { |
| 2226 |
char* hline_kv_start = &(value_start[2]); |
| 2227 |
if (unlikely(HkvlineForceIdFirst(arena_top - arena_bottom, &(value_start[2]), arena_bottom))) { |
| 2228 |
snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s is malformed.\n", line_idx, cur_fname); |
| 2229 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2230 |
} |
| 2231 |
value_start = strchrnul2_n(hline_kv_start, ',', '>'); |
| 2232 |
if (unlikely(*value_start == '\n')) { |
| 2233 |
snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s is malformed (value starts with '<', but there is no closing '>').\n", line_idx, cur_fname); |
| 2234 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2235 |
} |
| 2236 |
} |
| 2237 |
value_end = AdvToDelim(&(value_start[1]), '\n'); |
| 2238 |
} |
| 2239 |
} |
| 2240 |
const uint32_t key_slen = value_start - key_start; |
| 2241 |
if (key_slen) { |
| 2242 |
const uint32_t value_slen = value_end - value_start; |
| 2243 |
// might want to move this logic into plink2_common |
| 2244 |
for (uint32_t hashval = Hashceil(key_start, key_slen, xheader_entry_htable_size); ; ) { |
| 2245 |
const uint32_t cur_htable_entry = xheader_entries_htable[hashval]; |
| 2246 |
if (cur_htable_entry == UINT32_MAX) { |
| 2247 |
if (unlikely(PtrWSubCk(arena_bottom, key_slen + value_slen + 2, &arena_top))) { |
| 2248 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2249 |
} |
| 2250 |
char* entry_start = R_CAST(char*, arena_top); |
| 2251 |
char* entry_iter = memcpyax(entry_start, key_start, key_slen, '\0'); |
| 2252 |
memcpyx(entry_iter, value_start, value_slen, '\0'); |
| 2253 |
if (xheader_entry_ct * 2 < xheader_entry_htable_size) { |
| 2254 |
xheader_entries[xheader_entry_ct] = entry_start; |
| 2255 |
xheader_entries_htable[hashval] = xheader_entry_ct; |
| 2256 |
++xheader_entry_ct; |
| 2257 |
} else { |
| 2258 |
// resize |
| 2259 |
uint32_t next_xheader_table_size; |
| 2260 |
if (xheader_entry_htable_size < 0x80000000U) { |
| 2261 |
next_xheader_table_size = xheader_entry_htable_size * 2; |
| 2262 |
} else if (likely(xheader_entry_htable_size == 0x80000000U)) { |
| 2263 |
next_xheader_table_size = 0xfffffffaU; |
| 2264 |
} else { |
| 2265 |
logerrputs("Error: --pmerge[-list] is limited to 2^31 - 3 header lines.\n"); |
| 2266 |
reterr = kPglRetNotYetSupported; |
| 2267 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2268 |
} |
| 2269 |
if (unlikely(S_CAST(uintptr_t, arena_top - arena_bottom) < (next_xheader_table_size - xheader_entry_htable_size) * ((sizeof(intptr_t) / 2) + sizeof(int32_t)))) { |
| 2270 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2271 |
} |
| 2272 |
xheader_entry_htable_size = next_xheader_table_size; |
| 2273 |
xheader_entries_htable = R_CAST(uint32_t*, &(xheader_entries[xheader_entry_htable_size / 2])); |
| 2274 |
arena_bottom = R_CAST(unsigned char*, &(xheader_entries_htable[xheader_entry_htable_size])); |
| 2275 |
SetAllU32Arr(xheader_entry_htable_size, xheader_entries_htable); |
| 2276 |
xheader_entries[xheader_entry_ct] = entry_start; |
| 2277 |
++xheader_entry_ct; |
| 2278 |
for (uint32_t entry_idx = 0; entry_idx != xheader_entry_ct; ++entry_idx) { |
| 2279 |
const char* cur_entry = xheader_entries[entry_idx]; |
| 2280 |
HtableAddNondup(cur_entry, strlen(cur_entry), xheader_entry_htable_size, entry_idx, xheader_entries_htable); |
| 2281 |
} |
| 2282 |
} |
| 2283 |
break; |
| 2284 |
} |
| 2285 |
if (strequal_unsafe(xheader_entries[cur_htable_entry], key_start, key_slen)) { |
| 2286 |
char* entry_value_start = &(xheader_entries[cur_htable_entry][key_slen + 1]); |
| 2287 |
if (merge_xheader_mode == kMergeXheaderModeMatch) { |
| 2288 |
// entry_value_start[0] == 1 marks a conflict. |
| 2289 |
if (entry_value_start[0] != 1) { |
| 2290 |
if (!strequal_unsafe(entry_value_start, value_start, value_slen)) { |
| 2291 |
info_conflict_ct += StrStartsWithUnsafe(key_start, "#INFO=<"); |
| 2292 |
entry_value_start[0] = 1; |
| 2293 |
} |
| 2294 |
} |
| 2295 |
} else if (StrStartsWithUnsafe(key_start, "#INFO=<")) { |
| 2296 |
// Check for possible Number= incompatibility. |
| 2297 |
char* existing_read_iter = &(entry_value_start[1]); |
| 2298 |
char* numstr; |
| 2299 |
uint32_t num_slen; |
| 2300 |
int32_t existing_info_vtype_num; |
| 2301 |
if (unlikely(HkvlineFind(existing_read_iter, "Number", &numstr, &num_slen) || |
| 2302 |
FillInfoVtypeNum(numstr, num_slen, info_has_g_keyp, &existing_info_vtype_num))) { |
| 2303 |
char* write_iter = strcpya_k(g_logbuf, "Error: --pmerge"); |
| 2304 |
if (pmip->list_fname) { |
| 2305 |
write_iter = strcpya_k(write_iter, "-list"); |
| 2306 |
} |
| 2307 |
write_iter = strcpya_k(write_iter, ": First INFO/"); |
| 2308 |
write_iter = memcpya(write_iter, &(key_start[strlen("#INFO=<ID=")]), key_slen - strlen("#INFO=<ID=")); |
| 2309 |
strcpy_k(write_iter, " header line is malformed or unrecognized.\n"); |
| 2310 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2311 |
} |
| 2312 |
char* cur_read_iter = &(value_start[1]); |
| 2313 |
int32_t suppressed_info_vtype_num; |
| 2314 |
if (unlikely(HkvlineFind(cur_read_iter, "Number", &numstr, &num_slen) || |
| 2315 |
FillInfoVtypeNum(numstr, num_slen, info_has_g_keyp, &suppressed_info_vtype_num))) { |
| 2316 |
snprintf(g_logbuf, kLogbufSize, "Error: Header line %" PRIuPTR " of %s is malformed.\n", line_idx, cur_fname); |
| 2317 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2318 |
} |
| 2319 |
if ((existing_info_vtype_num != suppressed_info_vtype_num) && |
| 2320 |
(existing_info_vtype_num != kInfoVtypeUnknown) && |
| 2321 |
(suppressed_info_vtype_num != kInfoVtypeUnknown)) { |
| 2322 |
char* write_iter = strcpya_k(g_logbuf, "Warning: INFO/"); |
| 2323 |
write_iter = memcpya(write_iter, &(key_start[strlen("#INFO=<ID=")]), key_slen - strlen("#INFO=<ID=")); |
| 2324 |
write_iter = strcpya_k(write_iter, " header entry on line "); |
| 2325 |
write_iter = wtoa(line_idx, write_iter); |
| 2326 |
write_iter = strcpya_k(write_iter, " of "); |
| 2327 |
write_iter = strcpya(write_iter, cur_fname); |
| 2328 |
strcpy_k(write_iter, " has a different Number= value than an earlier file; this key may be merged incorrectly, if the merge completes at all.\n"); |
| 2329 |
WordWrapB(0); |
| 2330 |
logerrputsb(); |
| 2331 |
} |
| 2332 |
// possible todo: also warn on most type mismatches |
| 2333 |
} |
| 2334 |
break; |
| 2335 |
} |
| 2336 |
if (++hashval == xheader_entry_htable_size) { |
| 2337 |
hashval = 0; |
| 2338 |
} |
| 2339 |
} |
| 2340 |
} |
| 2341 |
char* line_end = &(value_end[1]); |
| 2342 |
uint32_t line_blen = line_end - line_start; |
| 2343 |
if (max_line_blen < line_blen) { |
| 2344 |
max_line_blen = line_blen; |
| 2345 |
} |
| 2346 |
line_start = line_end; |
| 2347 |
} |
| 2348 |
if (unlikely((orig_chrset_source == kChrsetSourceAnotherFile) && (!chrset_seen_in_this_file))) { |
| 2349 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENTLY_PRESENT_CHRSET; |
| 2350 |
} |
| 2351 |
if (!fileset_idx) { |
| 2352 |
FinalizeChrset(misc_flags, cip); |
| 2353 |
} |
| 2354 |
if (max_xheader_line_blen < max_line_blen) { |
| 2355 |
max_xheader_line_blen = max_line_blen; |
| 2356 |
} |
| 2357 |
// [-1] = #CHROM (must be first column) |
| 2358 |
// [0] = POS |
| 2359 |
// [1] = ID |
| 2360 |
// [2] = REF |
| 2361 |
// [3] = ALT |
| 2362 |
// [4] = QUAL |
| 2363 |
// [5] = FILTER |
| 2364 |
// [6] = INFO |
| 2365 |
// [7] = CM (usually absent) |
| 2366 |
uint32_t col_skips[8]; |
| 2367 |
uint32_t col_types[8]; |
| 2368 |
uint32_t no_multiallelic_allowed = 0; |
| 2369 |
uint32_t check_qual = 0; |
| 2370 |
uint32_t check_filter = 0; |
| 2371 |
uint32_t info_col_present = 0; |
| 2372 |
uint32_t check_info = 0; |
| 2373 |
uint32_t check_cm = 0; |
| 2374 |
uint32_t relevant_postchr_col_ct; |
| 2375 |
if (line_start[0] == '#') { |
| 2376 |
char* token_end = &(line_start[6]); |
| 2377 |
uint32_t found_header_bitset = 0; |
| 2378 |
relevant_postchr_col_ct = 0; |
| 2379 |
char* token_start; |
| 2380 |
for (uint32_t col_idx = 1; ; ++col_idx) { |
| 2381 |
token_start = FirstNonTspace(token_end); |
| 2382 |
if (IsEolnKns(*token_start)) { |
| 2383 |
break; |
| 2384 |
} |
| 2385 |
token_end = CurTokenEnd(token_start); |
| 2386 |
const uint32_t token_slen = token_end - token_start; |
| 2387 |
uint32_t cur_col_type; |
| 2388 |
if (token_slen <= 3) { |
| 2389 |
if (token_slen == 3) { |
| 2390 |
if (memequal_sk(token_start, "POS")) { |
| 2391 |
cur_col_type = 0; |
| 2392 |
} else if (memequal_sk(token_start, "REF")) { |
| 2393 |
cur_col_type = 2; |
| 2394 |
} else if (memequal_sk(token_start, "ALT")) { |
| 2395 |
cur_col_type = 3; |
| 2396 |
} else { |
| 2397 |
continue; |
| 2398 |
} |
| 2399 |
} else if (token_slen == 2) { |
| 2400 |
if (memequal_sk(token_start, "ID")) { |
| 2401 |
cur_col_type = 1; |
| 2402 |
} else if (memequal_sk(token_start, "CM")) { |
| 2403 |
cur_col_type = 7; |
| 2404 |
check_cm = 1; |
| 2405 |
} else { |
| 2406 |
continue; |
| 2407 |
} |
| 2408 |
} else { |
| 2409 |
continue; |
| 2410 |
} |
| 2411 |
} else if (strequal_k(token_start, "QUAL", token_slen)) { |
| 2412 |
if (pmip->merge_qual_mode == kMergeQualModeErase) { |
| 2413 |
continue; |
| 2414 |
} |
| 2415 |
cur_col_type = 4; |
| 2416 |
check_qual = 1; |
| 2417 |
} else if (strequal_k(token_start, "INFO", token_slen)) { |
| 2418 |
info_col_present = 1; |
| 2419 |
if (pmip->merge_info_mode == kMergeInfoCmModeErase) { |
| 2420 |
continue; |
| 2421 |
} |
| 2422 |
cur_col_type = 6; |
| 2423 |
check_info = 1; |
| 2424 |
} else if (token_slen == 6) { |
| 2425 |
if (memequal_sk(token_start, "FILTER")) { |
| 2426 |
if (pmip->merge_filter_mode == kMergeFilterModeErase) { |
| 2427 |
continue; |
| 2428 |
} |
| 2429 |
cur_col_type = 5; |
| 2430 |
check_filter = 1; |
| 2431 |
} else if (memequal_sk(token_start, "FORMAT")) { |
| 2432 |
break; |
| 2433 |
} else { |
| 2434 |
continue; |
| 2435 |
} |
| 2436 |
} else { |
| 2437 |
continue; |
| 2438 |
} |
| 2439 |
const uint32_t cur_col_type_shifted = 1 << cur_col_type; |
| 2440 |
if (unlikely(found_header_bitset & cur_col_type_shifted)) { |
| 2441 |
// known token, so no overflow danger |
| 2442 |
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '"); |
| 2443 |
write_iter = memcpya(write_iter, token_start, token_slen); |
| 2444 |
write_iter = strcpya_k(write_iter, "' on line "); |
| 2445 |
write_iter = wtoa(line_idx, write_iter); |
| 2446 |
write_iter = strcpya_k(write_iter, " of "); |
| 2447 |
write_iter = strcpya(write_iter, cur_fname); |
| 2448 |
memcpy_k(write_iter, ".\n\0", 4); |
| 2449 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2450 |
} |
| 2451 |
found_header_bitset |= cur_col_type_shifted; |
| 2452 |
col_skips[relevant_postchr_col_ct] = col_idx; |
| 2453 |
col_types[relevant_postchr_col_ct++] = cur_col_type; |
| 2454 |
} |
| 2455 |
if (unlikely((found_header_bitset & 0x0f) != 0x0f)) { |
| 2456 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of %s. (POS, ID, REF, and ALT are required.)\n", line_idx, cur_fname); |
| 2457 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2458 |
} |
| 2459 |
for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) { |
| 2460 |
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1]; |
| 2461 |
} |
| 2462 |
// skip this line in main loop |
| 2463 |
char* line_end = AdvPastDelim(token_start, '\n'); |
| 2464 |
const uint32_t line_blen = line_end - line_start; |
| 2465 |
if (max_line_blen < line_blen) { |
| 2466 |
max_line_blen = line_blen; |
| 2467 |
} |
| 2468 |
line_start = line_end; |
| 2469 |
++line_idx; |
| 2470 |
} else { |
| 2471 |
no_multiallelic_allowed = 1; |
| 2472 |
col_skips[0] = 1; |
| 2473 |
col_skips[1] = 1; |
| 2474 |
col_skips[2] = 1; |
| 2475 |
col_skips[3] = 1; |
| 2476 |
col_types[0] = 1; |
| 2477 |
const char* fifth_col_start = NextTokenMult(line_start, 4); |
| 2478 |
if (unlikely(!fifth_col_start)) { |
| 2479 |
goto ScanPvarsAndMergeHeader_ret_MISSING_TOKENS; |
| 2480 |
} |
| 2481 |
const char* sixth_col_start = NextToken(fifth_col_start); |
| 2482 |
if (!sixth_col_start) { |
| 2483 |
relevant_postchr_col_ct = 4; |
| 2484 |
col_types[1] = 0; |
| 2485 |
col_types[2] = 3; |
| 2486 |
col_types[3] = 2; |
| 2487 |
} else { |
| 2488 |
relevant_postchr_col_ct = 5; |
| 2489 |
col_skips[4] = 1; |
| 2490 |
col_types[1] = 7; |
| 2491 |
col_types[2] = 0; |
| 2492 |
col_types[3] = 3; |
| 2493 |
col_types[4] = 2; |
| 2494 |
check_cm = 1; |
| 2495 |
} |
| 2496 |
} |
| 2497 |
// In order to perform 'concatenation' with only one more pass through |
| 2498 |
// each .pvar, without making that yield a different result than |
| 2499 |
// general-purpose merge, we want to track (variant ID, alleles) for |
| 2500 |
// each variant in the current group of same-position variant(s). (It is |
| 2501 |
// not necessary to distinguish REF/ALT here.) This is necessary to |
| 2502 |
// compute write_nondoomed_variant_ct and write_nondoomed_max_allele_ct |
| 2503 |
// accurately, both of which must be known before the .pgen writer can be |
| 2504 |
// constructed. |
| 2505 |
// |
| 2506 |
// We store this as a sequence of records growing up from |
| 2507 |
// arena_bottom_mark, structured as follows: |
| 2508 |
// 4 byte uint32_t, storing record length in bytes |
| 2509 |
// AlleleCode storing extra_alt_ct |
| 2510 |
// null-terminated variant ID |
| 2511 |
// null-terminated REF |
| 2512 |
// null-terminated ALT, internally still comma-separated |
| 2513 |
unsigned char* arena_bottom_mark = arena_bottom; |
| 2514 |
const uint32_t prohibit_extra_chr = (misc_flags / kfMiscProhibitExtraChr) & 1; |
| 2515 |
const uint32_t filter_count_needed = (pmip->merge_filter_mode == kMergeFilterModeNonpassUnion) || (pmip->merge_filter_mode == kMergeFilterModeNmMatch); |
| 2516 |
const uintptr_t line_idx_body_start = line_idx; |
| 2517 |
uint32_t nonwrite_variant_ct = 0; |
| 2518 |
ctx.cur_fname = cur_fname; |
| 2519 |
ctx.first_record = R_CAST(RescanOnePosRecord*, arena_bottom_mark); |
| 2520 |
ctx.write_doomed_variant_ct = 0; |
| 2521 |
ctx.write_nondoomed_max_allele_ct = 2; |
| 2522 |
// ctx.first_chr_idx = 0; |
| 2523 |
ctx.first_bp = UINT32_MAX; |
| 2524 |
ctx.first_varid_ptr = &(cur_fileset->first_varid); |
| 2525 |
uint32_t cur_single_pos_ct = 0; |
| 2526 |
uint32_t max_single_pos_ct = 1; |
| 2527 |
uintptr_t cur_single_pos_blen = 0; |
| 2528 |
uintptr_t max_single_pos_blen = 0; |
| 2529 |
uint32_t read_max_allele_ct = 2; |
| 2530 |
uint32_t read_max_nonpass_filter_ct = 0; |
| 2531 |
uint32_t prev_chr_code = UINT32_MAX; |
| 2532 |
int32_t prev_bp = 0; |
| 2533 |
cur_fileset->nm_qual_exists = 0; |
| 2534 |
cur_fileset->nm_filter_exists = 0; |
| 2535 |
cur_fileset->nm_info_exists = 0; |
| 2536 |
cur_fileset->nz_cm_present = 0; |
| 2537 |
|
| 2538 |
info_pr_exists_here = info_pr_exists_here && info_col_present; |
| 2539 |
if (unlikely((cur_fileset->nonref_flags_storage == 0) && info_pr_exists_here)) { |
| 2540 |
// Provisional-vs.-not REF status is directly relevant during merge. |
| 2541 |
// It's of limited importance for most other operations, so |
| 2542 |
// Plink2Core() only prints a warning. |
| 2543 |
snprintf(g_logbuf, kLogbufSize, "Error: %s indicates that provisional-REF information (required by --pmerge%s) is stored in the companion .pvar, but that .pvar lacks an INFO/PR header line and/or an INFO column.\n", cur_fileset->pgen_fname, pmip->list_fname? "-list" : ""); |
| 2544 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT_WW; |
| 2545 |
} |
| 2546 |
cur_fileset->pvar_info_pr_exists = info_pr_exists_here; |
| 2547 |
for (; TextGetUnsafe2(&txs, &line_start); ++line_idx) { |
| 2548 |
if (unlikely(line_start[0] == '#')) { |
| 2549 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and if a #CHROM header line is present it must denote the end of the header block.)\n", line_idx, cur_fname); |
| 2550 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2551 |
} |
| 2552 |
char* first_token_end = CurTokenEnd(line_start); |
| 2553 |
if (unlikely(*first_token_end == '\n')) { |
| 2554 |
goto ScanPvarsAndMergeHeader_ret_MISSING_TOKENS; |
| 2555 |
} |
| 2556 |
uint32_t cur_chr_code; |
| 2557 |
reterr = GetOrAddChrCodeDestructive(cur_fname, line_idx, prohibit_extra_chr, line_start, first_token_end, cip, &cur_chr_code); |
| 2558 |
if (unlikely(reterr)) { |
| 2559 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2560 |
} |
| 2561 |
if (cur_chr_code != prev_chr_code) { |
| 2562 |
SetBit(cur_chr_code, chr_present); |
| 2563 |
if (chr_output_name_buf) { |
| 2564 |
char* chr_name_end = chrtoa(cip, cur_chr_code, chr_output_name_buf); |
| 2565 |
const uint32_t chr_slen = chr_name_end - chr_output_name_buf; |
| 2566 |
const int32_t chr_slen_delta = chr_slen - varid_templatep->chr_slen; |
| 2567 |
varid_templatep->chr_slen = chr_slen; |
| 2568 |
varid_templatep->base_len += chr_slen_delta; |
| 2569 |
if (varid_multi_templatep) { |
| 2570 |
varid_multi_templatep->chr_slen = chr_slen; |
| 2571 |
varid_multi_templatep->base_len += chr_slen_delta; |
| 2572 |
} |
| 2573 |
if (varid_multi_nonsnp_templatep) { |
| 2574 |
varid_multi_nonsnp_templatep->chr_slen = chr_slen; |
| 2575 |
varid_multi_nonsnp_templatep->base_len += chr_slen_delta; |
| 2576 |
} |
| 2577 |
} |
| 2578 |
if (prev_chr_code != UINT32_MAX) { |
| 2579 |
if (cur_single_pos_ct) { |
| 2580 |
// Rescan now, before clobbering prev_chr_code/prev_bp. |
| 2581 |
if (max_single_pos_ct < cur_single_pos_ct) { |
| 2582 |
max_single_pos_ct = cur_single_pos_ct; |
| 2583 |
} |
| 2584 |
if (max_single_pos_blen < cur_single_pos_blen) { |
| 2585 |
max_single_pos_blen = cur_single_pos_blen; |
| 2586 |
} |
| 2587 |
// This could be the last included variant in the entire file |
| 2588 |
// (e.g. all remaining POS values could be -1), in which case we |
| 2589 |
// need to save off last_varid now. |
| 2590 |
ctx.sort_vars_ascii = (sort_vars_mode == kSortAscii); |
| 2591 |
reterr = RescanOnePos(arena_top, cur_single_pos_ct, prev_chr_code, prev_bp, arena_bottom, &ctx, &nonwrite_variant_ct); |
| 2592 |
if (unlikely(reterr)) { |
| 2593 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2594 |
} |
| 2595 |
ctx.sort_vars_ascii = 1; |
| 2596 |
if (unlikely(ScrapeLastVarid(&ctx, arena_bottom, cur_single_pos_ct, &cur_fileset->last_varid))) { |
| 2597 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2598 |
} |
| 2599 |
cur_fileset->last_chr_idx = prev_chr_code; |
| 2600 |
cur_fileset->last_pos = prev_bp; |
| 2601 |
} |
| 2602 |
arena_bottom = arena_bottom_mark; |
| 2603 |
cur_single_pos_ct = 0; |
| 2604 |
cur_single_pos_blen = 0; |
| 2605 |
// Add prev_chr_code -> cur_chr_code graph edge. |
| 2606 |
if (!chr_outedges[prev_chr_code]) { |
| 2607 |
ArenaEndSet(arena_top, &arena_top); |
| 2608 |
if (unlikely(arena_end_alloc_w(arena_bottom, BitCtToWordCt(kMaxContigs), &arena_top, &(chr_outedges[prev_chr_code])))) { |
| 2609 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2610 |
} |
| 2611 |
ZeroWArr(BitCtToWordCt(kMaxContigs), chr_outedges[prev_chr_code]); |
| 2612 |
} |
| 2613 |
if (!IsSet(chr_outedges[prev_chr_code], cur_chr_code)) { |
| 2614 |
SetBit(cur_chr_code, chr_outedges[prev_chr_code]); |
| 2615 |
chr_inedge_cts[cur_chr_code] += 1; |
| 2616 |
} |
| 2617 |
} |
| 2618 |
prev_chr_code = cur_chr_code; |
| 2619 |
// no explicit split-chr check needed here, we'll error out anyway |
| 2620 |
// during topological sort |
| 2621 |
prev_bp = -1; |
| 2622 |
} |
| 2623 |
|
| 2624 |
*first_token_end = '\t'; |
| 2625 |
char* token_ptrs[8]; |
| 2626 |
uint32_t token_slens[8]; |
| 2627 |
char* line_iter = TokenLex(first_token_end, col_types, col_skips, relevant_postchr_col_ct, token_ptrs, token_slens); |
| 2628 |
if (unlikely(!line_iter)) { |
| 2629 |
goto ScanPvarsAndMergeHeader_ret_MISSING_TOKENS; |
| 2630 |
} |
| 2631 |
const char* alt_start = token_ptrs[3]; |
| 2632 |
const uint32_t alt_slen = token_slens[3]; |
| 2633 |
const uint32_t extra_alt_ct = CountByte(alt_start, ',', alt_slen); |
| 2634 |
if (unlikely(extra_alt_ct >= kPglMaxAltAlleleCt)) { |
| 2635 |
logerrprintfww("Error: Too many ALT alleles on line %" PRIuPTR " of %s. (This " PROG_NAME_STR " build is limited to " PGL_MAX_ALT_ALLELE_CT_STR ".)\n", line_idx, cur_fname); |
| 2636 |
reterr = kPglRetNotYetSupported; |
| 2637 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2638 |
} |
| 2639 |
|
| 2640 |
char* line_end = AdvPastDelim(line_iter, '\n'); |
| 2641 |
uint32_t line_blen = line_end - line_start; |
| 2642 |
if (max_line_blen < line_blen) { |
| 2643 |
max_line_blen = line_blen; |
| 2644 |
} |
| 2645 |
line_start = line_end; |
| 2646 |
|
| 2647 |
if (!IsSet(cip->chr_mask, cur_chr_code)) { |
| 2648 |
++nonwrite_variant_ct; |
| 2649 |
continue; |
| 2650 |
} |
| 2651 |
int32_t cur_bp; |
| 2652 |
if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp))) { |
| 2653 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid POS on line %" PRIuPTR " of %s.\n", line_idx, cur_fname); |
| 2654 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2655 |
} |
| 2656 |
const uint32_t ref_slen = token_slens[2]; |
| 2657 |
char* variant_id = token_ptrs[1]; |
| 2658 |
uint32_t id_slen = token_slens[1]; |
| 2659 |
if (varid_templatep && ((!missing_varid_match_slen) || ((id_slen == missing_varid_match_slen) && memequal(variant_id, missing_varid_match, missing_varid_match_slen)))) { |
| 2660 |
const VaridTemplate* cur_varid_templatep = varid_templatep; |
| 2661 |
if (extra_alt_ct && (varid_multi_templatep || varid_multi_nonsnp_templatep)) { |
| 2662 |
if (varid_multi_templatep) { |
| 2663 |
cur_varid_templatep = varid_multi_templatep; |
| 2664 |
} |
| 2665 |
if (varid_multi_nonsnp_templatep) { |
| 2666 |
if ((ref_slen > 1) || (token_slens[3] != 2 * extra_alt_ct + 1)) { |
| 2667 |
cur_varid_templatep = varid_multi_nonsnp_templatep; |
| 2668 |
} |
| 2669 |
} |
| 2670 |
} |
| 2671 |
variant_id = variant_id_buf; |
| 2672 |
char* variant_id_end = VaridTemplateWrite(cur_varid_templatep, token_ptrs[2], alt_start, cur_bp, ref_slen, extra_alt_ct, alt_slen, &max_allele_overflow_slen, variant_id); |
| 2673 |
// error message fix (11 Oct 2024) |
| 2674 |
if (max_allele_overflow_slen && (!(misc_flags & (kfMiscNewVarIdOverflowMissing | kfMiscNewVarIdOverflowTruncate)))) { |
| 2675 |
ctx.multiallelics_already_joined = 1; |
| 2676 |
} |
| 2677 |
id_slen = variant_id_end - variant_id; |
| 2678 |
// bugfix (11 Oct 2024): need to update line_blen value used in |
| 2679 |
// cur_single_pos_blen accounting. |
| 2680 |
line_blen += id_slen - token_slens[1]; |
| 2681 |
} |
| 2682 |
if (unlikely(id_slen > kMaxIdSlen)) { |
| 2683 |
logerrputs("Error: Variant IDs are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 2684 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT; |
| 2685 |
} |
| 2686 |
if (cur_bp <= prev_bp) { |
| 2687 |
if (cur_bp < 0) { |
| 2688 |
++nonwrite_variant_ct; |
| 2689 |
continue; |
| 2690 |
} |
| 2691 |
if (unlikely(cur_bp < prev_bp)) { |
| 2692 |
snprintf(g_logbuf, kLogbufSize, "Error: %s is not position-sorted. Retry --pmerge[-list] after using --make-pgen/--make-bed + --sort-vars to sort your data.\n", cur_fname); |
| 2693 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT_WW; |
| 2694 |
} |
| 2695 |
// same position as previous included variant |
| 2696 |
++cur_single_pos_ct; |
| 2697 |
cur_single_pos_blen += line_blen; |
| 2698 |
} else { |
| 2699 |
if (max_single_pos_ct < cur_single_pos_ct) { |
| 2700 |
max_single_pos_ct = cur_single_pos_ct; |
| 2701 |
} |
| 2702 |
if (max_single_pos_blen < cur_single_pos_blen) { |
| 2703 |
max_single_pos_blen = cur_single_pos_blen; |
| 2704 |
} |
| 2705 |
reterr = RescanOnePos(arena_top, cur_single_pos_ct, prev_chr_code, prev_bp, arena_bottom, &ctx, &nonwrite_variant_ct); |
| 2706 |
if (unlikely(reterr)) { |
| 2707 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2708 |
} |
| 2709 |
arena_bottom = arena_bottom_mark; |
| 2710 |
cur_single_pos_ct = 1; |
| 2711 |
cur_single_pos_blen = line_blen; |
| 2712 |
prev_bp = cur_bp; |
| 2713 |
} |
| 2714 |
variant_id[id_slen] = '\0'; |
| 2715 |
const uint32_t id_blen = id_slen + 1; |
| 2716 |
const uint32_t rec_blen = sizeof(int32_t) + sizeof(AlleleCode) + id_blen + ref_slen + alt_slen + 2; |
| 2717 |
if (S_CAST(uintptr_t, arena_top - arena_bottom) < rec_blen) { |
| 2718 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2719 |
} |
| 2720 |
RescanOnePosRecord* cur_record = R_CAST(RescanOnePosRecord*, arena_bottom); |
| 2721 |
arena_bottom = &(arena_bottom[rec_blen]); |
| 2722 |
cur_record->rec_blen = rec_blen; |
| 2723 |
const uint32_t cur_allele_ct = extra_alt_ct + 2; |
| 2724 |
cur_record->allele_ct = cur_allele_ct; |
| 2725 |
if (read_max_allele_ct < cur_allele_ct) { |
| 2726 |
read_max_allele_ct = cur_allele_ct; |
| 2727 |
} |
| 2728 |
char* write_iter = memcpya(cur_record->variant_id, variant_id, id_blen); |
| 2729 |
write_iter = memcpyax(write_iter, token_ptrs[2], ref_slen, '\0'); |
| 2730 |
memcpyx(write_iter, alt_start, alt_slen, '\0'); |
| 2731 |
|
| 2732 |
if (check_qual) { |
| 2733 |
const char* qual_token = token_ptrs[4]; |
| 2734 |
if ((qual_token[0] != '.') || (qual_token[1] > ' ')) { |
| 2735 |
cur_fileset->nm_qual_exists = 1; |
| 2736 |
// possible todo: update col_types and col_skips to remove this |
| 2737 |
// column. |
| 2738 |
check_qual = 0; |
| 2739 |
} |
| 2740 |
} |
| 2741 |
if (check_filter) { |
| 2742 |
const char* filter_token = token_ptrs[5]; |
| 2743 |
const uint32_t filter_slen = token_slens[5]; |
| 2744 |
if ((filter_slen > 1) || (filter_token[0] != '.')) { |
| 2745 |
cur_fileset->nm_filter_exists = 1; |
| 2746 |
if (filter_count_needed) { |
| 2747 |
if (!strequal_k(filter_token, "PASS", filter_slen)) { |
| 2748 |
const uint32_t cur_filter_ct_m1 = CountByte(filter_token, ';', filter_slen); |
| 2749 |
if (cur_filter_ct_m1 >= read_max_nonpass_filter_ct) { |
| 2750 |
read_max_nonpass_filter_ct = cur_filter_ct_m1 + 1; |
| 2751 |
} |
| 2752 |
} |
| 2753 |
} else { |
| 2754 |
check_filter = 0; |
| 2755 |
} |
| 2756 |
} |
| 2757 |
} |
| 2758 |
if (check_info) { |
| 2759 |
const char* info_token = token_ptrs[6]; |
| 2760 |
const uint32_t info_slen = token_slens[6]; |
| 2761 |
if ((info_slen > 1) || (info_token[0] != '.')) { |
| 2762 |
cur_fileset->nm_info_exists = 1; |
| 2763 |
at_least_one_info_exists = 1; |
| 2764 |
check_info = 0; |
| 2765 |
} |
| 2766 |
} |
| 2767 |
if (check_cm) { |
| 2768 |
const char* cm_token = token_ptrs[7]; |
| 2769 |
if ((cm_token[0] != '0') || (cm_token[1] > ' ')) { |
| 2770 |
double cur_cm; |
| 2771 |
if (unlikely(!ScantokDouble(cm_token, &cur_cm))) { |
| 2772 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid centimorgan position on line %" PRIuPTR " of %s.\n", line_idx, cur_fname); |
| 2773 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2774 |
} |
| 2775 |
if (cur_cm != 0.0) { |
| 2776 |
cur_fileset->nz_cm_present = 1; |
| 2777 |
check_cm = 0; |
| 2778 |
} |
| 2779 |
} |
| 2780 |
} |
| 2781 |
} |
| 2782 |
if (unlikely(CleanupTextStream2(cur_fname, &txs, &reterr))) { |
| 2783 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2784 |
} |
| 2785 |
const uintptr_t read_variant_ct = line_idx - line_idx_body_start; |
| 2786 |
if (unlikely(read_variant_ct > kPglMaxVariantCt)) { |
| 2787 |
logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 3 variants. We recommend using\nother software for very deep studies of small numbers of genomes.\n"); |
| 2788 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT; |
| 2789 |
} |
| 2790 |
if (cur_single_pos_ct || (read_variant_ct != nonwrite_variant_ct)) { |
| 2791 |
cur_fileset->read_variant_ct = read_variant_ct; |
| 2792 |
cur_fileset->max_pvar_line_blen = max_line_blen; |
| 2793 |
if (max_single_pos_ct < cur_single_pos_ct) { |
| 2794 |
max_single_pos_ct = cur_single_pos_ct; |
| 2795 |
} |
| 2796 |
cur_fileset->max_single_pos_ct = max_single_pos_ct; |
| 2797 |
if (cur_single_pos_ct) { |
| 2798 |
ctx.sort_vars_ascii = (sort_vars_mode == kSortAscii); |
| 2799 |
reterr = RescanOnePos(arena_top, cur_single_pos_ct, prev_chr_code, prev_bp, arena_bottom, &ctx, &nonwrite_variant_ct); |
| 2800 |
if (unlikely(reterr)) { |
| 2801 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2802 |
} |
| 2803 |
if (unlikely(ScrapeLastVarid(&ctx, arena_bottom, cur_single_pos_ct, &cur_fileset->last_varid))) { |
| 2804 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2805 |
} |
| 2806 |
cur_fileset->last_chr_idx = prev_chr_code; |
| 2807 |
cur_fileset->last_pos = prev_bp; |
| 2808 |
} |
| 2809 |
cur_fileset->first_chr_idx = ctx.first_chr_idx; |
| 2810 |
cur_fileset->first_pos = ctx.first_bp; |
| 2811 |
if (max_single_pos_blen < cur_single_pos_blen) { |
| 2812 |
max_single_pos_blen = cur_single_pos_blen; |
| 2813 |
} |
| 2814 |
cur_fileset->max_single_pos_blen = max_single_pos_blen; |
| 2815 |
const uint32_t write_variant_ct = read_variant_ct - nonwrite_variant_ct; |
| 2816 |
cur_fileset->write_variant_ct = write_variant_ct; |
| 2817 |
cur_fileset->write_nondoomed_variant_ct = write_variant_ct - ctx.write_doomed_variant_ct; |
| 2818 |
if (unlikely(no_multiallelic_allowed && (read_max_allele_ct > 2))) { |
| 2819 |
snprintf(g_logbuf, kLogbufSize, "Error: %s contains multiallelic variant(s), despite having no #CHROM header line. Add that header line to make it obvious that this isn't a valid .bim.\n", cur_fname); |
| 2820 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW; |
| 2821 |
} |
| 2822 |
cur_fileset->read_max_allele_ct = read_max_allele_ct; |
| 2823 |
cur_fileset->write_nondoomed_max_allele_ct = ctx.write_nondoomed_max_allele_ct; |
| 2824 |
cur_fileset->read_max_nonpass_filter_ct = read_max_nonpass_filter_ct; |
| 2825 |
arena_bottom = arena_bottom_mark; |
| 2826 |
filesets_iterp = &((*filesets_iterp)->next); |
| 2827 |
} else { |
| 2828 |
PmergeInputFilesetLl** next_filesets_iterp = &((*filesets_iterp)->next); |
| 2829 |
*filesets_iterp = cur_fileset->next; |
| 2830 |
filesets_iterp = next_filesets_iterp; |
| 2831 |
++null_fileset_ct; |
| 2832 |
} |
| 2833 |
} |
| 2834 |
if (unlikely(null_fileset_ct && ((null_fileset_ct == fileset_ct) || (pmip->flags & kfPmergeVariantInnerJoin)))) { |
| 2835 |
logerrputs("Error: No variants remaining.\n"); |
| 2836 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT; |
| 2837 |
} |
| 2838 |
cip->chrset_source = orig_chrset_source; |
| 2839 |
|
| 2840 |
BigstackEndSet(arena_top); |
| 2841 |
if (unlikely(BigstackBaseSetChecked(arena_bottom))) { |
| 2842 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2843 |
} |
| 2844 |
// defensive |
| 2845 |
arena_bottom = nullptr; |
| 2846 |
arena_top = nullptr; |
| 2847 |
|
| 2848 |
if (xheader_entries && (!info_pr_exists)) { |
| 2849 |
// If INFO/PR is not present in any input .pvar/.bim, but nonref_flags |
| 2850 |
// is stored in at least one input .pgen, and we're already writing the |
| 2851 |
// INFO column for other reasons, we *do* want to write INFO/PR. |
| 2852 |
PmergeInputFilesetLl* filesets_iter = *filesets_ptr; |
| 2853 |
do { |
| 2854 |
if (filesets_iter->nonref_flags_storage == 3) { |
| 2855 |
if (unlikely(info_pr_nonflag_exists)) { |
| 2856 |
logerrputs("Error: Conflicting INFO/PR definitions. Either fix all REF alleles so that the\n\"provisional reference\" flag is no longer needed, or remove/rename the other\nuse of the INFO/PR key.\n"); |
| 2857 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT; |
| 2858 |
} |
| 2859 |
info_pr_exists = 1; |
| 2860 |
break; |
| 2861 |
} |
| 2862 |
filesets_iter = filesets_iter->next; |
| 2863 |
} while (filesets_iter != nullptr); |
| 2864 |
} |
| 2865 |
// Note that, under "--merge-info-mode erase", we may need to scrape |
| 2866 |
// INFO/PR from .pvar files to be saved later to the .pgen. |
| 2867 |
const uint32_t write_info_pr_to_pvar = info_pr_exists && (pmip->merge_info_mode != kMergeInfoCmModeErase); |
| 2868 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar"); |
| 2869 |
// kfImportKeepAutoconvVzs cannot be set here. |
| 2870 |
const uint32_t output_zst = (pmip->flags / kfPmergeOutputVzs) & 1; |
| 2871 |
if (output_zst) { |
| 2872 |
snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst"); |
| 2873 |
} |
| 2874 |
if (xheader_entry_ct || write_info_pr_to_pvar) { |
| 2875 |
const uintptr_t overflow_buf_size = max_xheader_line_blen + kCompressStreamBlock; |
| 2876 |
unsigned char* compress_wkspace = nullptr; |
| 2877 |
uint32_t compress_thread_ct = 1; |
| 2878 |
if (output_zst) { |
| 2879 |
const uintptr_t compress_wkspace_req = CstreamWkspaceReq(overflow_buf_size); |
| 2880 |
if (overflow_buf_size + compress_wkspace_req <= linebuf_capacity) { |
| 2881 |
compress_wkspace = R_CAST(unsigned char*, &(linebuf[overflow_buf_size])); |
| 2882 |
} else { |
| 2883 |
if (unlikely(bigstack_alloc_uc(compress_wkspace_req, &compress_wkspace))) { |
| 2884 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2885 |
} |
| 2886 |
} |
| 2887 |
compress_thread_ct = decompress_thread_ct; |
| 2888 |
} |
| 2889 |
reterr = InitCstream(outname, 0, output_zst, compress_thread_ct, overflow_buf_size, linebuf, compress_wkspace, &css); |
| 2890 |
if (unlikely(reterr)) { |
| 2891 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2892 |
} |
| 2893 |
cswritep = linebuf; |
| 2894 |
uint32_t info_key_ct = 0; |
| 2895 |
for (uint32_t xheader_entry_idx = 0; xheader_entry_idx != xheader_entry_ct; ++xheader_entry_idx) { |
| 2896 |
const char* key = xheader_entries[xheader_entry_idx]; |
| 2897 |
const uint32_t key_slen = strlen(key); |
| 2898 |
const char* value = &(key[key_slen + 1]); |
| 2899 |
if (value[0] == 1) { |
| 2900 |
// conflict that we're skipping |
| 2901 |
continue; |
| 2902 |
} |
| 2903 |
if (at_least_one_info_exists) { |
| 2904 |
if (StrStartsWithUnsafe(key, "#INFO=<")) { |
| 2905 |
++info_key_ct; |
| 2906 |
} |
| 2907 |
} |
| 2908 |
*cswritep++ = '#'; |
| 2909 |
cswritep = memcpya(cswritep, key, key_slen); |
| 2910 |
cswritep = strcpya(cswritep, value); |
| 2911 |
AppendBinaryEoln(&cswritep); |
| 2912 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 2913 |
goto ScanPvarsAndMergeHeader_ret_WRITE_FAIL; |
| 2914 |
} |
| 2915 |
} |
| 2916 |
if (write_info_pr_to_pvar) { |
| 2917 |
cswritep = strcpya_k(cswritep, "##INFO=<ID=PR,Number=0,Type=Flag,Description=\"Provisional reference allele, may not be based on real reference genome\">" EOLN_STR); |
| 2918 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 2919 |
goto ScanPvarsAndMergeHeader_ret_WRITE_FAIL; |
| 2920 |
} |
| 2921 |
} |
| 2922 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 2923 |
goto ScanPvarsAndMergeHeader_ret_WRITE_FAIL; |
| 2924 |
} |
| 2925 |
|
| 2926 |
BigstackReset(bigstack_mark); |
| 2927 |
if (at_least_one_info_exists) { |
| 2928 |
// Export INFO key hash table for future use, positioning it at the |
| 2929 |
// bottom of bigstack. |
| 2930 |
// Similar to ParseInfoHeader() in plink2_data.cc. |
| 2931 |
char** xheader_entries_next = S_CAST(char**, bigstack_end_alloc_raw_rd(xheader_entry_ct * sizeof(intptr_t))); |
| 2932 |
memmove(xheader_entries_next, xheader_entries, xheader_entry_ct * sizeof(intptr_t)); |
| 2933 |
xheader_entries = xheader_entries_next; |
| 2934 |
const char** info_keys; |
| 2935 |
if (unlikely(bigstack_alloc_kcp(info_key_ct + write_info_pr_to_pvar, &info_keys))) { |
| 2936 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2937 |
} |
| 2938 |
arena_bottom = g_bigstack_base; |
| 2939 |
arena_top = BigstackEndRoundedDown(); |
| 2940 |
|
| 2941 |
uint32_t xheader_entry_idx = 0; |
| 2942 |
for (uint32_t info_key_idx = 0; info_key_idx != info_key_ct; ++info_key_idx) { |
| 2943 |
const char* key; |
| 2944 |
const char* value; |
| 2945 |
uint32_t key_slen; |
| 2946 |
do { |
| 2947 |
key = xheader_entries[xheader_entry_idx++]; |
| 2948 |
key_slen = strlen(key); |
| 2949 |
value = &(key[key_slen + 1]); |
| 2950 |
} while ((value[0] == 1) || (!StrStartsWithUnsafe(key, "#INFO=<"))); |
| 2951 |
const char* info_key = &(key[strlen("#INFO=<ID=")]); |
| 2952 |
const uint32_t info_key_slen = key_slen - strlen("#INFO=<ID="); |
| 2953 |
if (info_key_slen > kMaxInfoKeySlen) { |
| 2954 |
logerrputs("Error: " PROG_NAME_STR " does not support INFO keys longer than " MAX_INFO_KEY_SLEN_STR " characters.\n"); |
| 2955 |
reterr = kPglRetNotYetSupported; |
| 2956 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 2957 |
} |
| 2958 |
if (unlikely(value[0] != ',')) { |
| 2959 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INFO_HEADER_LINE; |
| 2960 |
} |
| 2961 |
const uintptr_t entry_byte_ct = RoundUpPow2(offsetof(InfoVtype, key) + 1 + info_key_slen, sizeof(intptr_t)); |
| 2962 |
if (unlikely(S_CAST(uintptr_t, arena_top - arena_bottom) < entry_byte_ct)) { |
| 2963 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2964 |
} |
| 2965 |
InfoVtype* new_entry = R_CAST(InfoVtype*, arena_bottom); |
| 2966 |
arena_bottom = &(arena_bottom[entry_byte_ct]); |
| 2967 |
memcpy(new_entry->key, info_key, info_key_slen + 1); |
| 2968 |
info_keys[info_key_idx] = new_entry->key; |
| 2969 |
char* numstr; |
| 2970 |
uint32_t num_slen; |
| 2971 |
if (unlikely(HkvlineFind(&(value[1]), "Number", &numstr, &num_slen) || |
| 2972 |
FillInfoVtypeNum(numstr, num_slen, info_has_g_keyp, &(new_entry->num)))) { |
| 2973 |
goto ScanPvarsAndMergeHeader_ret_MALFORMED_INFO_HEADER_LINE; |
| 2974 |
} |
| 2975 |
} |
| 2976 |
if (write_info_pr_to_pvar) { |
| 2977 |
const uintptr_t entry_byte_ct = RoundUpPow2(offsetof(InfoVtype, key) + 1 + strlen("PR"), sizeof(intptr_t)); |
| 2978 |
if (unlikely(S_CAST(uintptr_t, arena_top - arena_bottom) < entry_byte_ct)) { |
| 2979 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 2980 |
} |
| 2981 |
InfoVtype* new_entry = R_CAST(InfoVtype*, arena_bottom); |
| 2982 |
arena_bottom = &(arena_bottom[entry_byte_ct]); |
| 2983 |
strcpy_k(new_entry->key, "PR"); |
| 2984 |
info_keys[info_key_ct] = new_entry->key; |
| 2985 |
new_entry->num = 0; |
| 2986 |
++info_key_ct; |
| 2987 |
} |
| 2988 |
BigstackBaseSet(arena_bottom); |
| 2989 |
arena_bottom = nullptr; |
| 2990 |
arena_top = nullptr; |
| 2991 |
if (pmip->merge_info_sort == kSortAscii) { |
| 2992 |
StrptrArrSortOverread(info_key_ct, info_keys); |
| 2993 |
} else if (pmip->merge_info_sort == kSortNatural) { |
| 2994 |
StrptrArrNsort(info_key_ct, info_keys); |
| 2995 |
} |
| 2996 |
|
| 2997 |
const uint32_t info_key_ctl = BitCtToWordCt(info_key_ct); |
| 2998 |
uintptr_t* dummy_include; |
| 2999 |
if (unlikely(bigstack_end_alloc_w(info_key_ctl, &dummy_include))) { |
| 3000 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 3001 |
} |
| 3002 |
SetAllBits(info_key_ct, dummy_include); |
| 3003 |
const uintptr_t bytes_left = bigstack_left(); |
| 3004 |
reterr = AllocAndPopulateIdHtableMt(dummy_include, info_keys, info_key_ct, bytes_left - (bytes_left / 64), 1, info_keys_htablep, nullptr, info_keys_htable_sizep, nullptr); |
| 3005 |
if (unlikely(reterr)) { |
| 3006 |
goto ScanPvarsAndMergeHeader_ret_1; |
| 3007 |
} |
| 3008 |
*info_keys_ptr = info_keys; |
| 3009 |
*info_key_ctp = info_key_ct; |
| 3010 |
|
| 3011 |
bigstack_mark = g_bigstack_base; |
| 3012 |
} |
| 3013 |
} else { |
| 3014 |
// bugfix (2 Mar 2021): if there's an existing file with the |
| 3015 |
// eventual-output-.pvar name, truncate it down to zero, since we append |
| 3016 |
// later. |
| 3017 |
FILE* pvar_stub_file = fopen(outname, FOPEN_WB); |
| 3018 |
if (unlikely(!pvar_stub_file)) { |
| 3019 |
goto ScanPvarsAndMergeHeader_ret_OPEN_FAIL; |
| 3020 |
} |
| 3021 |
if (unlikely(fclose(pvar_stub_file))) { |
| 3022 |
goto ScanPvarsAndMergeHeader_ret_WRITE_FAIL; |
| 3023 |
} |
| 3024 |
} |
| 3025 |
const uint32_t name_ct = cip->name_ct; |
| 3026 |
const uint32_t autosome_code_end = cip->autosome_ct + 1; |
| 3027 |
const uint32_t name_code_start = autosome_code_end + kChrOffsetCt; |
| 3028 |
// When there are multiple chromosomes with no remaining in-edges, we |
| 3029 |
// prioritize as follows: |
| 3030 |
// 1. Smallest autosomal chromosome index. |
| 3031 |
// 2. PAR1 < chrX < PAR2 < chrY < XY < chrM |
| 3032 |
// 3. Contig names in natural-sort or ASCII-sort increasing order, |
| 3033 |
// depending on --sort-vars setting. |
| 3034 |
// See also SortChr() in plink2_data.cc. This is a bit simpler since we |
| 3035 |
// don't need the sort_idxs to be dense. |
| 3036 |
const uint32_t max_code_p1 = cip->max_code + 1; |
| 3037 |
const uint32_t chr_code_end = max_code_p1 + name_ct; |
| 3038 |
uint32_t* chr_idx_to_sort_idx; |
| 3039 |
if (unlikely(bigstack_end_alloc_u32(chr_code_end, &chr_idx_to_sort_idx))) { |
| 3040 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 3041 |
} |
| 3042 |
for (uint32_t chr_code = 0; chr_code != autosome_code_end; ++chr_code) { |
| 3043 |
chr_idx_to_sort_idx[chr_code] = chr_code; |
| 3044 |
} |
| 3045 |
const uint32_t xymt_ct = cip->max_code - autosome_code_end; |
| 3046 |
const uint32_t xymt_idx_to_chr_sort_offset[kChrOffsetCt] = {1, 3, 4, 5, 0, 2}; |
| 3047 |
for (uint32_t xymt_idx = 0; xymt_idx != xymt_ct; ++xymt_idx) { |
| 3048 |
chr_idx_to_sort_idx[autosome_code_end + xymt_idx] = autosome_code_end + xymt_idx_to_chr_sort_offset[xymt_idx]; |
| 3049 |
} |
| 3050 |
if (name_ct) { |
| 3051 |
unsigned char* bigstack_end_mark2 = g_bigstack_end; |
| 3052 |
StrSortIndexedDeref* nonstd_sort_buf = S_CAST(StrSortIndexedDeref*, bigstack_end_alloc(name_ct * sizeof(StrSortIndexedDeref))); |
| 3053 |
if (unlikely(!nonstd_sort_buf)) { |
| 3054 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 3055 |
} |
| 3056 |
const char** nonstd_names = cip->nonstd_names; |
| 3057 |
for (uint32_t name_idx = 0; name_idx != name_ct; ++name_idx) { |
| 3058 |
// bugfix (17 Feb 2022): first non-null nonstd_names[] entry is at |
| 3059 |
// [max_code_p1], not [0] |
| 3060 |
nonstd_sort_buf[name_idx].strptr = nonstd_names[name_idx + max_code_p1]; |
| 3061 |
nonstd_sort_buf[name_idx].orig_idx = name_idx; |
| 3062 |
} |
| 3063 |
// nonstd_names are not allocated in main workspace, so can't overread. |
| 3064 |
StrptrArrSortMain(name_ct, 0, (sort_vars_mode != kSortAscii), nonstd_sort_buf); |
| 3065 |
for (uint32_t name_idx = 0; name_idx != name_ct; ++name_idx) { |
| 3066 |
chr_idx_to_sort_idx[max_code_p1 + nonstd_sort_buf[name_idx].orig_idx] = name_code_start + name_idx; |
| 3067 |
} |
| 3068 |
BigstackEndReset(bigstack_end_mark2); |
| 3069 |
} |
| 3070 |
const uint32_t sort_code_end = name_code_start + name_ct; |
| 3071 |
const uint32_t sort_code_endl = BitCtToWordCt(sort_code_end); |
| 3072 |
uint32_t* chr_sort_idx_to_idx; |
| 3073 |
uintptr_t* no_incoming_set; |
| 3074 |
if (unlikely(bigstack_end_alloc_u32(sort_code_end, &chr_sort_idx_to_idx) || |
| 3075 |
bigstack_end_calloc_w(sort_code_endl, &no_incoming_set))) { |
| 3076 |
goto ScanPvarsAndMergeHeader_ret_NOMEM; |
| 3077 |
} |
| 3078 |
const uint32_t chr_code_endl = BitCtToWordCt(chr_code_end); |
| 3079 |
const uint32_t chr_ct = PopcountWords(chr_present, chr_code_endl); |
| 3080 |
{ |
| 3081 |
uintptr_t chr_code_base = 0; |
| 3082 |
uintptr_t cur_bits = chr_present[0]; |
| 3083 |
for (uint32_t uii = 0; uii != chr_ct; ++uii) { |
| 3084 |
uint32_t chr_code = BitIter1(chr_present, &chr_code_base, &cur_bits); |
| 3085 |
const uint32_t chr_sort_idx = chr_idx_to_sort_idx[chr_code]; |
| 3086 |
chr_sort_idx_to_idx[chr_sort_idx] = chr_code; |
| 3087 |
if (!chr_inedge_cts[chr_code]) { |
| 3088 |
SetBit(chr_sort_idx, no_incoming_set); |
| 3089 |
} |
| 3090 |
} |
| 3091 |
} |
| 3092 |
uint32_t chr_fo_idx = 0; |
| 3093 |
while (1) { |
| 3094 |
uint32_t chr_sort_idx; |
| 3095 |
{ |
| 3096 |
uint32_t widx = 0; |
| 3097 |
for (; widx != sort_code_endl; ++widx) { |
| 3098 |
const uintptr_t cur_bits = no_incoming_set[widx]; |
| 3099 |
if (cur_bits) { |
| 3100 |
chr_sort_idx = widx * kBitsPerWord + ctzw(cur_bits); |
| 3101 |
// clear this bit |
| 3102 |
no_incoming_set[widx] = cur_bits & (cur_bits - 1); |
| 3103 |
break; |
| 3104 |
} |
| 3105 |
} |
| 3106 |
if (widx == sort_code_endl) { |
| 3107 |
break; |
| 3108 |
} |
| 3109 |
} |
| 3110 |
const uint32_t chr_idx = chr_sort_idx_to_idx[chr_sort_idx]; |
| 3111 |
cip->chr_file_order[chr_fo_idx] = chr_idx; |
| 3112 |
cip->chr_idx_to_foidx[chr_idx] = chr_fo_idx; |
| 3113 |
++chr_fo_idx; |
| 3114 |
const uintptr_t* outedges = chr_outedges[chr_idx]; |
| 3115 |
if (outedges) { |
| 3116 |
for (uint32_t widx = 0; widx != chr_code_endl; ++widx) { |
| 3117 |
uintptr_t cur_bits = outedges[widx]; |
| 3118 |
if (cur_bits) { |
| 3119 |
const uint32_t other_chr_idx_base = widx * kBitsPerWord; |
| 3120 |
do { |
| 3121 |
const uint32_t other_chr_idx = other_chr_idx_base + ctzw(cur_bits); |
| 3122 |
chr_inedge_cts[other_chr_idx] -= 1; |
| 3123 |
if (!chr_inedge_cts[other_chr_idx]) { |
| 3124 |
const uint32_t other_chr_sort_idx = chr_idx_to_sort_idx[other_chr_idx]; |
| 3125 |
SetBit(other_chr_sort_idx, no_incoming_set); |
| 3126 |
} |
| 3127 |
cur_bits &= cur_bits - 1; |
| 3128 |
} while (cur_bits); |
| 3129 |
} |
| 3130 |
} |
| 3131 |
} |
| 3132 |
} |
| 3133 |
if (unlikely(chr_fo_idx != chr_ct)) { |
| 3134 |
logerrputs("Error: Chromosomes are not in a consistent order. Retry --pmerge[-list] after\nusing --make-pgen/--make-bed + --sort-vars to sort your variants in a\nconsistent manner.\n"); |
| 3135 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT; |
| 3136 |
} |
| 3137 |
if (unlikely(max_allele_overflow_slen && (!(misc_flags & (kfMiscNewVarIdOverflowMissing | kfMiscNewVarIdOverflowTruncate))))) { |
| 3138 |
logputs("\n"); |
| 3139 |
logerrprintf("Error: Allele code(s) too long for --set-%s-var-ids.\n", (misc_flags & kfMiscSetMissingVarIds)? "missing" : "all"); |
| 3140 |
// Not a precise bound, but in practice this should print the more useful |
| 3141 |
// message >99% of the time. |
| 3142 |
if (max_allele_overflow_slen < kMaxIdSlen / 2) { |
| 3143 |
logerrprintfww("The longest observed allele code across these datasets has length %u. If you're fine with the corresponding ID length, rerun with \"--new-id-max-allele-len %u\" added to your command line.\n", max_allele_overflow_slen, max_allele_overflow_slen); |
| 3144 |
} else { |
| 3145 |
logerrprintfww("The longest observed allele code across these datasets has length %u. We recommend deciding on a length-limit, and then adding \"--new-id-max-allele-len <limit> missing\" to your command line to cause variants with longer allele codes to be assigned '.' IDs. (You can then process just those variants with another script, if necessary.)\n", max_allele_overflow_slen); |
| 3146 |
} |
| 3147 |
goto ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT; |
| 3148 |
} |
| 3149 |
cip->chr_ct = chr_ct; |
| 3150 |
// edge case: if no header meta lines, but we're writing INFO/PR, no need |
| 3151 |
// to log "headers merged" |
| 3152 |
logprintf("--pmerge%s: %" PRIuPTR " .pvar files scanned%s.\n", pmip->list_fname? "-list" : "", fileset_ct, (xheader_entry_ct || (info_pr_exists && xheader_entries))? ", headers merged" : ""); |
| 3153 |
if (null_fileset_ct) { |
| 3154 |
logprintfww("Note: Ignoring %" PRIuPTR " .pgen file%s since it doesn't intersect the chromosome filter.\n", null_fileset_ct, (null_fileset_ct == 1)? "" : "s"); |
| 3155 |
*fileset_ctp -= null_fileset_ct; |
| 3156 |
} |
| 3157 |
if (info_conflict_ct) { |
| 3158 |
logprintfww("Note: Skipping %" PRIuPTR " INFO key%s with mismatching header lines.\n", info_conflict_ct, (info_conflict_ct == 1)? "" : "s"); |
| 3159 |
} |
| 3160 |
*info_conflict_presentp = !!info_conflict_ct; |
| 3161 |
} |
| 3162 |
while (0) { |
| 3163 |
ScanPvarsAndMergeHeader_ret_NOMEM: |
| 3164 |
reterr = kPglRetNomem; |
| 3165 |
break; |
| 3166 |
ScanPvarsAndMergeHeader_ret_OPEN_FAIL: |
| 3167 |
reterr = kPglRetOpenFail; |
| 3168 |
break; |
| 3169 |
ScanPvarsAndMergeHeader_ret_TSTREAM_FAIL: |
| 3170 |
TextStreamErrPrint(cur_fname, &txs); |
| 3171 |
break; |
| 3172 |
ScanPvarsAndMergeHeader_ret_MISSING_TOKENS: |
| 3173 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, cur_fname); |
| 3174 |
ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT_WW: |
| 3175 |
WordWrapB(0); |
| 3176 |
logerrputsb(); |
| 3177 |
ScanPvarsAndMergeHeader_ret_MALFORMED_INPUT: |
| 3178 |
reterr = kPglRetMalformedInput; |
| 3179 |
break; |
| 3180 |
ScanPvarsAndMergeHeader_ret_INCONSISTENTLY_PRESENT_CHRSET: |
| 3181 |
logerrputs("Error: ##chrSet header line present in some, but not all, --pmerge[-list] input\nfiles. This is only permitted when the chromosome set is also defined on the\ncommand line.\n"); |
| 3182 |
reterr = kPglRetInconsistentInput; |
| 3183 |
break; |
| 3184 |
ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT_WW: |
| 3185 |
WordWrapB(0); |
| 3186 |
logerrputsb(); |
| 3187 |
ScanPvarsAndMergeHeader_ret_INCONSISTENT_INPUT: |
| 3188 |
reterr = kPglRetInconsistentInput; |
| 3189 |
break; |
| 3190 |
ScanPvarsAndMergeHeader_ret_MALFORMED_INFO_HEADER_LINE: |
| 3191 |
logerrputs("Error: Malformed or unrecognized INFO header line.\n"); |
| 3192 |
reterr = kPglRetMalformedInput; |
| 3193 |
break; |
| 3194 |
ScanPvarsAndMergeHeader_ret_WRITE_FAIL: |
| 3195 |
reterr = kPglRetWriteFail; |
| 3196 |
break; |
| 3197 |
} |
| 3198 |
ScanPvarsAndMergeHeader_ret_1: |
| 3199 |
CleanupTextStream2(cur_fname, &txs, &reterr); |
| 3200 |
CswriteCloseCond(&css, cswritep); |
| 3201 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 3202 |
return reterr; |
| 3203 |
} |
| 3204 |
|
| 3205 |
typedef struct PmergeFilesetSorterStruct { |
| 3206 |
PmergeInputFilesetLl* pp; |
| 3207 |
uint64_t first_coord; |
| 3208 |
uint64_t last_coord; |
| 3209 |
#ifdef __cplusplus |
| 3210 |
bool operator<(const struct PmergeFilesetSorterStruct& rhs) const { |
| 3211 |
if (first_coord != rhs.first_coord) { |
| 3212 |
return (first_coord < rhs.first_coord); |
| 3213 |
} |
| 3214 |
return (strcmp(pp->first_varid, rhs.pp->first_varid) < 0); |
| 3215 |
} |
| 3216 |
#endif |
| 3217 |
} PmergeFilesetSorter; |
| 3218 |
|
| 3219 |
typedef struct PmergeFilesetNsorterStruct { |
| 3220 |
PmergeInputFilesetLl* pp; |
| 3221 |
uint64_t first_coord; |
| 3222 |
uint64_t last_coord; |
| 3223 |
#ifdef __cplusplus |
| 3224 |
bool operator<(const struct PmergeFilesetNsorterStruct& rhs) const { |
| 3225 |
if (first_coord != rhs.first_coord) { |
| 3226 |
return (first_coord < rhs.first_coord); |
| 3227 |
} |
| 3228 |
return (strcmp_natural_uncasted(pp->first_varid, rhs.pp->first_varid) < 0); |
| 3229 |
} |
| 3230 |
#endif |
| 3231 |
} PmergeFilesetNsorter; |
| 3232 |
|
| 3233 |
#ifndef __cplusplus |
| 3234 |
int32_t FilesetAsciiCmp(const void* aa, const void* bb) { |
| 3235 |
const PmergeFilesetSorter* pfs1 = S_CAST(const PmergeFilesetSorter*, aa); |
| 3236 |
const PmergeFilesetSorter* pfs2 = S_CAST(const PmergeFilesetSorter*, bb); |
| 3237 |
const uint64_t first_coord1 = pfs1->first_coord; |
| 3238 |
const uint64_t first_coord2 = pfs2->first_coord; |
| 3239 |
if (first_coord1 != first_coord2) { |
| 3240 |
return (first_coord1 < first_coord2)? -1 : 1; |
| 3241 |
} |
| 3242 |
return strcmp(pfs1->pp->first_varid, pfs2->pp->first_varid); |
| 3243 |
} |
| 3244 |
|
| 3245 |
int32_t FilesetNaturalCmp(const void* aa, const void* bb) { |
| 3246 |
const PmergeFilesetNsorter* pfs1 = S_CAST(const PmergeFilesetNsorter*, aa); |
| 3247 |
const PmergeFilesetNsorter* pfs2 = S_CAST(const PmergeFilesetNsorter*, bb); |
| 3248 |
const uint64_t first_coord1 = pfs1->first_coord; |
| 3249 |
const uint64_t first_coord2 = pfs2->first_coord; |
| 3250 |
if (first_coord1 != first_coord2) { |
| 3251 |
return (first_coord1 < first_coord2)? -1 : 1; |
| 3252 |
} |
| 3253 |
return strcmp_natural_uncasted(pfs1->pp->first_varid, pfs2->pp->first_varid); |
| 3254 |
} |
| 3255 |
#endif |
| 3256 |
|
| 3257 |
// Determines whether there's no overlap between the positional ranges covered |
| 3258 |
// by the filesets. If so, the filesets linked list is sorted. |
| 3259 |
PglErr DetectConcatJob(const uint32_t* chr_idx_to_foidx, uintptr_t fileset_ct, SortMode sort_vars_mode, PmergeInputFilesetLl** filesets_ptr, uint32_t* is_concat_jobp) { |
| 3260 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3261 |
PglErr reterr = kPglRetSuccess; |
| 3262 |
{ |
| 3263 |
PmergeFilesetSorter* sorted_filesets; |
| 3264 |
if (unlikely(BIGSTACK_ALLOC_X(PmergeFilesetSorter, fileset_ct, &sorted_filesets))) { |
| 3265 |
goto DetectConcatJob_ret_NOMEM; |
| 3266 |
} |
| 3267 |
PmergeInputFilesetLl* filesets_iter = *filesets_ptr; |
| 3268 |
for (uintptr_t fileset_idx = 0; fileset_idx != fileset_ct; ++fileset_idx, filesets_iter = filesets_iter->next) { |
| 3269 |
sorted_filesets[fileset_idx].pp = filesets_iter; |
| 3270 |
sorted_filesets[fileset_idx].first_coord = (S_CAST(uint64_t, chr_idx_to_foidx[filesets_iter->first_chr_idx]) << 32) | filesets_iter->first_pos; |
| 3271 |
sorted_filesets[fileset_idx].last_coord = (S_CAST(uint64_t, chr_idx_to_foidx[filesets_iter->last_chr_idx]) << 32) | filesets_iter->last_pos; |
| 3272 |
} |
| 3273 |
const uint32_t sort_ascii = (sort_vars_mode == kSortAscii); |
| 3274 |
if (sort_ascii) { |
| 3275 |
STD_SORT(fileset_ct, FilesetAsciiCmp, sorted_filesets); |
| 3276 |
} else { |
| 3277 |
STD_SORT(fileset_ct, FilesetNaturalCmp, R_CAST(PmergeFilesetNsorter*, sorted_filesets)); |
| 3278 |
} |
| 3279 |
uintptr_t prev_last_coord = sorted_filesets[0].last_coord; |
| 3280 |
uintptr_t fileset_idx = 1; |
| 3281 |
for (; fileset_idx != fileset_ct; ++fileset_idx) { |
| 3282 |
const uintptr_t cur_first_coord = sorted_filesets[fileset_idx].first_coord; |
| 3283 |
if (cur_first_coord <= prev_last_coord) { |
| 3284 |
if (cur_first_coord < prev_last_coord) { |
| 3285 |
break; |
| 3286 |
} |
| 3287 |
if (sort_ascii) { |
| 3288 |
if (strcmp(sorted_filesets[fileset_idx - 1].pp->last_varid, sorted_filesets[fileset_idx].pp->first_varid) >= 0) { |
| 3289 |
break; |
| 3290 |
} |
| 3291 |
} else { |
| 3292 |
if (strcmp_natural(sorted_filesets[fileset_idx - 1].pp->last_varid, sorted_filesets[fileset_idx].pp->first_varid) >= 0) { |
| 3293 |
break; |
| 3294 |
} |
| 3295 |
} |
| 3296 |
continue; |
| 3297 |
} |
| 3298 |
prev_last_coord = sorted_filesets[fileset_idx].last_coord; |
| 3299 |
} |
| 3300 |
if (fileset_idx == fileset_ct) { |
| 3301 |
PmergeInputFilesetLl** filesets_iterp = filesets_ptr; |
| 3302 |
for (fileset_idx = 0; fileset_idx != fileset_ct; ++fileset_idx) { |
| 3303 |
*filesets_iterp = sorted_filesets[fileset_idx].pp; |
| 3304 |
filesets_iterp = &((*filesets_iterp)->next); |
| 3305 |
} |
| 3306 |
*filesets_iterp = nullptr; |
| 3307 |
logputs("Concatenation job detected.\n"); |
| 3308 |
*is_concat_jobp = 1; |
| 3309 |
} |
| 3310 |
} |
| 3311 |
while (0) { |
| 3312 |
DetectConcatJob_ret_NOMEM: |
| 3313 |
reterr = kPglRetNomem; |
| 3314 |
break; |
| 3315 |
} |
| 3316 |
BigstackReset(bigstack_mark); |
| 3317 |
return reterr; |
| 3318 |
} |
| 3319 |
|
| 3320 |
void CleanupFilesetLl(PmergeInputFilesetLl* filesets_iter, PglErr* reterrp) { |
| 3321 |
PglErr reterr = *reterrp; |
| 3322 |
while (filesets_iter != nullptr) { |
| 3323 |
free_cond(filesets_iter->first_varid); |
| 3324 |
free_cond(filesets_iter->last_varid); |
| 3325 |
const uint32_t is_temporary = filesets_iter->is_temporary; |
| 3326 |
if (is_temporary) { |
| 3327 |
if (filesets_iter->pgen_fname) { |
| 3328 |
if (reterr == kPglRetSuccess) { |
| 3329 |
if (unlikely(unlink(filesets_iter->pgen_fname))) { |
| 3330 |
reterr = kPglRetWriteFail; |
| 3331 |
} |
| 3332 |
} |
| 3333 |
free(filesets_iter->pgen_fname); |
| 3334 |
} |
| 3335 |
if (filesets_iter->pvar_fname) { |
| 3336 |
if (reterr == kPglRetSuccess) { |
| 3337 |
if (unlikely(unlink(filesets_iter->pvar_fname))) { |
| 3338 |
reterr = kPglRetWriteFail; |
| 3339 |
} |
| 3340 |
} |
| 3341 |
free(filesets_iter->pvar_fname); |
| 3342 |
} |
| 3343 |
if (filesets_iter->psam_fname) { |
| 3344 |
if (reterr == kPglRetSuccess) { |
| 3345 |
if (unlikely(unlink(filesets_iter->psam_fname))) { |
| 3346 |
reterr = kPglRetWriteFail; |
| 3347 |
} |
| 3348 |
} |
| 3349 |
free(filesets_iter->psam_fname); |
| 3350 |
} |
| 3351 |
if (filesets_iter->pgen_locked_fname) { |
| 3352 |
if (reterr == kPglRetSuccess) { |
| 3353 |
if (unlikely(unlink(filesets_iter->pgen_locked_fname))) { |
| 3354 |
reterr = kPglRetWriteFail; |
| 3355 |
} |
| 3356 |
} |
| 3357 |
free(filesets_iter->pgen_locked_fname); |
| 3358 |
} |
| 3359 |
} |
| 3360 |
PmergeInputFilesetLl* cur_node = filesets_iter; |
| 3361 |
filesets_iter = filesets_iter->next; |
| 3362 |
if (is_temporary) { |
| 3363 |
free(cur_node); |
| 3364 |
} |
| 3365 |
} |
| 3366 |
*reterrp = reterr; |
| 3367 |
} |
| 3368 |
|
| 3369 |
PglErr ScrapeSampleOrder(const char* psam_fname, const SampleIdInfo* siip, const uint32_t* xid_htable, uint32_t read_sample_ct, uint32_t xid_ct, uint32_t xid_htable_size, FamCol fam_cols, uint32_t psam_linebuf_capacity, uint32_t max_thread_ct, uint32_t* old_sample_idx_to_new, uint32_t* sample_idx_increasingp, uint32_t* cur_write_sample_ctp, uintptr_t* read_sample_include, uintptr_t* sample_span) { |
| 3370 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3371 |
PglErr reterr = kPglRetSuccess; |
| 3372 |
TextStream txs; |
| 3373 |
PreinitTextStream(&txs); |
| 3374 |
{ |
| 3375 |
const uint32_t decompress_thread_ct = MAXV(max_thread_ct - 1, 1); |
| 3376 |
char* linebuf; |
| 3377 |
if (unlikely(bigstack_alloc_c(psam_linebuf_capacity, &linebuf))) { |
| 3378 |
goto ScrapeSampleOrder_ret_NOMEM; |
| 3379 |
} |
| 3380 |
// Lots of overlap with second half of MergePsams(). |
| 3381 |
reterr = TextStreamOpenEx(psam_fname, kMaxLongLine, psam_linebuf_capacity, decompress_thread_ct, nullptr, linebuf, &txs); |
| 3382 |
if (unlikely(reterr)) { |
| 3383 |
goto ScrapeSampleOrder_ret_TSTREAM_REWIND_FAIL_N; |
| 3384 |
} |
| 3385 |
const char* line_start = TextLineEnd(&txs); |
| 3386 |
while (1) { |
| 3387 |
if (unlikely(!TextGetUnsafe2K(&txs, &line_start))) { |
| 3388 |
reterr = TextStreamRawErrcode(&txs); |
| 3389 |
goto ScrapeSampleOrder_ret_TSTREAM_REWIND_FAIL_N; |
| 3390 |
} |
| 3391 |
if ((line_start[0] != '#') || tokequal_k(&(line_start[1]), "FID") || tokequal_k(&(line_start[1]), "IID")) { |
| 3392 |
break; |
| 3393 |
} |
| 3394 |
line_start = AdvPastDelim(line_start, '\n'); |
| 3395 |
} |
| 3396 |
uint32_t sid_present = 0; |
| 3397 |
uint32_t fid_present; |
| 3398 |
if (line_start[0] == '#') { |
| 3399 |
fid_present = (line_start[1] == 'F'); |
| 3400 |
const char* postiid_token_start = FirstNonTspace(&(line_start[4])); |
| 3401 |
if (fid_present) { |
| 3402 |
postiid_token_start = FirstNonTspace(CurTokenEnd(postiid_token_start)); |
| 3403 |
} |
| 3404 |
sid_present = tokequal_k(postiid_token_start, "SID"); |
| 3405 |
line_start = AdvPastDelim(postiid_token_start, '\n'); |
| 3406 |
} else { |
| 3407 |
// .fam |
| 3408 |
fid_present = (fam_cols / kfFamCol1) & 1; |
| 3409 |
} |
| 3410 |
const uint32_t read_sample_ctl = BitCtToWordCt(read_sample_ct); |
| 3411 |
ZeroWArr(read_sample_ctl, read_sample_include); |
| 3412 |
const uint32_t xid_ctl = BitCtToWordCt(xid_ct); |
| 3413 |
ZeroWArr(xid_ctl, sample_span); |
| 3414 |
uint32_t* old_sample_idx_to_new_iter = old_sample_idx_to_new; |
| 3415 |
uint32_t prev_write_sample_idx = 0; |
| 3416 |
uint32_t sample_idx_increasing = 1; |
| 3417 |
for (uint32_t read_sample_idx = 0; read_sample_idx != read_sample_ct; ++read_sample_idx, line_start = AdvPastDelim(line_start, '\n')) { |
| 3418 |
if (unlikely(!TextGetUnsafe2K(&txs, &line_start))) { |
| 3419 |
reterr = TextStreamRawErrcode(&txs); |
| 3420 |
goto ScrapeSampleOrder_ret_TSTREAM_REWIND_FAIL_N; |
| 3421 |
} |
| 3422 |
uint32_t write_sample_idx; |
| 3423 |
if (unlikely(LookupXidHtable(line_start, siip, xid_htable, xid_htable_size, fid_present, sid_present, &write_sample_idx, g_textbuf))) { |
| 3424 |
goto ScrapeSampleOrder_ret_REWIND_FAIL_N; |
| 3425 |
} |
| 3426 |
if (write_sample_idx == UINT32_MAX) { |
| 3427 |
continue; |
| 3428 |
} |
| 3429 |
SetBit(read_sample_idx, read_sample_include); |
| 3430 |
SetBit(write_sample_idx, sample_span); |
| 3431 |
*old_sample_idx_to_new_iter++ = write_sample_idx; |
| 3432 |
if (write_sample_idx < prev_write_sample_idx) { |
| 3433 |
sample_idx_increasing = 0; |
| 3434 |
} |
| 3435 |
prev_write_sample_idx = write_sample_idx; |
| 3436 |
} |
| 3437 |
const uint32_t cur_write_sample_ct = PopcountWords(read_sample_include, read_sample_ctl); |
| 3438 |
*cur_write_sample_ctp = cur_write_sample_ct; |
| 3439 |
*sample_idx_increasingp = sample_idx_increasing; |
| 3440 |
} |
| 3441 |
while (0) { |
| 3442 |
ScrapeSampleOrder_ret_NOMEM: |
| 3443 |
reterr = kPglRetNomem; |
| 3444 |
break; |
| 3445 |
ScrapeSampleOrder_ret_TSTREAM_REWIND_FAIL_N: |
| 3446 |
logputs("\n"); |
| 3447 |
TextStreamErrPrintRewind(psam_fname, &txs, &reterr); |
| 3448 |
break; |
| 3449 |
ScrapeSampleOrder_ret_REWIND_FAIL_N: |
| 3450 |
logputs("\n"); |
| 3451 |
logerrprintfww(kErrprintfRewind, psam_fname); |
| 3452 |
reterr = kPglRetRewindFail; |
| 3453 |
break; |
| 3454 |
} |
| 3455 |
CleanupTextStream2(psam_fname, &txs, &reterr); |
| 3456 |
BigstackReset(bigstack_mark); |
| 3457 |
return reterr; |
| 3458 |
} |
| 3459 |
|
| 3460 |
typedef struct PvariantMergeContextStruct { |
| 3461 |
char* cswritep; |
| 3462 |
CompressStreamState css; |
| 3463 |
|
| 3464 |
unsigned char write_qual; |
| 3465 |
unsigned char write_filter; |
| 3466 |
unsigned char write_info; |
| 3467 |
unsigned char write_cm; |
| 3468 |
MergeQualMode merge_qual_mode; |
| 3469 |
MergeFilterMode merge_filter_mode; |
| 3470 |
MergeInfoCmMode merge_info_mode; |
| 3471 |
MergeInfoCmMode merge_cm_mode; |
| 3472 |
SortMode merge_info_sort; |
| 3473 |
uint32_t max_allele_ct; |
| 3474 |
|
| 3475 |
uintptr_t read_max_allele_ct; |
| 3476 |
char** cur_fields_buf; |
| 3477 |
uint32_t* cur_slens_buf; |
| 3478 |
AlleleCode* allele_cts_buf; |
| 3479 |
uintptr_t* is_pr_buf; |
| 3480 |
|
| 3481 |
// used for both alleles and FILTER |
| 3482 |
const char** tmp_strs; |
| 3483 |
uint32_t* tmp_htable; |
| 3484 |
|
| 3485 |
uintptr_t* filter_set; |
| 3486 |
|
| 3487 |
// concatenation: allele_remap results used immediately for .pgen |
| 3488 |
// general case: allele_remap results from .pvar merging pass thrown away, |
| 3489 |
// we re-scrape when merging .pgen |
| 3490 |
AlleleCode* allele_remap; // variant-major |
| 3491 |
|
| 3492 |
const char* const* info_keys; |
| 3493 |
const uint32_t* info_keys_htable; |
| 3494 |
uint32_t info_key_ct; |
| 3495 |
uint32_t info_keys_htable_size; |
| 3496 |
uint32_t info_conflict_present; |
| 3497 |
char* info_missing_str; |
| 3498 |
char* locked_missing_semicolon_str; |
| 3499 |
char* missing_semicolon_str; |
| 3500 |
char* locked_missing_comma_str; |
| 3501 |
char* missing_comma_str; |
| 3502 |
char* pr_str; |
| 3503 |
uintptr_t* info_field_set; |
| 3504 |
char** basic_info_fields; |
| 3505 |
char*** ar_info_fields; // types A and R have multiple subfields |
| 3506 |
uint32_t* read_info_field_order; |
| 3507 |
uint32_t pr_kidx; |
| 3508 |
|
| 3509 |
const char** fnames; |
| 3510 |
uintptr_t* line_idx_body_starts; |
| 3511 |
|
| 3512 |
// low bit = writing to final, next bit = reading from tmp |
| 3513 |
unsigned char tmp_status; |
| 3514 |
|
| 3515 |
char* chr_buf; |
| 3516 |
uint32_t chr_slen; |
| 3517 |
uint32_t cur_bp; |
| 3518 |
} PvariantMergeContext; |
| 3519 |
|
| 3520 |
typedef struct PvariantPosMergeContextStruct { |
| 3521 |
PvariantMergeContext pmc; |
| 3522 |
|
| 3523 |
SortMode sort_vars_mode; |
| 3524 |
AlleleCode max_written_allele_ct; |
| 3525 |
uint32_t max_written_single_pos_ct; |
| 3526 |
uintptr_t max_written_line_blen; |
| 3527 |
uintptr_t max_written_pos_blen; |
| 3528 |
|
| 3529 |
uintptr_t* write_allele_idx_offsets; |
| 3530 |
uintptr_t* write_nonref_flags; |
| 3531 |
uint32_t write_variant_idx; |
| 3532 |
uint32_t next_print_variant_idx; |
| 3533 |
uint32_t write_variant_ct; |
| 3534 |
} PvariantPosMergeContext; |
| 3535 |
|
| 3536 |
void PreinitPvariantPosMergeContext(PvariantPosMergeContext* ppmcp) { |
| 3537 |
ppmcp->pmc.cswritep = nullptr; |
| 3538 |
PreinitCstream(&ppmcp->pmc.css); |
| 3539 |
} |
| 3540 |
|
| 3541 |
// this should be more than enough |
| 3542 |
CONSTI32(kMaxFilterCt, 65535); |
| 3543 |
#define MAX_FILTER_CT_STR "65535" |
| 3544 |
|
| 3545 |
PglErr InitPvariantPosMergeContext(const PmergeInfo* pmip, const char* out_fname, const char* const* info_keys, const uint32_t* info_keys_htable, const char** fnames, uintptr_t* line_idx_body_starts, uint32_t write_qual, uint32_t write_filter, uint32_t write_info, uint32_t write_cm, uint32_t info_key_ct, uint32_t info_keys_htable_size, uint32_t info_conflict_present, SortMode sort_vars_mode, uint32_t is_tmp_src, uint32_t is_final_dst, uint32_t output_zst, uintptr_t overflow_buf_size, uint32_t read_max_allele_ct, uint32_t write_max_allele_ct, uintptr_t max_single_pos_ct, uint32_t read_max_nonpass_filter_ct, PvariantPosMergeContext* ppmcp) { |
| 3546 |
PvariantMergeContext* pmcp = &ppmcp->pmc; |
| 3547 |
PglErr reterr = InitCstreamAlloc(out_fname, is_final_dst, output_zst, 1, overflow_buf_size, &pmcp->css, &pmcp->cswritep); |
| 3548 |
if (unlikely(reterr)) { |
| 3549 |
return reterr; |
| 3550 |
} |
| 3551 |
|
| 3552 |
pmcp->write_qual = write_qual; |
| 3553 |
pmcp->write_filter = write_filter; |
| 3554 |
pmcp->write_info = write_info; |
| 3555 |
pmcp->write_cm = write_cm; |
| 3556 |
pmcp->merge_qual_mode = pmip->merge_qual_mode; |
| 3557 |
MergeFilterMode merge_filter_mode = pmip->merge_filter_mode; |
| 3558 |
if (!read_max_nonpass_filter_ct) { |
| 3559 |
if ((merge_filter_mode == kMergeFilterModeNonpassUnion) || (merge_filter_mode == kMergeFilterModeNmMatch)) { |
| 3560 |
// only need to distinguish PASS vs. missing in this common case |
| 3561 |
merge_filter_mode = kMergeFilterModeNmFirst; |
| 3562 |
} |
| 3563 |
} |
| 3564 |
pmcp->merge_filter_mode = merge_filter_mode; |
| 3565 |
pmcp->merge_info_mode = pmip->merge_info_mode; |
| 3566 |
pmcp->merge_cm_mode = pmip->merge_info_mode; |
| 3567 |
pmcp->merge_info_sort = pmip->merge_info_sort; |
| 3568 |
const uint32_t max_allele_ct = pmip->max_allele_ct; |
| 3569 |
pmcp->max_allele_ct = max_allele_ct; |
| 3570 |
|
| 3571 |
char* cswritep = strcpya_k(pmcp->cswritep, "#CHROM\tPOS\tID\tREF\tALT"); |
| 3572 |
if (write_qual) { |
| 3573 |
cswritep = strcpya_k(cswritep, "\tQUAL"); |
| 3574 |
} |
| 3575 |
if (write_filter) { |
| 3576 |
cswritep = strcpya_k(cswritep, "\tFILTER"); |
| 3577 |
} |
| 3578 |
if (write_info) { |
| 3579 |
cswritep = strcpya_k(cswritep, "\tINFO"); |
| 3580 |
} |
| 3581 |
if (write_cm) { |
| 3582 |
cswritep = strcpya_k(cswritep, "\tCM"); |
| 3583 |
} |
| 3584 |
AppendBinaryEoln(&cswritep); |
| 3585 |
pmcp->cswritep = cswritep; |
| 3586 |
|
| 3587 |
if (unlikely(bigstack_alloc_ac(max_single_pos_ct * read_max_allele_ct, &pmcp->allele_remap))) { |
| 3588 |
return kPglRetNomem; |
| 3589 |
} |
| 3590 |
pmcp->cur_fields_buf = nullptr; |
| 3591 |
pmcp->cur_slens_buf = nullptr; |
| 3592 |
pmcp->allele_cts_buf = nullptr; |
| 3593 |
pmcp->is_pr_buf = nullptr; |
| 3594 |
pmcp->tmp_strs = nullptr; |
| 3595 |
pmcp->tmp_htable = nullptr; |
| 3596 |
pmcp->filter_set = nullptr; |
| 3597 |
pmcp->read_max_allele_ct = read_max_allele_ct; |
| 3598 |
if (max_single_pos_ct > 1) { |
| 3599 |
// Need space for 1 more than the allele-count-limit, since we need to be |
| 3600 |
// able to write tombstones. |
| 3601 |
const uint32_t merged_allele_ct_max_p1 = max_allele_ct? (max_allele_ct + 1) : (kPglMaxAlleleCt + 1); |
| 3602 |
|
| 3603 |
const uint32_t filter_ct_max = MINV(1 + max_single_pos_ct * read_max_nonpass_filter_ct, kMaxFilterCt); |
| 3604 |
const uint32_t str_ct_max = MAXV(merged_allele_ct_max_p1, filter_ct_max); |
| 3605 |
const uint32_t htable_size = GetHtableMinSize(str_ct_max); |
| 3606 |
if (unlikely(bigstack_alloc_cp(max_single_pos_ct, &pmcp->cur_fields_buf) || |
| 3607 |
bigstack_alloc_u32(max_single_pos_ct, &pmcp->cur_slens_buf) || |
| 3608 |
bigstack_alloc_ac(max_single_pos_ct, &pmcp->allele_cts_buf) || |
| 3609 |
bigstack_alloc_w(BitCtToWordCt(max_single_pos_ct), &pmcp->is_pr_buf) || |
| 3610 |
bigstack_alloc_kcp(str_ct_max, &pmcp->tmp_strs) || |
| 3611 |
bigstack_alloc_u32(htable_size, &pmcp->tmp_htable))) { |
| 3612 |
return kPglRetNomem; |
| 3613 |
} |
| 3614 |
if (merge_filter_mode == kMergeFilterModeNmMatch) { |
| 3615 |
if (unlikely(bigstack_alloc_w(BitCtToWordCt(filter_ct_max), &pmcp->filter_set))) { |
| 3616 |
return kPglRetNomem; |
| 3617 |
} |
| 3618 |
} |
| 3619 |
} |
| 3620 |
|
| 3621 |
pmcp->info_keys = info_keys; |
| 3622 |
pmcp->info_keys_htable = info_keys_htable; |
| 3623 |
pmcp->info_key_ct = info_key_ct; |
| 3624 |
pmcp->info_keys_htable_size = info_keys_htable_size; |
| 3625 |
pmcp->info_conflict_present = info_conflict_present; |
| 3626 |
pmcp->info_missing_str = nullptr; |
| 3627 |
pmcp->locked_missing_semicolon_str = nullptr; |
| 3628 |
pmcp->missing_semicolon_str = nullptr; |
| 3629 |
pmcp->locked_missing_comma_str = nullptr; |
| 3630 |
pmcp->missing_comma_str = nullptr; |
| 3631 |
pmcp->pr_str = nullptr; |
| 3632 |
pmcp->info_field_set = nullptr; |
| 3633 |
pmcp->basic_info_fields = nullptr; |
| 3634 |
pmcp->ar_info_fields = nullptr; |
| 3635 |
pmcp->read_info_field_order = nullptr; |
| 3636 |
pmcp->pr_kidx = UINT32_MAX; |
| 3637 |
if (info_key_ct) { |
| 3638 |
char*** ar_info_fields = nullptr; |
| 3639 |
if (unlikely(bigstack_alloc_w(BitCtToWordCt(info_key_ct), &pmcp->info_field_set) || |
| 3640 |
bigstack_calloc_cpp(info_key_ct, &ar_info_fields) || |
| 3641 |
bigstack_alloc_u32(info_key_ct, &pmcp->read_info_field_order))) { |
| 3642 |
return kPglRetNomem; |
| 3643 |
} |
| 3644 |
char** ar_info_alloc_iter = R_CAST(char**, g_bigstack_base); |
| 3645 |
char** ar_info_alloc_limit = R_CAST(char**, BigstackEndRoundedDown()); |
| 3646 |
uint32_t ar_info_ct = 0; |
| 3647 |
int32_t max_num = 1; |
| 3648 |
for (uint32_t info_key_idx = 0; info_key_idx != info_key_ct; ++info_key_idx) { |
| 3649 |
const int32_t info_vtype = const_container_of(info_keys[info_key_idx], InfoVtype, key)->num; |
| 3650 |
if (!IsInfoVtypeARSkip(info_vtype)) { |
| 3651 |
if (max_num < info_vtype) { |
| 3652 |
max_num = info_vtype; |
| 3653 |
} |
| 3654 |
continue; |
| 3655 |
} |
| 3656 |
++ar_info_ct; |
| 3657 |
const uintptr_t subfield_ct = write_max_allele_ct + kInfoVtypeR - info_vtype; |
| 3658 |
if (unlikely(S_CAST(uintptr_t, ar_info_alloc_limit - ar_info_alloc_iter) < subfield_ct)) { |
| 3659 |
return kPglRetNomem; |
| 3660 |
} |
| 3661 |
ar_info_fields[info_key_idx] = ar_info_alloc_iter; |
| 3662 |
ar_info_alloc_iter = &(ar_info_alloc_iter[subfield_ct]); |
| 3663 |
} |
| 3664 |
if (ar_info_ct) { |
| 3665 |
BigstackBaseSet(ar_info_alloc_iter); |
| 3666 |
pmcp->ar_info_fields = ar_info_fields; |
| 3667 |
} else { |
| 3668 |
BigstackReset(ar_info_fields); |
| 3669 |
} |
| 3670 |
if (ar_info_ct != info_key_ct) { |
| 3671 |
if (unlikely(bigstack_calloc_cp(info_key_ct, &pmcp->basic_info_fields))) { |
| 3672 |
return kPglRetNomem; |
| 3673 |
} |
| 3674 |
} |
| 3675 |
if (unlikely(bigstack_alloc_c(2 * max_num, &pmcp->info_missing_str) || |
| 3676 |
bigstack_alloc_c(strlen("PR;==;=.;=,.,"), &pmcp->pr_str))) { |
| 3677 |
return kPglRetNomem; |
| 3678 |
} |
| 3679 |
u16setsa(pmcp->info_missing_str, 0x2e2c, max_num); |
| 3680 |
pmcp->info_missing_str[0] = '='; |
| 3681 |
pmcp->locked_missing_semicolon_str = &(pmcp->pr_str[3]); |
| 3682 |
pmcp->missing_semicolon_str = &(pmcp->pr_str[6]); |
| 3683 |
pmcp->locked_missing_comma_str = &(pmcp->pr_str[9]); |
| 3684 |
pmcp->missing_comma_str = &(pmcp->pr_str[11]); |
| 3685 |
|
| 3686 |
pmcp->pr_kidx = IdHtableFind("PR", info_keys, info_keys_htable, strlen("PR"), info_keys_htable_size); |
| 3687 |
} |
| 3688 |
pmcp->fnames = fnames; |
| 3689 |
pmcp->line_idx_body_starts = line_idx_body_starts; |
| 3690 |
|
| 3691 |
pmcp->tmp_status = is_final_dst + 2 * is_tmp_src; |
| 3692 |
|
| 3693 |
ppmcp->sort_vars_mode = sort_vars_mode; |
| 3694 |
ppmcp->max_written_allele_ct = 2; |
| 3695 |
ppmcp->max_written_single_pos_ct = 1; |
| 3696 |
ppmcp->max_written_line_blen = 0; |
| 3697 |
ppmcp->max_written_pos_blen = 0; |
| 3698 |
ppmcp->write_allele_idx_offsets = nullptr; |
| 3699 |
ppmcp->write_nonref_flags = nullptr; |
| 3700 |
ppmcp->write_variant_idx = 0; |
| 3701 |
ppmcp->next_print_variant_idx = 10000; |
| 3702 |
ppmcp->write_variant_ct = 0; |
| 3703 |
return kPglRetSuccess; |
| 3704 |
} |
| 3705 |
|
| 3706 |
BoolErr FlushPvarCounted(PvariantMergeContext* pmcp, char** cswritepp, uint64_t* cur_line_blenp) { |
| 3707 |
if (S_CAST(uintptr_t, (*cswritepp) - pmcp->css.overflow_buf) < kCompressStreamBlock + 1) { |
| 3708 |
return 0; |
| 3709 |
} |
| 3710 |
*cur_line_blenp += (*cswritepp) - pmcp->cswritep; |
| 3711 |
BoolErr reterr; |
| 3712 |
if (IsUncompressedCstream(&pmcp->css)) { |
| 3713 |
reterr = ForceUncompressedCswrite(&pmcp->css, cswritepp); |
| 3714 |
} else { |
| 3715 |
reterr = ForceCompressedCswrite(&pmcp->css, cswritepp); |
| 3716 |
} |
| 3717 |
pmcp->cswritep = *cswritepp; |
| 3718 |
return reterr; |
| 3719 |
} |
| 3720 |
|
| 3721 |
static_assert(sizeof(AlleleCode) == 1, "RenderFinalInfoFromSingleTmp() needs to be updated."); |
| 3722 |
PglErr RenderFinalInfoFromSingleTmp(uint32_t read_info_slen, PvariantMergeContext* pmcp, char* read_info_start, char** cswritepp) { |
| 3723 |
// Since the input is from a tmp file, we can assume keys are already sorted |
| 3724 |
// and all values are valid. We only need to convert '=' locked-missing |
| 3725 |
// values to regular missing values. |
| 3726 |
// Flag (0) -> can't happen, there's no notion of a missing value (or a |
| 3727 |
// value at all, for that matter), there are only missing keys |
| 3728 |
// positive number -> that number of '.'; we do not resolve each entry |
| 3729 |
// separately since we generally want to do the simplest |
| 3730 |
// thing that might work. A/R is different since we |
| 3731 |
// actually know a raw string comparison won't work when |
| 3732 |
// allele reordering is involved. (G is punted since |
| 3733 |
// chrX is a nightmare.) |
| 3734 |
// unknown/G (-1) -> single '.' |
| 3735 |
// A/R -> each allele entry resolved separately |
| 3736 |
char* cswritep = *cswritepp; |
| 3737 |
*cswritep++ = '\t'; |
| 3738 |
const char* const* info_keys = pmcp->info_keys; |
| 3739 |
const uint32_t* info_keys_htable = pmcp->info_keys_htable; |
| 3740 |
const uint32_t info_keys_htable_size = pmcp->info_keys_htable_size; |
| 3741 |
char* read_info_end = &(read_info_start[read_info_slen + 1]); |
| 3742 |
read_info_end[-1] = ';'; |
| 3743 |
char* read_info_iter = read_info_start; |
| 3744 |
do { |
| 3745 |
char* key_end = S_CAST(char*, rawmemchr2(read_info_iter, '=', ';')); |
| 3746 |
const uint32_t key_slen = key_end - read_info_iter; |
| 3747 |
if (*key_end == ';') { |
| 3748 |
// flag |
| 3749 |
cswritep = memcpya(cswritep, read_info_iter, key_slen + 1); |
| 3750 |
read_info_iter = &(key_end[1]); |
| 3751 |
continue; |
| 3752 |
} |
| 3753 |
const uint32_t kidx = IdHtableFindNnt(read_info_iter, info_keys, info_keys_htable, key_slen, info_keys_htable_size); |
| 3754 |
assert(kidx && (kidx != UINT32_MAX)); |
| 3755 |
const int32_t knum = const_container_of(info_keys[kidx], InfoVtype, key)->num; |
| 3756 |
char* value_iter = &(key_end[1]); |
| 3757 |
read_info_iter = AdvPastDelim(value_iter, ';'); |
| 3758 |
if (!IsInfoVtypeARSkip(knum)) { |
| 3759 |
if (value_iter[0] != '=') { |
| 3760 |
cswritep = memcpya(cswritep, key_end, read_info_iter - key_end); |
| 3761 |
} else { |
| 3762 |
cswritep = strcpya_k(cswritep, "=."); |
| 3763 |
if (knum > 1) { |
| 3764 |
// ",." |
| 3765 |
cswritep = u16setsa(cswritep, 0x2e2c, knum - 1); |
| 3766 |
} |
| 3767 |
*cswritep++ = ';'; |
| 3768 |
} |
| 3769 |
} else { |
| 3770 |
char* field_end = &(read_info_iter[-1]); |
| 3771 |
*field_end = '='; |
| 3772 |
while (1) { |
| 3773 |
char* next_eq = AdvToDelim(value_iter, '='); |
| 3774 |
cswritep = memcpya(cswritep, value_iter, next_eq - value_iter); |
| 3775 |
if (next_eq == field_end) { |
| 3776 |
break; |
| 3777 |
} |
| 3778 |
*cswritep++ = '.'; |
| 3779 |
value_iter = &(next_eq[1]); |
| 3780 |
} |
| 3781 |
*cswritep++ = ';'; |
| 3782 |
} |
| 3783 |
} while (read_info_iter != read_info_end); |
| 3784 |
*cswritepp = &(cswritep[-1]); |
| 3785 |
return kPglRetSuccess; |
| 3786 |
} |
| 3787 |
|
| 3788 |
// Need to sort by key, but don't need to worry about reading/writing |
| 3789 |
// locked-missing values or managing Number=A/R/G subfields. |
| 3790 |
PglErr RenderTmpInfoFromSingleUnsorted(const char* read_pvar_fname, uintptr_t line_idx, uint32_t read_info_slen, uint32_t lone_pgen_pr, PvariantMergeContext* pmcp, char* read_info_start, char** cswritepp, uint32_t* is_pr_ptr) { |
| 3791 |
const char* const* info_keys = pmcp->info_keys; |
| 3792 |
const uint32_t* info_keys_htable = pmcp->info_keys_htable; |
| 3793 |
const uint32_t info_key_ct = pmcp->info_key_ct; |
| 3794 |
const uint32_t info_keys_htable_size = pmcp->info_keys_htable_size; |
| 3795 |
const uint32_t info_key_ctl = BitCtToWordCt(info_key_ct); |
| 3796 |
uintptr_t* info_field_set = pmcp->info_field_set; |
| 3797 |
ZeroWArr(info_key_ctl, info_field_set); |
| 3798 |
char** basic_info_fields = pmcp->basic_info_fields; |
| 3799 |
char* read_info_end = &(read_info_start[read_info_slen + 1]); |
| 3800 |
read_info_end[-1] = ';'; |
| 3801 |
char* read_info_iter = read_info_start; |
| 3802 |
do { |
| 3803 |
char* key_end = S_CAST(char*, rawmemchr2(read_info_iter, '=', ';')); |
| 3804 |
const uint32_t key_slen = key_end - read_info_iter; |
| 3805 |
const uint32_t kidx = IdHtableFindNnt(read_info_iter, info_keys, info_keys_htable, key_slen, info_keys_htable_size); |
| 3806 |
if (kidx == UINT32_MAX) { |
| 3807 |
// Skip this key. This can happen on e.g. a header conflict. |
| 3808 |
if (*key_end != ';') { |
| 3809 |
key_end = AdvToDelim(&(key_end[1]), ';'); |
| 3810 |
} |
| 3811 |
read_info_iter = &(key_end[1]); |
| 3812 |
continue; |
| 3813 |
} |
| 3814 |
if (unlikely(IsSet(info_field_set, kidx))) { |
| 3815 |
*key_end = '\0'; |
| 3816 |
logputs("\n"); |
| 3817 |
logerrprintfww("Error: Duplicate INFO key '%s' on line %" PRIuPTR " of %s.\n", read_info_iter, line_idx, read_pvar_fname); |
| 3818 |
return kPglRetMalformedInput; |
| 3819 |
} |
| 3820 |
SetBit(kidx, info_field_set); |
| 3821 |
const int32_t knum = const_container_of(info_keys[kidx], InfoVtype, key)->num; |
| 3822 |
if (unlikely((knum == 0) != (*key_end == ';'))) { |
| 3823 |
logputs("\n"); |
| 3824 |
logerrprintfww("Error: Line %" PRIuPTR " of %s has a malformed INFO field (%s immediate ';').\n", line_idx, read_pvar_fname, (knum != 0)? "non-flag key followed by" : "flag key followed by '=' instead of"); |
| 3825 |
// InconsistentInput instead of MalformedInput error code since this |
| 3826 |
// may be caused by inconsistent headers across files |
| 3827 |
return kPglRetInconsistentInput; |
| 3828 |
} |
| 3829 |
// just leave everything semicolon-terminated |
| 3830 |
basic_info_fields[kidx] = read_info_iter; |
| 3831 |
if (knum == 0) { |
| 3832 |
read_info_iter = &(key_end[1]); |
| 3833 |
} else { |
| 3834 |
char* value_end = AdvToDelim(&(key_end[1]), ';'); |
| 3835 |
read_info_iter = &(value_end[1]); |
| 3836 |
} |
| 3837 |
} while (read_info_iter != read_info_end); |
| 3838 |
if (lone_pgen_pr) { |
| 3839 |
const uint32_t pr_kidx = pmcp->pr_kidx; |
| 3840 |
SetBit(pr_kidx, info_field_set); |
| 3841 |
basic_info_fields[pr_kidx] = pmcp->pr_str; |
| 3842 |
} |
| 3843 |
const uint32_t observed_key_ct = PopcountWords(info_field_set, info_key_ctl); |
| 3844 |
if (!observed_key_ct) { |
| 3845 |
*cswritepp = strcpya_k(*cswritepp, "\t."); |
| 3846 |
return kPglRetSuccess; |
| 3847 |
} |
| 3848 |
char* cswritep = *cswritepp; |
| 3849 |
*cswritep++ = '\t'; |
| 3850 |
uintptr_t kidx_base = 0; |
| 3851 |
uintptr_t cur_bits = info_field_set[0]; |
| 3852 |
for (uint32_t uii = 0; uii != observed_key_ct; ++uii) { |
| 3853 |
const uint32_t kidx = BitIter1(info_field_set, &kidx_base, &cur_bits); |
| 3854 |
char* kv_start = basic_info_fields[kidx]; |
| 3855 |
char* kv_end = AdvPastDelim(kv_start, ';'); |
| 3856 |
cswritep = memcpya(cswritep, kv_start, kv_end - kv_start); |
| 3857 |
} |
| 3858 |
if (is_pr_ptr) { |
| 3859 |
*is_pr_ptr = IsSet(info_field_set, pmcp->pr_kidx); |
| 3860 |
} |
| 3861 |
*cswritepp = &(cswritep[-1]); |
| 3862 |
return kPglRetSuccess; |
| 3863 |
} |
| 3864 |
|
| 3865 |
// [0] = REF |
| 3866 |
// [1] = ALT |
| 3867 |
// [2] = QUAL |
| 3868 |
// [3] = FILTER |
| 3869 |
// [4] = INFO |
| 3870 |
// [5] = CM (null-terminated string always present, default "0") |
| 3871 |
typedef struct SamePosPvarRecordStruct { |
| 3872 |
uint32_t other_field_offsets[6]; |
| 3873 |
// High 32 bits = filename index, low bits = variant index |
| 3874 |
uint64_t secondary_key; |
| 3875 |
AlleleCode allele_ct; |
| 3876 |
// low bit = .pgen PR flag; next bit = does .pvar have a INFO/PR field? |
| 3877 |
unsigned char pgen_pr_status; |
| 3878 |
char variant_id[]; |
| 3879 |
} SamePosPvarRecord; |
| 3880 |
|
| 3881 |
// returns allele_ct == 0 if allele is filtered out, otherwise at least 2 |
| 3882 |
// if non-null, *is_pr_ptr must be initialized to 0 |
| 3883 |
// record fields assumed to be null-terminated, but this may change in the |
| 3884 |
// middle of the function |
| 3885 |
PglErr MergePvariant(uintptr_t merge_rec_ct, PvariantMergeContext* pmcp, SamePosPvarRecord** same_id_records, uint32_t* is_pr_ptr, uint32_t* allele_ct_ptr, uint64_t* cur_line_blenp) { |
| 3886 |
char* cswritep = memcpyax(pmcp->cswritep, pmcp->chr_buf, pmcp->chr_slen, '\t'); |
| 3887 |
cswritep = u32toa_x(pmcp->cur_bp, '\t', cswritep); |
| 3888 |
char* cur_variant_id = same_id_records[0]->variant_id; |
| 3889 |
cswritep = strcpyax(cswritep, cur_variant_id, '\t'); |
| 3890 |
const uint32_t max_allele_ct = pmcp->max_allele_ct; |
| 3891 |
const uint32_t tmp_status = pmcp->tmp_status; |
| 3892 |
AlleleCode* allele_remap = pmcp->allele_remap; |
| 3893 |
if (merge_rec_ct == 1) { |
| 3894 |
SamePosPvarRecord* cur_record = same_id_records[0]; |
| 3895 |
const uint32_t read_allele_ct = cur_record->allele_ct; |
| 3896 |
if (max_allele_ct && (read_allele_ct > max_allele_ct)) { |
| 3897 |
if (tmp_status & 1) { |
| 3898 |
// cswritep not saved, so this rolls back the 3-column-write above |
| 3899 |
*allele_ct_ptr = 0; |
| 3900 |
return kPglRetSuccess; |
| 3901 |
} |
| 3902 |
// Need to write a tombstone. |
| 3903 |
*allele_ct_ptr = max_allele_ct + 1; |
| 3904 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 3905 |
const uint32_t ref_offset = other_field_offsets[0]; |
| 3906 |
const uint32_t alt_offset = other_field_offsets[1]; |
| 3907 |
cswritep = memcpya(cswritep, &(cur_variant_id[ref_offset]), alt_offset - ref_offset); |
| 3908 |
cswritep[-1] = '\t'; |
| 3909 |
char* alt_start = &(cur_variant_id[alt_offset]); |
| 3910 |
if (read_allele_ct == max_allele_ct + 1) { |
| 3911 |
const uint32_t qual_offset = other_field_offsets[2]; |
| 3912 |
cswritep = memcpya(cswritep, alt_start, qual_offset - alt_offset - 1); |
| 3913 |
} else { |
| 3914 |
char* alt_trunc = AdvToNthDelim(alt_start, max_allele_ct, ','); |
| 3915 |
cswritep = memcpya(cswritep, alt_start, alt_trunc - alt_start); |
| 3916 |
} |
| 3917 |
// doesn't matter if we write a few extra fields |
| 3918 |
cswritep = strcpya_k(cswritep, "\t.\t.\t.\t0" EOLN_STR); |
| 3919 |
*cur_line_blenp = cswritep - pmcp->cswritep; |
| 3920 |
if (unlikely(Cswrite(&pmcp->css, &cswritep))) { |
| 3921 |
return kPglRetWriteFail; |
| 3922 |
} |
| 3923 |
pmcp->cswritep = cswritep; |
| 3924 |
return kPglRetSuccess; |
| 3925 |
} |
| 3926 |
*allele_ct_ptr = read_allele_ct; |
| 3927 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 3928 |
const uint32_t ref_offset = other_field_offsets[0]; |
| 3929 |
const uint32_t alt_offset = other_field_offsets[1]; |
| 3930 |
const uint32_t qual_offset = other_field_offsets[2]; |
| 3931 |
{ |
| 3932 |
const char* ref_and_alt_str = &(cur_variant_id[ref_offset]); |
| 3933 |
const uint32_t ref_and_alt_slen = qual_offset - 1 - ref_offset; |
| 3934 |
cswritep = memcpya(cswritep, ref_and_alt_str, ref_and_alt_slen); |
| 3935 |
cswritep[S_CAST(int32_t, alt_offset - qual_offset)] = '\t'; |
| 3936 |
// only need to initialize first two entries |
| 3937 |
// possible todo: detect missing allele codes here so we can validate |
| 3938 |
allele_remap[0] = 0; |
| 3939 |
allele_remap[1] = 1; |
| 3940 |
} |
| 3941 |
if (pmcp->write_qual) { |
| 3942 |
const uint32_t read_qual_blen = other_field_offsets[3] - qual_offset; |
| 3943 |
if (!read_qual_blen) { |
| 3944 |
cswritep = strcpya_k(cswritep, "\t."); |
| 3945 |
} else { |
| 3946 |
char* read_qual_start = &(cur_variant_id[qual_offset]); |
| 3947 |
if ((tmp_status != 3) || (!strequal_k_unsafe(read_qual_start, "="))) { |
| 3948 |
*cswritep++ = '\t'; |
| 3949 |
cswritep = memcpya(cswritep, read_qual_start, read_qual_blen - 1); |
| 3950 |
} else { |
| 3951 |
cswritep = strcpya_k(cswritep, "\t."); |
| 3952 |
} |
| 3953 |
} |
| 3954 |
} |
| 3955 |
if (pmcp->write_filter) { |
| 3956 |
const uint32_t filter_offset = other_field_offsets[3]; |
| 3957 |
const uint32_t read_filter_blen = other_field_offsets[4] - filter_offset; |
| 3958 |
if (!read_filter_blen) { |
| 3959 |
cswritep = strcpya_k(cswritep, "\t."); |
| 3960 |
} else { |
| 3961 |
char* read_filter_start = &(cur_variant_id[filter_offset]); |
| 3962 |
if ((tmp_status != 3) || (!strequal_k_unsafe(read_filter_start, "="))) { |
| 3963 |
*cswritep++ = '\t'; |
| 3964 |
cswritep = memcpya(cswritep, read_filter_start, read_filter_blen - 1); |
| 3965 |
} else { |
| 3966 |
cswritep = strcpya_k(cswritep, "\t."); |
| 3967 |
} |
| 3968 |
} |
| 3969 |
} |
| 3970 |
if (pmcp->write_info) { |
| 3971 |
const uint32_t info_offset = other_field_offsets[4]; |
| 3972 |
const uint32_t read_info_blen = other_field_offsets[5] - info_offset; |
| 3973 |
const uint32_t lone_pgen_pr = (cur_record->pgen_pr_status == 1); |
| 3974 |
if (is_pr_ptr && (cur_record->pgen_pr_status & 1)) { |
| 3975 |
*is_pr_ptr = 1; |
| 3976 |
is_pr_ptr = nullptr; |
| 3977 |
} |
| 3978 |
char* read_info_start = &(cur_variant_id[info_offset]); |
| 3979 |
if ((!read_info_blen) || ((read_info_blen == 1) && (read_info_start[0] == '.'))) { |
| 3980 |
if (!lone_pgen_pr) { |
| 3981 |
cswritep = strcpya_k(cswritep, "\t."); |
| 3982 |
} else { |
| 3983 |
cswritep = strcpya_k(cswritep, "\tPR"); |
| 3984 |
} |
| 3985 |
} else { |
| 3986 |
const uint32_t read_info_slen = read_info_blen - 1; |
| 3987 |
if ((pmcp->merge_info_sort == kSortNone) || (tmp_status & 2)) { |
| 3988 |
if ((pmcp->merge_info_mode == kMergeInfoCmModeNmFirst) || (tmp_status != 3)) { |
| 3989 |
*cswritep++ = '\t'; |
| 3990 |
if ((!pmcp->info_conflict_present) || (tmp_status & 2)) { |
| 3991 |
cswritep = memcpya(cswritep, read_info_start, read_info_slen); |
| 3992 |
} else { |
| 3993 |
// Line may contain key(s) that were filtered out during .pvar |
| 3994 |
// header merge due to a conflict. Remove the corresponding |
| 3995 |
// INFO keys from every line. This incidentally also removes |
| 3996 |
// INFO keys that were (improperly) not declared at all in the |
| 3997 |
// header. |
| 3998 |
// We don't promise to remove undeclared INFO keys in the general |
| 3999 |
// case, since this code path is substantially more expensive |
| 4000 |
// than the memcpya() above. Any user who does want to guarantee |
| 4001 |
// removal of such keys (and detection of duplicate keys) can use |
| 4002 |
// --merge-info-sort. |
| 4003 |
const char* const* info_keys = pmcp->info_keys; |
| 4004 |
const uint32_t* info_keys_htable = pmcp->info_keys_htable; |
| 4005 |
const uint32_t info_keys_htable_size = pmcp->info_keys_htable_size; |
| 4006 |
char* read_info_iter = read_info_start; |
| 4007 |
char* read_info_end = &(read_info_start[read_info_slen]); |
| 4008 |
char* initial_write_ptr = cswritep; |
| 4009 |
*read_info_end++ = ';'; |
| 4010 |
do { |
| 4011 |
char* key_end = S_CAST(char*, rawmemchr2(read_info_iter, '=', ';')); |
| 4012 |
const uint32_t key_slen = key_end - read_info_iter; |
| 4013 |
const uint32_t kidx = IdHtableFindNnt(read_info_iter, info_keys, info_keys_htable, key_slen, info_keys_htable_size); |
| 4014 |
char* value_end = key_end; |
| 4015 |
if (*value_end != ';') { |
| 4016 |
value_end = AdvToDelim(&(value_end[1]), ';'); |
| 4017 |
} |
| 4018 |
++value_end; |
| 4019 |
if (kidx != UINT32_MAX) { |
| 4020 |
cswritep = memcpya(cswritep, read_info_iter, value_end - read_info_iter); |
| 4021 |
} |
| 4022 |
read_info_iter = value_end; |
| 4023 |
} while (read_info_iter != read_info_end); |
| 4024 |
read_info_end[-1] = '\0'; |
| 4025 |
if (cswritep == initial_write_ptr) { |
| 4026 |
*cswritep++ = '.'; |
| 4027 |
} else { |
| 4028 |
// strip trailing semicolon |
| 4029 |
--cswritep; |
| 4030 |
} |
| 4031 |
} |
| 4032 |
if (lone_pgen_pr) { |
| 4033 |
cswritep = strcpya_k(cswritep, ";PR"); |
| 4034 |
} else if (is_pr_ptr != nullptr) { |
| 4035 |
*is_pr_ptr = PrInInfo(read_info_slen, read_info_start); |
| 4036 |
} |
| 4037 |
} else { |
| 4038 |
// convert from tmp to final. |
| 4039 |
// lone_pgen_pr is impossible here, since we wrote an INFO column |
| 4040 |
// to the tmp file, and when we do we'll always insert INFO/PR when |
| 4041 |
// relevant. is_pr_ptr != nullptr is also impossible, for the |
| 4042 |
// converse reason. |
| 4043 |
PglErr reterr = RenderFinalInfoFromSingleTmp(read_info_slen, pmcp, read_info_start, &cswritep); |
| 4044 |
if (unlikely(reterr)) { |
| 4045 |
return reterr; |
| 4046 |
} |
| 4047 |
} |
| 4048 |
} else { |
| 4049 |
// merge_info_sort != kSortNone, reading from original. |
| 4050 |
// So we need to sort by key, but we don't need to worry about |
| 4051 |
// reading/writing locked-missing values. |
| 4052 |
const uint32_t file_idx = cur_record->secondary_key >> 32; |
| 4053 |
const uint32_t variant_uidx = S_CAST(uint32_t, cur_record->secondary_key); |
| 4054 |
PglErr reterr = RenderTmpInfoFromSingleUnsorted(pmcp->fnames[file_idx], pmcp->line_idx_body_starts[file_idx] + variant_uidx, read_info_slen, lone_pgen_pr, pmcp, read_info_start, &cswritep, is_pr_ptr); |
| 4055 |
if (unlikely(reterr)) { |
| 4056 |
return reterr; |
| 4057 |
} |
| 4058 |
} |
| 4059 |
} |
| 4060 |
} else if (is_pr_ptr) { |
| 4061 |
const uint32_t info_offset = other_field_offsets[4]; |
| 4062 |
const uint32_t read_info_blen = other_field_offsets[5] - info_offset; |
| 4063 |
if (read_info_blen >= 2) { |
| 4064 |
char* read_info_start = &(cur_variant_id[info_offset]); |
| 4065 |
*is_pr_ptr = PrInInfo(read_info_blen - 1, read_info_start); |
| 4066 |
} |
| 4067 |
} |
| 4068 |
if (pmcp->write_cm) { |
| 4069 |
char* cm_start = &(cur_variant_id[other_field_offsets[5]]); |
| 4070 |
if ((tmp_status != 3) || (!strequal_k_unsafe(cm_start, "="))) { |
| 4071 |
*cswritep++ = '\t'; |
| 4072 |
cswritep = strcpya(cswritep, cm_start); |
| 4073 |
} else { |
| 4074 |
cswritep = strcpya_k(cswritep, "\t0"); |
| 4075 |
} |
| 4076 |
} |
| 4077 |
} else { |
| 4078 |
// 1. Merge alleles. Fast exit path if any source variant has more than |
| 4079 |
// max_allele_ct alleles on its own. |
| 4080 |
// 2. Merge QUAL. |
| 4081 |
// 3. Merge FILTER. |
| 4082 |
// 4. Merge INFO. |
| 4083 |
// 5. Merge CM. |
| 4084 |
const uintptr_t read_max_allele_ct = pmcp->read_max_allele_ct; |
| 4085 |
AlleleCode* allele_cts = pmcp->allele_cts_buf; |
| 4086 |
uint32_t is_pr = 0; |
| 4087 |
uint32_t merged_info_allele_ct; |
| 4088 |
{ |
| 4089 |
char** cur_refs = pmcp->cur_fields_buf; |
| 4090 |
uintptr_t* is_pr_bitarr = pmcp->is_pr_buf; |
| 4091 |
const uintptr_t merge_rec_ctl = BitCtToWordCt(merge_rec_ct); |
| 4092 |
ZeroWArr(merge_rec_ctl, is_pr_bitarr); |
| 4093 |
// First pass: fill cur_refs, allele_cts, is_pr_bitarr; null-terminate |
| 4094 |
// any extra ALT alleles |
| 4095 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4096 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4097 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4098 |
cur_variant_id = cur_record->variant_id; |
| 4099 |
cur_refs[rec_idx] = &(cur_variant_id[other_field_offsets[0]]); |
| 4100 |
const AlleleCode allele_ct = cur_record->allele_ct; |
| 4101 |
allele_cts[rec_idx] = cur_record->allele_ct; |
| 4102 |
if (allele_ct > 2) { |
| 4103 |
const uint32_t extra_alt_ct = allele_ct - 2; |
| 4104 |
char* alt_iter = &(cur_variant_id[other_field_offsets[1]]); |
| 4105 |
for (uint32_t uii = 0; uii != extra_alt_ct; ++uii) { |
| 4106 |
char* cur_alt_end = AdvToDelim(alt_iter, ','); |
| 4107 |
*cur_alt_end = '\0'; |
| 4108 |
alt_iter = &(cur_alt_end[1]); |
| 4109 |
} |
| 4110 |
} |
| 4111 |
const uint32_t pgen_pr_status = cur_record->pgen_pr_status; |
| 4112 |
if (pgen_pr_status & 1) { |
| 4113 |
SetBit(rec_idx, is_pr_bitarr); |
| 4114 |
} else if (pgen_pr_status) { |
| 4115 |
const uint32_t info_offset = other_field_offsets[4]; |
| 4116 |
const uint32_t info_blen = other_field_offsets[5] - info_offset; |
| 4117 |
char* info_start = &(cur_record->variant_id[info_offset]); |
| 4118 |
AssignBit(rec_idx, PrInInfo(info_blen - 1, info_start), is_pr_bitarr); |
| 4119 |
} |
| 4120 |
} |
| 4121 |
const uint32_t allele_ct_capacity = max_allele_ct? (max_allele_ct + 1) : (kPglMaxAlleleCt + 1); |
| 4122 |
uint32_t allele_ct_limit = 0; |
| 4123 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4124 |
allele_ct_limit += allele_cts[rec_idx]; |
| 4125 |
if (allele_ct_limit >= allele_ct_capacity) { |
| 4126 |
allele_ct_limit = allele_ct_capacity; |
| 4127 |
break; |
| 4128 |
} |
| 4129 |
} |
| 4130 |
const uint32_t htable_size = GetHtableMinSize(allele_ct_limit); |
| 4131 |
uint32_t* merged_alleles_htable = pmcp->tmp_htable; |
| 4132 |
SetAllU32Arr(htable_size, merged_alleles_htable); |
| 4133 |
const uintptr_t pr_ct = PopcountWords(is_pr_bitarr, merge_rec_ctl); |
| 4134 |
const char** merged_alleles = pmcp->tmp_strs; |
| 4135 |
uint32_t merged_allele_ct = 0; |
| 4136 |
if (pr_ct != merge_rec_ct) { |
| 4137 |
// REF allele known. Verify that we have agreement. |
| 4138 |
const uintptr_t known_ref_ct = merge_rec_ct - pr_ct; |
| 4139 |
uintptr_t rec_idx_base = 0; |
| 4140 |
uintptr_t inv_bits = ~is_pr_bitarr[0]; |
| 4141 |
uintptr_t rec_idx = BitIter0(is_pr_bitarr, &rec_idx_base, &inv_bits); |
| 4142 |
char* ref_allele = cur_refs[rec_idx]; |
| 4143 |
const uint32_t ref_allele_slen = strlen(ref_allele); |
| 4144 |
allele_remap[rec_idx * read_max_allele_ct] = 0; |
| 4145 |
for (uintptr_t ulii = 1; ulii != known_ref_ct; ++ulii) { |
| 4146 |
rec_idx = BitIter0(is_pr_bitarr, &rec_idx_base, &inv_bits); |
| 4147 |
allele_remap[rec_idx * read_max_allele_ct] = 0; |
| 4148 |
char* cur_ref = cur_refs[rec_idx]; |
| 4149 |
if (unlikely(!strequal_unsafe(cur_ref, ref_allele, ref_allele_slen))) { |
| 4150 |
logputs("\n"); |
| 4151 |
logerrprintfww("Error: Conflicting REF alleles for variant '%s' at %s:%u.\n", cur_variant_id, pmcp->chr_buf, pmcp->cur_bp); |
| 4152 |
return kPglRetInconsistentInput; |
| 4153 |
} |
| 4154 |
} |
| 4155 |
merged_alleles[0] = ref_allele; |
| 4156 |
HtableAddNondup(ref_allele, ref_allele_slen, htable_size, 0, merged_alleles_htable); |
| 4157 |
++merged_allele_ct; |
| 4158 |
} else { |
| 4159 |
is_pr = 1; |
| 4160 |
if (is_pr_ptr) { |
| 4161 |
*is_pr_ptr = 1; |
| 4162 |
} |
| 4163 |
} |
| 4164 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4165 |
char* allele_iter = cur_refs[rec_idx]; |
| 4166 |
uint32_t allele_idx = 0; |
| 4167 |
if (!IsSet(is_pr_bitarr, rec_idx)) { |
| 4168 |
allele_idx = 1; |
| 4169 |
allele_iter = &(strnul(allele_iter)[1]); |
| 4170 |
} |
| 4171 |
const uint32_t allele_ct = allele_cts[rec_idx]; |
| 4172 |
AlleleCode* cur_allele_remap = &(allele_remap[rec_idx * read_max_allele_ct]); |
| 4173 |
for (; allele_idx != allele_ct; ++allele_idx) { |
| 4174 |
const uint32_t cur_allele_slen = strlen(allele_iter); |
| 4175 |
uint32_t merged_allele_idx; |
| 4176 |
if ((allele_iter[0] != '.') || (cur_allele_slen != 1)) { |
| 4177 |
merged_allele_idx = IdHtableAdd(allele_iter, merged_alleles, cur_allele_slen, htable_size, merged_allele_ct, merged_alleles_htable); |
| 4178 |
if (merged_allele_idx == UINT32_MAX) { |
| 4179 |
merged_alleles[merged_allele_ct] = allele_iter; |
| 4180 |
merged_allele_idx = merged_allele_ct; |
| 4181 |
++merged_allele_ct; |
| 4182 |
if (merged_allele_ct == allele_ct_limit) { |
| 4183 |
// Too many alleles. |
| 4184 |
if (unlikely(allele_ct_limit == kPglMaxAlleleCt + 1)) { |
| 4185 |
logputs("\n"); |
| 4186 |
logerrprintfww("Error: Too many alleles for variant '%s' at %s:%u. (This " PROG_NAME_STR " build is limited to " PGL_MAX_ALLELE_CT_STR ".)\n", cur_variant_id, pmcp->chr_buf, pmcp->cur_bp); |
| 4187 |
return kPglRetNotYetSupported; |
| 4188 |
} |
| 4189 |
if (tmp_status & 1) { |
| 4190 |
*allele_ct_ptr = 0; |
| 4191 |
return kPglRetSuccess; |
| 4192 |
} |
| 4193 |
// Write tombstone. |
| 4194 |
*allele_ct_ptr = allele_ct_limit; |
| 4195 |
cswritep = strcpyax(cswritep, merged_alleles[0], '\t'); |
| 4196 |
for (uint32_t aidx = 1; aidx != allele_ct_limit; ++aidx) { |
| 4197 |
cswritep = strcpyax(cswritep, merged_alleles[aidx], ','); |
| 4198 |
} |
| 4199 |
cswritep[-1] = '\t'; |
| 4200 |
cswritep = strcpya_k(cswritep, ".\t.\t.\t0" EOLN_STR); |
| 4201 |
*cur_line_blenp = cswritep - pmcp->cswritep; |
| 4202 |
if (unlikely(Cswrite(&pmcp->css, &cswritep))) { |
| 4203 |
return kPglRetWriteFail; |
| 4204 |
} |
| 4205 |
pmcp->cswritep = cswritep; |
| 4206 |
return kPglRetSuccess; |
| 4207 |
} |
| 4208 |
} |
| 4209 |
} else { |
| 4210 |
if (unlikely(allele_ct != 2)) { |
| 4211 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4212 |
const uint32_t file_idx = cur_record->secondary_key >> 32; |
| 4213 |
const uint32_t variant_uidx = S_CAST(uint32_t, cur_record->secondary_key); |
| 4214 |
logputs("\n"); |
| 4215 |
logerrprintfww("Error: Missing allele in multiallelic variant on line %" PRIuPTR " of %s.\n", pmcp->line_idx_body_starts[file_idx] + variant_uidx, pmcp->fnames[file_idx]); |
| 4216 |
return kPglRetMalformedInput; |
| 4217 |
} |
| 4218 |
merged_allele_idx = kMissingAlleleCode; |
| 4219 |
} |
| 4220 |
cur_allele_remap[allele_idx] = merged_allele_idx; |
| 4221 |
allele_iter = &(allele_iter[cur_allele_slen + 1]); |
| 4222 |
} |
| 4223 |
} |
| 4224 |
// When merging .ped-derived datasets, it's possible for *all* alleles to |
| 4225 |
// be missing. |
| 4226 |
merged_info_allele_ct = merged_allele_ct; |
| 4227 |
for (; merged_allele_ct < 2; ++merged_allele_ct) { |
| 4228 |
merged_alleles[merged_allele_ct] = &(g_one_char_strs[92]); |
| 4229 |
} |
| 4230 |
cswritep = strcpyax(cswritep, merged_alleles[0], '\t'); |
| 4231 |
for (uint32_t aidx = 1; aidx != merged_allele_ct; ++aidx) { |
| 4232 |
cswritep = strcpyax(cswritep, merged_alleles[aidx], ','); |
| 4233 |
} |
| 4234 |
--cswritep; |
| 4235 |
*allele_ct_ptr = merged_allele_ct; |
| 4236 |
} |
| 4237 |
if (pmcp->write_qual) { |
| 4238 |
const MergeQualMode merge_qual_mode = pmcp->merge_qual_mode; |
| 4239 |
*cswritep++ = '\t'; |
| 4240 |
if ((merge_qual_mode == kMergeQualModeFirst) || (merge_qual_mode == kMergeQualModeNmFirst)) { |
| 4241 |
uintptr_t rec_idx = 0; |
| 4242 |
for (; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4243 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4244 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4245 |
char* tmp_variant_id = cur_record->variant_id; |
| 4246 |
const uint32_t qual_start = other_field_offsets[2]; |
| 4247 |
const uint32_t qual_blen = other_field_offsets[3] - qual_start; |
| 4248 |
if (qual_blen) { |
| 4249 |
if ((!((qual_blen == 2) && (tmp_variant_id[qual_start] == '.'))) || (merge_qual_mode == kMergeQualModeFirst)) { |
| 4250 |
cswritep = memcpya(cswritep, &(tmp_variant_id[qual_start]), qual_blen - 1); |
| 4251 |
break; |
| 4252 |
} |
| 4253 |
} |
| 4254 |
} |
| 4255 |
if (rec_idx == merge_rec_ct) { |
| 4256 |
*cswritep++ = '.'; |
| 4257 |
} |
| 4258 |
} else { |
| 4259 |
char** cur_qual_strs = pmcp->cur_fields_buf; |
| 4260 |
uintptr_t nm_qual_ct = 0; |
| 4261 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4262 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4263 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4264 |
char* tmp_variant_id = cur_record->variant_id; |
| 4265 |
const uint32_t qual_start = other_field_offsets[2]; |
| 4266 |
const uint32_t qual_blen = other_field_offsets[3] - qual_start; |
| 4267 |
if (qual_blen && (!((qual_blen == 2) && (tmp_variant_id[qual_start] == '.')))) { |
| 4268 |
cur_qual_strs[nm_qual_ct] = &(tmp_variant_id[qual_start]); |
| 4269 |
++nm_qual_ct; |
| 4270 |
} |
| 4271 |
} |
| 4272 |
if ((!nm_qual_ct) || ((merge_qual_mode == kMergeQualModeMin) && (nm_qual_ct != merge_rec_ct))) { |
| 4273 |
*cswritep++ = '.'; |
| 4274 |
} else if (nm_qual_ct == 1) { |
| 4275 |
cswritep = strcpya(cswritep, cur_qual_strs[0]); |
| 4276 |
} else { |
| 4277 |
// Must parse and compare QUAL values. |
| 4278 |
float main_qual = 0.0; |
| 4279 |
uintptr_t nm_rec_idx = 0; |
| 4280 |
for (; nm_rec_idx != nm_qual_ct; ++nm_rec_idx) { |
| 4281 |
float cur_qual; |
| 4282 |
if (unlikely(ScanFloat(cur_qual_strs[nm_rec_idx], &cur_qual))) { |
| 4283 |
// Note that we only validate QUAL when we have to. |
| 4284 |
|
| 4285 |
// Yes, line number/filename would be better, but to get those |
| 4286 |
// we'd need to determine the original variant index from the |
| 4287 |
// nonmissing index, which isn't really worth the trouble here. |
| 4288 |
logputs("\n"); |
| 4289 |
logerrprintfww("Error: Invalid QUAL value for variant '%s' at %s:%u.\n", cur_variant_id, pmcp->chr_buf, pmcp->cur_bp); |
| 4290 |
return kPglRetMalformedInput; |
| 4291 |
} |
| 4292 |
if (!nm_rec_idx) { |
| 4293 |
main_qual = cur_qual; |
| 4294 |
continue; |
| 4295 |
} |
| 4296 |
if (merge_qual_mode == kMergeQualModeMin) { |
| 4297 |
if (cur_qual < main_qual) { |
| 4298 |
main_qual = cur_qual; |
| 4299 |
} |
| 4300 |
} else if (cur_qual != main_qual) { |
| 4301 |
break; |
| 4302 |
} |
| 4303 |
} |
| 4304 |
if (nm_rec_idx == nm_qual_ct) { |
| 4305 |
cswritep = ftoa_g(main_qual, cswritep); |
| 4306 |
} else { |
| 4307 |
*cswritep++ = '.'; |
| 4308 |
} |
| 4309 |
} |
| 4310 |
} |
| 4311 |
} |
| 4312 |
if (pmcp->write_filter) { |
| 4313 |
const MergeFilterMode merge_filter_mode = pmcp->merge_filter_mode; |
| 4314 |
*cswritep++ = '\t'; |
| 4315 |
if ((merge_filter_mode == kMergeFilterModeFirst) || (merge_filter_mode == kMergeFilterModeNmFirst)) { |
| 4316 |
uintptr_t rec_idx = 0; |
| 4317 |
for (; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4318 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4319 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4320 |
char* tmp_variant_id = cur_record->variant_id; |
| 4321 |
const uint32_t filter_start = other_field_offsets[3]; |
| 4322 |
const uint32_t filter_blen = other_field_offsets[4] - filter_start; |
| 4323 |
if (filter_blen) { |
| 4324 |
if ((!((filter_blen == 2) && (tmp_variant_id[filter_start] == '.'))) || (merge_filter_mode == kMergeFilterModeFirst)) { |
| 4325 |
cswritep = memcpya(cswritep, &(tmp_variant_id[filter_start]), filter_blen - 1); |
| 4326 |
break; |
| 4327 |
} |
| 4328 |
} |
| 4329 |
} |
| 4330 |
if (rec_idx == merge_rec_ct) { |
| 4331 |
*cswritep++ = '.'; |
| 4332 |
} |
| 4333 |
} else { |
| 4334 |
// First pass: count number of tokens in non-PASS entries so we can |
| 4335 |
// size the hash table properly, distinguish between PASS and missing |
| 4336 |
// if there are no non-PASS entries. |
| 4337 |
char** cur_filter_strs = pmcp->cur_fields_buf; |
| 4338 |
uintptr_t nm_merge_rec_ct = 0; |
| 4339 |
uintptr_t nonpass_subtoken_ct = 0; |
| 4340 |
uint32_t pass_exists = 0; |
| 4341 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4342 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4343 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4344 |
char* tmp_variant_id = cur_record->variant_id; |
| 4345 |
const uint32_t filter_start = other_field_offsets[3]; |
| 4346 |
const uint32_t filter_blen = other_field_offsets[4] - filter_start; |
| 4347 |
if (filter_blen && (!((filter_blen == 2) && (tmp_variant_id[filter_start] == '.')))) { |
| 4348 |
char* filter_str = &(tmp_variant_id[filter_start]); |
| 4349 |
// bugfix (7 Jan 2023) |
| 4350 |
if ((filter_blen == 5) && memequal_sk(filter_str, "PASS")) { |
| 4351 |
pass_exists = 1; |
| 4352 |
} else { |
| 4353 |
nonpass_subtoken_ct += 1 + CountByte(filter_str, ';', filter_blen - 1); |
| 4354 |
cur_filter_strs[nm_merge_rec_ct] = filter_str; |
| 4355 |
++nm_merge_rec_ct; |
| 4356 |
} |
| 4357 |
} |
| 4358 |
} |
| 4359 |
if (!nm_merge_rec_ct) { |
| 4360 |
if (pass_exists) { |
| 4361 |
cswritep = strcpya_k(cswritep, "PASS"); |
| 4362 |
} else { |
| 4363 |
*cswritep++ = '.'; |
| 4364 |
} |
| 4365 |
} else if (nm_merge_rec_ct == 1) { |
| 4366 |
cswritep = strcpya(cswritep, cur_filter_strs[0]); |
| 4367 |
} else { |
| 4368 |
const uint32_t htable_size = GetHtableMinSize(MINV(nonpass_subtoken_ct + 1, kMaxFilterCt)); |
| 4369 |
uint32_t* filter_htable = pmcp->tmp_htable; |
| 4370 |
SetAllU32Arr(htable_size, filter_htable); |
| 4371 |
const char** subtokens = pmcp->tmp_strs; |
| 4372 |
subtokens[0] = "PASS"; |
| 4373 |
HtableAddNondup(subtokens[0], strlen("PASS"), htable_size, 0, filter_htable); |
| 4374 |
uint32_t cur_filter_ct = 1; |
| 4375 |
|
| 4376 |
const uintptr_t first_loop_stop = (merge_filter_mode == kMergeFilterModeNmMatch)? 1 : nm_merge_rec_ct; |
| 4377 |
for (uintptr_t nm_rec_idx = 0; nm_rec_idx != first_loop_stop; ++nm_rec_idx) { |
| 4378 |
char* filter_subtoken_iter = cur_filter_strs[nm_rec_idx]; |
| 4379 |
while (1) { |
| 4380 |
char* subtoken_end = strchrnul(filter_subtoken_iter, ';'); |
| 4381 |
const uint32_t is_last = (*subtoken_end == '\0'); |
| 4382 |
if (!is_last) { |
| 4383 |
*subtoken_end = '\0'; |
| 4384 |
} |
| 4385 |
if (IdHtableAdd(filter_subtoken_iter, subtokens, subtoken_end - filter_subtoken_iter, htable_size, cur_filter_ct, filter_htable) == UINT32_MAX) { |
| 4386 |
if (unlikely(cur_filter_ct == kMaxFilterCt + 1)) { |
| 4387 |
logputs("\n"); |
| 4388 |
logerrprintfww("Error: Too many distinct FILTERs for variant '%s' at %s:%u. (This " PROG_NAME_STR " build is limited to " MAX_FILTER_CT_STR ".)\n", cur_variant_id, pmcp->chr_buf, pmcp->cur_bp); |
| 4389 |
return kPglRetNotYetSupported; |
| 4390 |
} |
| 4391 |
subtokens[cur_filter_ct] = filter_subtoken_iter; |
| 4392 |
++cur_filter_ct; |
| 4393 |
} |
| 4394 |
if (is_last) { |
| 4395 |
break; |
| 4396 |
} |
| 4397 |
filter_subtoken_iter = &(subtoken_end[1]); |
| 4398 |
} |
| 4399 |
} |
| 4400 |
uint32_t mismatch_found = 0; |
| 4401 |
if (merge_filter_mode == kMergeFilterModeNmMatch) { |
| 4402 |
uintptr_t* filter_set = pmcp->filter_set; |
| 4403 |
const uint32_t filter_ctl = BitCtToWordCt(cur_filter_ct); |
| 4404 |
for (uintptr_t nm_rec_idx = 1; nm_rec_idx != nm_merge_rec_ct; ++nm_rec_idx) { |
| 4405 |
filter_set[0] = 1; |
| 4406 |
ZeroWArr(filter_ctl - 1, &(filter_set[1])); |
| 4407 |
char* filter_subtoken_iter = cur_filter_strs[nm_rec_idx]; |
| 4408 |
while (1) { |
| 4409 |
char* subtoken_end = strchrnul(filter_subtoken_iter, ';'); |
| 4410 |
const uint32_t is_last = (*subtoken_end == '\0'); |
| 4411 |
if (!is_last) { |
| 4412 |
*subtoken_end = '\0'; |
| 4413 |
} |
| 4414 |
const uint32_t filter_idx = IdHtableFind(filter_subtoken_iter, subtokens, filter_htable, subtoken_end - filter_subtoken_iter, htable_size); |
| 4415 |
if (filter_idx == UINT32_MAX) { |
| 4416 |
mismatch_found = 1; |
| 4417 |
break; |
| 4418 |
} |
| 4419 |
SetBit(filter_idx, filter_set); |
| 4420 |
if (is_last) { |
| 4421 |
break; |
| 4422 |
} |
| 4423 |
filter_subtoken_iter = &(subtoken_end[1]); |
| 4424 |
} |
| 4425 |
if (mismatch_found) { |
| 4426 |
break; |
| 4427 |
} |
| 4428 |
if (PopcountWords(filter_set, filter_ctl) != cur_filter_ct) { |
| 4429 |
mismatch_found = 1; |
| 4430 |
break; |
| 4431 |
} |
| 4432 |
} |
| 4433 |
} |
| 4434 |
if (!mismatch_found) { |
| 4435 |
if (unlikely((subtokens[1][0] == '\0') && (cur_filter_ct == 2))) { |
| 4436 |
// We usually don't explicitly check for this type of malformed |
| 4437 |
// input, but if the empty string is the *only* non-PASS FILTER |
| 4438 |
// key, we must error out since we'd otherwise generate an |
| 4439 |
// invalid .pvar. |
| 4440 |
logputs("\n"); |
| 4441 |
logerrprintfww("Error: Length-0 FILTER key present for variant '%s' at %s:%u.\n", cur_variant_id, pmcp->chr_buf, pmcp->cur_bp); |
| 4442 |
return kPglRetMalformedInput; |
| 4443 |
} |
| 4444 |
for (uint32_t uii = 1; uii != cur_filter_ct; ++uii) { |
| 4445 |
cswritep = strcpyax(cswritep, subtokens[uii], ';'); |
| 4446 |
} |
| 4447 |
--cswritep; |
| 4448 |
} |
| 4449 |
} |
| 4450 |
} |
| 4451 |
} |
| 4452 |
if (pmcp->write_info) { |
| 4453 |
*cswritep++ = '\t'; |
| 4454 |
// Lots of overlap with RenderTmpInfoFromSingleUnsorted(). |
| 4455 |
const char* const* info_keys = pmcp->info_keys; |
| 4456 |
const uint32_t* info_keys_htable = pmcp->info_keys_htable; |
| 4457 |
const uint32_t info_key_ct = pmcp->info_key_ct; |
| 4458 |
const uint32_t info_keys_htable_size = pmcp->info_keys_htable_size; |
| 4459 |
const uint32_t info_key_ctl = BitCtToWordCt(info_key_ct); |
| 4460 |
const char* info_missing_str = pmcp->info_missing_str; |
| 4461 |
uintptr_t* info_field_set = pmcp->info_field_set; |
| 4462 |
ZeroWArr(info_key_ctl, info_field_set); |
| 4463 |
char** basic_info_fields = pmcp->basic_info_fields; |
| 4464 |
char*** ar_info_fields = pmcp->ar_info_fields; |
| 4465 |
uint32_t* read_info_field_order_iter = (pmcp->merge_info_sort == kSortNone)? pmcp->read_info_field_order : nullptr; |
| 4466 |
const MergeInfoCmMode merge_info_mode = pmcp->merge_info_mode; |
| 4467 |
char* locked_missing_semicolon_str; |
| 4468 |
char* locked_missing_comma_str; |
| 4469 |
if (tmp_status == 1) { |
| 4470 |
locked_missing_semicolon_str = pmcp->missing_semicolon_str; |
| 4471 |
locked_missing_comma_str = pmcp->missing_comma_str; |
| 4472 |
} else { |
| 4473 |
locked_missing_semicolon_str = pmcp->locked_missing_semicolon_str; |
| 4474 |
locked_missing_comma_str = pmcp->locked_missing_comma_str; |
| 4475 |
} |
| 4476 |
uintptr_t rec_idx = 0; |
| 4477 |
for (; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4478 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4479 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4480 |
char* tmp_variant_id = cur_record->variant_id; |
| 4481 |
const uint32_t info_start = other_field_offsets[4]; |
| 4482 |
const uint32_t info_blen = other_field_offsets[5] - info_start; |
| 4483 |
if ((!info_blen) || ((info_blen == 2) && (tmp_variant_id[info_start] == '.'))) { |
| 4484 |
continue; |
| 4485 |
} |
| 4486 |
char* read_info_iter = &(tmp_variant_id[info_start]); |
| 4487 |
char* read_info_end = &(read_info_iter[info_blen]); |
| 4488 |
read_info_end[-1] = ';'; |
| 4489 |
|
| 4490 |
uint32_t read_allele_ct = allele_cts[rec_idx]; |
| 4491 |
AlleleCode* cur_allele_remap = &(allele_remap[rec_idx * read_max_allele_ct]); |
| 4492 |
if (read_allele_ct == 2) { |
| 4493 |
if (cur_allele_remap[0] == kMissingAlleleCode) { |
| 4494 |
read_allele_ct = 0; |
| 4495 |
} else if (cur_allele_remap[1] == kMissingAlleleCode) { |
| 4496 |
read_allele_ct = 1; |
| 4497 |
} |
| 4498 |
} |
| 4499 |
|
| 4500 |
do { |
| 4501 |
char* key_end = S_CAST(char*, rawmemchr2(read_info_iter, '=', ';')); |
| 4502 |
const uint32_t key_slen = key_end - read_info_iter; |
| 4503 |
const uint32_t kidx = IdHtableFindNnt(read_info_iter, info_keys, info_keys_htable, key_slen, info_keys_htable_size); |
| 4504 |
if (kidx == UINT32_MAX) { |
| 4505 |
// Skip this key. This can happen on e.g. a header conflict. |
| 4506 |
if (*key_end != ';') { |
| 4507 |
key_end = AdvToDelim(&(key_end[1]), ';'); |
| 4508 |
} |
| 4509 |
read_info_iter = &(key_end[1]); |
| 4510 |
continue; |
| 4511 |
} |
| 4512 |
// possible todo: error out on duplicated INFO key in a single |
| 4513 |
// input variant, like we already do in |
| 4514 |
// RenderTmpInfoFromSingleUnsorted(). |
| 4515 |
const int32_t knum = const_container_of(info_keys[kidx], InfoVtype, key)->num; |
| 4516 |
if (unlikely((knum == 0) != (*key_end == ';'))) { |
| 4517 |
const uint32_t file_idx = cur_record->secondary_key >> 32; |
| 4518 |
const uint32_t variant_uidx = S_CAST(uint32_t, cur_record->secondary_key); |
| 4519 |
logputs("\n"); |
| 4520 |
logerrprintfww("Error: Line %" PRIuPTR " of %s has a malformed INFO field (%s immediate ';').\n", pmcp->line_idx_body_starts[file_idx] + variant_uidx, pmcp->fnames[file_idx], (knum != 0)? "non-flag key followed by" : "flag key followed by '=' instead of"); |
| 4521 |
// InconsistentInput instead of MalformedInput error code since |
| 4522 |
// this may be caused by inconsistent headers across files |
| 4523 |
return kPglRetInconsistentInput; |
| 4524 |
} |
| 4525 |
if (!IsInfoVtypeARSkip(knum)) { |
| 4526 |
// Treat payload as a single string, including '=' and ';'. Do not |
| 4527 |
// null-terminate, semicolon is enough. |
| 4528 |
if (knum == 0) { |
| 4529 |
if (!IsSet(info_field_set, kidx)) { |
| 4530 |
SetBit(kidx, info_field_set); |
| 4531 |
basic_info_fields[kidx] = key_end; |
| 4532 |
if (read_info_field_order_iter) { |
| 4533 |
*read_info_field_order_iter++ = kidx; |
| 4534 |
} |
| 4535 |
} |
| 4536 |
read_info_iter = &(key_end[1]); |
| 4537 |
} else { |
| 4538 |
char* value_end = AdvToDelim(&(key_end[1]), ';'); |
| 4539 |
if (!IsSet(info_field_set, kidx)) { |
| 4540 |
SetBit(kidx, info_field_set); |
| 4541 |
if (read_info_field_order_iter) { |
| 4542 |
*read_info_field_order_iter++ = kidx; |
| 4543 |
} |
| 4544 |
if (merge_info_mode == kMergeInfoCmModeFirst) { |
| 4545 |
basic_info_fields[kidx] = key_end; |
| 4546 |
} else { |
| 4547 |
const uint32_t value_slen = value_end - key_end; |
| 4548 |
basic_info_fields[kidx] = nullptr; |
| 4549 |
if (knum <= 1) { |
| 4550 |
// Regular missing string is "=." |
| 4551 |
if ((key_end[1] != '.') || (value_slen != 2)) { |
| 4552 |
basic_info_fields[kidx] = key_end; |
| 4553 |
} |
| 4554 |
} else { |
| 4555 |
// Missing string looks like "=.,.,.", where number of dots |
| 4556 |
// is knum. |
| 4557 |
if ((value_slen != S_CAST(uint32_t, knum) * 2) || (!memequal(key_end, info_missing_str, value_slen))) { |
| 4558 |
basic_info_fields[kidx] = key_end; |
| 4559 |
} |
| 4560 |
} |
| 4561 |
} |
| 4562 |
} else if (merge_info_mode != kMergeInfoCmModeFirst) { |
| 4563 |
uint32_t is_nonmissing = 0; |
| 4564 |
// Locked-missing string is "==" (or "=." when we don't need to |
| 4565 |
// generate a temporary .pvar). This is the only way for |
| 4566 |
// basic_info_fields[kidx] == locked_missing_semicolon_str to |
| 4567 |
// be true. |
| 4568 |
const uint32_t value_slen = value_end - key_end; |
| 4569 |
if ((!basic_info_fields[kidx]) || ((merge_info_mode == kMergeInfoCmModeNmMatch) && (!memequal_k(basic_info_fields[kidx], locked_missing_semicolon_str, 3)))) { |
| 4570 |
if (knum <= 1) { |
| 4571 |
is_nonmissing = (key_end[1] != '.') || (value_slen != 2); |
| 4572 |
} else { |
| 4573 |
is_nonmissing = (value_slen != S_CAST(uint32_t, knum) * 2) || (!memequal(key_end, info_missing_str, value_slen)); |
| 4574 |
} |
| 4575 |
} |
| 4576 |
if (is_nonmissing) { |
| 4577 |
if (!basic_info_fields[kidx]) { |
| 4578 |
basic_info_fields[kidx] = key_end; |
| 4579 |
} else { |
| 4580 |
// set to locked-missing if unequal |
| 4581 |
if (!memequal(key_end, basic_info_fields[kidx], value_slen + 1)) { |
| 4582 |
// This may need to be postprocessed in the knum>1 case. |
| 4583 |
basic_info_fields[kidx] = locked_missing_semicolon_str; |
| 4584 |
} |
| 4585 |
} |
| 4586 |
} |
| 4587 |
} |
| 4588 |
read_info_iter = &(value_end[1]); |
| 4589 |
} |
| 4590 |
} else { |
| 4591 |
// Treat per-allele payloads separately. |
| 4592 |
const uint32_t first_aidx = knum - kInfoVtypeR; |
| 4593 |
if (unlikely(first_aidx >= read_allele_ct)) { |
| 4594 |
const uint32_t file_idx = cur_record->secondary_key >> 32; |
| 4595 |
const uint32_t variant_uidx = S_CAST(uint32_t, cur_record->secondary_key); |
| 4596 |
logputs("\n"); |
| 4597 |
logerrprintfww("Error: Invalid INFO key '%s' on line %" PRIuPTR " of %s (this variant has no %s allele, and key has Number=%c).\n", info_keys[kidx], pmcp->line_idx_body_starts[file_idx] + variant_uidx, pmcp->fnames[file_idx], read_allele_ct? "ALT" : "REF", first_aidx? 'A' : 'R'); |
| 4598 |
return kPglRetInconsistentInput; |
| 4599 |
} |
| 4600 |
char** cur_ar_info_fields = ar_info_fields[kidx]; |
| 4601 |
const uint32_t subfield_ct = merged_info_allele_ct - first_aidx; |
| 4602 |
if (!IsSet(info_field_set, kidx)) { |
| 4603 |
SetBit(kidx, info_field_set); |
| 4604 |
ZeroPtrArr(subfield_ct, cur_ar_info_fields); |
| 4605 |
if (read_info_field_order_iter) { |
| 4606 |
*read_info_field_order_iter++ = kidx; |
| 4607 |
} |
| 4608 |
} |
| 4609 |
read_info_iter = &(key_end[1]); |
| 4610 |
char* value_end = AdvToDelim(read_info_iter, ';'); |
| 4611 |
if (unlikely(CountByte(read_info_iter, ',', value_end - read_info_iter) != read_allele_ct - first_aidx - 1)) { |
| 4612 |
const uint32_t file_idx = cur_record->secondary_key >> 32; |
| 4613 |
const uint32_t variant_uidx = S_CAST(uint32_t, cur_record->secondary_key); |
| 4614 |
logputs("\n"); |
| 4615 |
logerrprintfww("Error: Invalid INFO entry for key '%s' on line %" PRIuPTR " of %s (incorrect number of values).\n", info_keys[kidx], pmcp->line_idx_body_starts[file_idx] + variant_uidx, pmcp->fnames[file_idx]); |
| 4616 |
return kPglRetInconsistentInput; |
| 4617 |
} |
| 4618 |
*value_end = ','; |
| 4619 |
uint32_t read_aidx = first_aidx; |
| 4620 |
if (merge_info_mode == kMergeInfoCmModeNmFirst) { |
| 4621 |
do { |
| 4622 |
const uint32_t write_aidx = cur_allele_remap[read_aidx] - first_aidx; |
| 4623 |
if ((!cur_ar_info_fields[write_aidx]) && (!memequal_sk(read_info_iter, ".,"))) { |
| 4624 |
cur_ar_info_fields[write_aidx] = read_info_iter; |
| 4625 |
} |
| 4626 |
read_info_iter = AdvPastDelim(read_info_iter, ','); |
| 4627 |
++read_aidx; |
| 4628 |
} while (read_aidx != read_allele_ct); |
| 4629 |
} else if (merge_info_mode == kMergeInfoCmModeFirst) { |
| 4630 |
do { |
| 4631 |
const uint32_t write_aidx = cur_allele_remap[read_aidx] - first_aidx; |
| 4632 |
cur_ar_info_fields[write_aidx] = read_info_iter; |
| 4633 |
read_info_iter = AdvPastDelim(read_info_iter, ','); |
| 4634 |
++read_aidx; |
| 4635 |
} while (read_aidx != read_allele_ct); |
| 4636 |
} else { |
| 4637 |
// NmMatch |
| 4638 |
do { |
| 4639 |
const uint32_t write_aidx = cur_allele_remap[read_aidx] - first_aidx; |
| 4640 |
char* next_subtoken_start = AdvPastDelim(read_info_iter, ','); |
| 4641 |
if (!memequal_sk(read_info_iter, ".,")) { |
| 4642 |
if (!cur_ar_info_fields[write_aidx]) { |
| 4643 |
cur_ar_info_fields[write_aidx] = read_info_iter; |
| 4644 |
} else if (!memequal_k(cur_ar_info_fields[write_aidx], locked_missing_comma_str, 2)) { |
| 4645 |
if (!memequal(read_info_iter, cur_ar_info_fields[write_aidx], next_subtoken_start - read_info_iter)) { |
| 4646 |
cur_ar_info_fields[write_aidx] = locked_missing_comma_str; |
| 4647 |
} |
| 4648 |
} |
| 4649 |
} |
| 4650 |
read_info_iter = next_subtoken_start; |
| 4651 |
++read_aidx; |
| 4652 |
} while (read_aidx != read_allele_ct); |
| 4653 |
} |
| 4654 |
} |
| 4655 |
} while (read_info_iter != read_info_end); |
| 4656 |
} |
| 4657 |
if (is_pr) { |
| 4658 |
const uint32_t pr_kidx = pmcp->pr_kidx; |
| 4659 |
if (!IsSet(info_field_set, pr_kidx)) { |
| 4660 |
SetBit(pr_kidx, info_field_set); |
| 4661 |
basic_info_fields[pr_kidx] = pmcp->pr_str; |
| 4662 |
if (read_info_field_order_iter) { |
| 4663 |
*read_info_field_order_iter++ = pr_kidx; |
| 4664 |
} |
| 4665 |
} |
| 4666 |
} |
| 4667 |
const uint32_t observed_key_ct = PopcountWords(info_field_set, info_key_ctl); |
| 4668 |
if (!observed_key_ct) { |
| 4669 |
*cswritep++ = '.'; |
| 4670 |
} else { |
| 4671 |
uint32_t* read_info_field_order = pmcp->read_info_field_order; |
| 4672 |
if (!read_info_field_order_iter) { |
| 4673 |
// We can now fill in the sorted field order. |
| 4674 |
uintptr_t kidx_base = 0; |
| 4675 |
uintptr_t cur_bits = info_field_set[0]; |
| 4676 |
for (uint32_t uii = 0; uii != observed_key_ct; ++uii) { |
| 4677 |
const uint32_t kidx = BitIter1(info_field_set, &kidx_base, &cur_bits); |
| 4678 |
read_info_field_order[uii] = kidx; |
| 4679 |
} |
| 4680 |
} |
| 4681 |
if ((merge_info_mode != kMergeInfoCmModeNmMatch) || (tmp_status != 3)) { |
| 4682 |
for (uint32_t uii = 0; uii != observed_key_ct; ++uii) { |
| 4683 |
const uint32_t kidx = read_info_field_order[uii]; |
| 4684 |
const char* cur_key = info_keys[kidx]; |
| 4685 |
const int32_t knum = const_container_of(cur_key, InfoVtype, key)->num; |
| 4686 |
cswritep = strcpya(cswritep, cur_key); |
| 4687 |
if (!IsInfoVtypeARSkip(knum)) { |
| 4688 |
char* v_start = basic_info_fields[kidx]; |
| 4689 |
if (!v_start) { |
| 4690 |
// Missing value. |
| 4691 |
if (knum <= 1) { |
| 4692 |
cswritep = strcpya_k(cswritep, "=.;"); |
| 4693 |
} else { |
| 4694 |
// Need to expand to "=.,.,.;" |
| 4695 |
*cswritep++ = '='; |
| 4696 |
cswritep = u16setsa(cswritep, 0x2c2e, knum); |
| 4697 |
cswritep[-1] = ';'; |
| 4698 |
} |
| 4699 |
} else if ((tmp_status != 1) || (knum <= 1) || (!memequal_k(v_start, locked_missing_semicolon_str, 3))) { |
| 4700 |
char* v_end = AdvPastDelim(v_start, ';'); |
| 4701 |
cswritep = memcpya(cswritep, v_start, v_end - v_start); |
| 4702 |
} else { |
| 4703 |
// Need to expand to "=.,.,.;" |
| 4704 |
*cswritep++ = '='; |
| 4705 |
cswritep = u16setsa(cswritep, 0x2c2e, knum); |
| 4706 |
cswritep[-1] = ';'; |
| 4707 |
} |
| 4708 |
} else { |
| 4709 |
*cswritep++ = '='; |
| 4710 |
char** cur_ar_info_fields = ar_info_fields[kidx]; |
| 4711 |
const uint32_t first_aidx = knum - kInfoVtypeR; |
| 4712 |
for (uint32_t write_idx = 0; write_idx != merged_info_allele_ct - first_aidx; ++write_idx) { |
| 4713 |
char* v_start = cur_ar_info_fields[write_idx]; |
| 4714 |
if (!v_start) { |
| 4715 |
cswritep = strcpya_k(cswritep, ".,"); |
| 4716 |
} else { |
| 4717 |
char* v_end = AdvPastDelim(v_start, ','); |
| 4718 |
cswritep = memcpya(cswritep, v_start, v_end - v_start); |
| 4719 |
} |
| 4720 |
} |
| 4721 |
cswritep[-1] = ';'; |
| 4722 |
} |
| 4723 |
} |
| 4724 |
} else { |
| 4725 |
// Necessary to convert all intermediate locked-missing |
| 4726 |
// representations to final form. |
| 4727 |
for (uint32_t uii = 0; uii != observed_key_ct; ++uii) { |
| 4728 |
const uint32_t kidx = read_info_field_order[uii]; |
| 4729 |
const char* cur_key = info_keys[kidx]; |
| 4730 |
const int32_t knum = const_container_of(cur_key, InfoVtype, key)->num; |
| 4731 |
cswritep = strcpya(cswritep, cur_key); |
| 4732 |
if (!IsInfoVtypeARSkip(knum)) { |
| 4733 |
char* v_start = basic_info_fields[kidx]; |
| 4734 |
if (v_start && (!memequal_k(v_start, locked_missing_semicolon_str, 3))) { |
| 4735 |
char* v_end = AdvPastDelim(v_start, ';'); |
| 4736 |
cswritep = memcpya(cswritep, v_start, v_end - v_start); |
| 4737 |
} else if (knum <= 1) { |
| 4738 |
cswritep = strcpya_k(cswritep, "=.;"); |
| 4739 |
} else { |
| 4740 |
*cswritep++ = '='; |
| 4741 |
cswritep = u16setsa(cswritep, 0x2c2e, knum); |
| 4742 |
cswritep[-1] = ';'; |
| 4743 |
} |
| 4744 |
} else { |
| 4745 |
*cswritep++ = '='; |
| 4746 |
char** cur_ar_info_fields = ar_info_fields[kidx]; |
| 4747 |
const uint32_t first_aidx = knum - kInfoVtypeR; |
| 4748 |
for (uint32_t write_idx = 0; write_idx != merged_info_allele_ct - first_aidx; ++write_idx) { |
| 4749 |
char* v_start = cur_ar_info_fields[write_idx]; |
| 4750 |
if (v_start && (!memequal_k(v_start, locked_missing_comma_str, 2))) { |
| 4751 |
char* v_end = AdvPastDelim(v_start, ','); |
| 4752 |
cswritep = memcpya(cswritep, v_start, v_end - v_start); |
| 4753 |
} else { |
| 4754 |
cswritep = strcpya_k(cswritep, ".,"); |
| 4755 |
} |
| 4756 |
} |
| 4757 |
cswritep[-1] = ';'; |
| 4758 |
} |
| 4759 |
} |
| 4760 |
} |
| 4761 |
--cswritep; |
| 4762 |
} |
| 4763 |
} |
| 4764 |
if (pmcp->write_cm) { |
| 4765 |
// Very similar to QUAL. Differences: |
| 4766 |
// - No 'min' option. |
| 4767 |
// - Double-precision float parsing required. |
| 4768 |
// - '0' is the missing value, not '.'. |
| 4769 |
const MergeInfoCmMode merge_cm_mode = pmcp->merge_cm_mode; |
| 4770 |
*cswritep++ = '\t'; |
| 4771 |
if ((merge_cm_mode == kMergeInfoCmModeFirst) || (merge_cm_mode == kMergeInfoCmModeNmFirst)) { |
| 4772 |
uintptr_t rec_idx = 0; |
| 4773 |
for (; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4774 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4775 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4776 |
char* tmp_variant_id = cur_record->variant_id; |
| 4777 |
char* cm_str = &(tmp_variant_id[other_field_offsets[5]]); |
| 4778 |
if (cm_str[0] != '\0') { |
| 4779 |
if ((!strequal_k_unsafe(cm_str, "0")) || (merge_cm_mode == kMergeInfoCmModeFirst)) { |
| 4780 |
cswritep = strcpya(cswritep, cm_str); |
| 4781 |
break; |
| 4782 |
} |
| 4783 |
} |
| 4784 |
} |
| 4785 |
if (rec_idx == merge_rec_ct) { |
| 4786 |
*cswritep++ = '0'; |
| 4787 |
} |
| 4788 |
} else { |
| 4789 |
char** cur_cm_strs = pmcp->cur_fields_buf; |
| 4790 |
uintptr_t nz_cm_ct = 0; |
| 4791 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 4792 |
SamePosPvarRecord* cur_record = same_id_records[rec_idx]; |
| 4793 |
const uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 4794 |
char* tmp_variant_id = cur_record->variant_id; |
| 4795 |
char* cm_str = &(tmp_variant_id[other_field_offsets[5]]); |
| 4796 |
if ((cm_str[0] != '\0') && (!strequal_k_unsafe(cm_str, "0"))) { |
| 4797 |
cur_cm_strs[nz_cm_ct] = cm_str; |
| 4798 |
++nz_cm_ct; |
| 4799 |
} |
| 4800 |
} |
| 4801 |
if (!nz_cm_ct) { |
| 4802 |
*cswritep++ = '0'; |
| 4803 |
} else if (nz_cm_ct == 1) { |
| 4804 |
cswritep = strcpya(cswritep, cur_cm_strs[0]); |
| 4805 |
} else { |
| 4806 |
// Parse and check equality of CM values. |
| 4807 |
double main_cm = 0.0; |
| 4808 |
uintptr_t nm_rec_idx = 0; |
| 4809 |
for (; nm_rec_idx != nz_cm_ct; ++nm_rec_idx) { |
| 4810 |
double cur_cm; |
| 4811 |
if (unlikely(!ScantokDouble(cur_cm_strs[nm_rec_idx], &cur_cm))) { |
| 4812 |
logputs("\n"); |
| 4813 |
logerrprintfww("Error: Invalid CM value for variant '%s' at %s:%u.\n", cur_variant_id, pmcp->chr_buf, pmcp->cur_bp); |
| 4814 |
return kPglRetMalformedInput; |
| 4815 |
} |
| 4816 |
if (!nm_rec_idx) { |
| 4817 |
main_cm = cur_cm; |
| 4818 |
continue; |
| 4819 |
} |
| 4820 |
if (cur_cm != main_cm) { |
| 4821 |
break; |
| 4822 |
} |
| 4823 |
} |
| 4824 |
if (nm_rec_idx == nz_cm_ct) { |
| 4825 |
cswritep = dtoa_g(main_cm, cswritep); |
| 4826 |
} else { |
| 4827 |
*cswritep++ = '.'; |
| 4828 |
} |
| 4829 |
} |
| 4830 |
} |
| 4831 |
} |
| 4832 |
} |
| 4833 |
AppendBinaryEoln(&cswritep); |
| 4834 |
*cur_line_blenp = cswritep - pmcp->cswritep; |
| 4835 |
if (unlikely(Cswrite(&pmcp->css, &cswritep))) { |
| 4836 |
return kPglRetWriteFail; |
| 4837 |
} |
| 4838 |
pmcp->cswritep = cswritep; |
| 4839 |
return kPglRetSuccess; |
| 4840 |
} |
| 4841 |
|
| 4842 |
// We don't want to crash in an uncontrolled manner if the .pgen contains an |
| 4843 |
// instance of an allele that the .pvar claims shouldn't exist. |
| 4844 |
// If normalize is true, this also flips the variant when it's REF that's |
| 4845 |
// missing in the .pvar. |
| 4846 |
PglErr ValidateBiallelicVariantWithMissingCode(const AlleleCode* cur_allele_remap, uint32_t sample_ct, uint32_t normalize, PgenVariant* pgvp) { |
| 4847 |
uintptr_t* genovec = pgvp->genovec; |
| 4848 |
ZeroTrailingNyps(sample_ct, genovec); |
| 4849 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 4850 |
GenoarrCountFreqsUnsafe(genovec, sample_ct, genocounts); |
| 4851 |
if (unlikely(genocounts[1] || (genocounts[0] && (cur_allele_remap[0] == kMissingAlleleCode)) || (genocounts[2] && (cur_allele_remap[1] == kMissingAlleleCode)) || pgvp->dosage_ct)) { |
| 4852 |
logputs("\n"); |
| 4853 |
logerrputs("Error: Missing allele in .pvar is present in the .pgen.\n"); |
| 4854 |
return kPglRetInconsistentInput; |
| 4855 |
} |
| 4856 |
if (normalize && ((cur_allele_remap[0] == 1) || (cur_allele_remap[1] == 0))) { |
| 4857 |
// only possible when [0] == missing |
| 4858 |
GenovecInvertUnsafe(sample_ct, genovec); |
| 4859 |
if (pgvp->phasepresent_ct) { |
| 4860 |
BitvecInvert(BitCtToWordCt(sample_ct), pgvp->phaseinfo); |
| 4861 |
} |
| 4862 |
if (pgvp->dosage_ct) { |
| 4863 |
BiallelicDosage16Invert(pgvp->dosage_ct, pgvp->dosage_main); |
| 4864 |
if (pgvp->dphase_ct) { |
| 4865 |
BiallelicDphase16Invert(pgvp->dphase_ct, pgvp->dphase_delta); |
| 4866 |
} |
| 4867 |
} |
| 4868 |
} |
| 4869 |
return kPglRetSuccess; |
| 4870 |
} |
| 4871 |
|
| 4872 |
void Update8bitDenseFromSparse(const uintptr_t* subset_mask, const void* __restrict src, uint32_t subset_size, void* __restrict dst) { |
| 4873 |
const unsigned char* src_uc = S_CAST(const unsigned char*, src); |
| 4874 |
unsigned char* dst_uc = S_CAST(unsigned char*, dst); |
| 4875 |
uintptr_t uidx_base = 0; |
| 4876 |
uintptr_t cur_bits = subset_mask[0]; |
| 4877 |
for (uint32_t uii = 0; uii != subset_size; ++uii) { |
| 4878 |
const uintptr_t cur_uidx = BitIter1(subset_mask, &uidx_base, &cur_bits); |
| 4879 |
dst_uc[cur_uidx] = src_uc[uii]; |
| 4880 |
} |
| 4881 |
} |
| 4882 |
|
| 4883 |
void Update16bitDenseFromSparse(const uintptr_t* subset_mask, const void* __restrict src, uint32_t subset_size, void* __restrict dst) { |
| 4884 |
const uint16_t* src_u16 = S_CAST(const uint16_t*, src); |
| 4885 |
uint16_t* dst_u16 = S_CAST(uint16_t*, dst); |
| 4886 |
uintptr_t uidx_base = 0; |
| 4887 |
uintptr_t cur_bits = subset_mask[0]; |
| 4888 |
for (uint32_t uii = 0; uii != subset_size; ++uii) { |
| 4889 |
const uintptr_t cur_uidx = BitIter1(subset_mask, &uidx_base, &cur_bits); |
| 4890 |
dst_u16[cur_uidx] = src_u16[uii]; |
| 4891 |
} |
| 4892 |
} |
| 4893 |
|
| 4894 |
void CopyAndPermuteBitarr(const uintptr_t* __restrict read_bitarr, const uint32_t* __restrict old_sample_idx_to_new, uint32_t write_sample_ctl, uint32_t read_ct, uintptr_t* __restrict write_bitarr) { |
| 4895 |
ZeroWArr(write_sample_ctl, write_bitarr); |
| 4896 |
uintptr_t read_uidx_base = 0; |
| 4897 |
uintptr_t cur_bits = read_bitarr[0]; |
| 4898 |
for (uint32_t read_idx = 0; read_idx != read_ct; ++read_idx) { |
| 4899 |
const uint32_t read_uidx = BitIter1(read_bitarr, &read_uidx_base, &cur_bits); |
| 4900 |
const uint32_t write_sample_idx = old_sample_idx_to_new[read_uidx]; |
| 4901 |
SetBit(write_sample_idx, write_bitarr); |
| 4902 |
} |
| 4903 |
} |
| 4904 |
|
| 4905 |
// Subset of CopyAndPermute8bit(). |
| 4906 |
void PermuteUpdate8bitDenseFromSparse(const uintptr_t* __restrict src_subset, const void* __restrict src_vals, const uint32_t* __restrict old_sample_idx_to_new, uint32_t sample_ct, uint32_t val_ct, uintptr_t* __restrict dst_subset, void* __restrict dst_vals) { |
| 4907 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 4908 |
ZeroWArr(sample_ctl, dst_subset); |
| 4909 |
const unsigned char* src_vals_uc = S_CAST(const unsigned char*, src_vals); |
| 4910 |
unsigned char* dst_vals_uc = S_CAST(unsigned char*, dst_vals); |
| 4911 |
|
| 4912 |
uintptr_t cur_bits = src_subset[0]; |
| 4913 |
uintptr_t old_sample_idx_base = 0; |
| 4914 |
for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) { |
| 4915 |
const uint32_t old_sample_idx = BitIter1(src_subset, &old_sample_idx_base, &cur_bits); |
| 4916 |
const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx]; |
| 4917 |
SetBit(new_sample_idx, dst_subset); |
| 4918 |
dst_vals_uc[new_sample_idx] = src_vals_uc[old_val_idx]; |
| 4919 |
} |
| 4920 |
} |
| 4921 |
|
| 4922 |
// ok for dst_subset to be nullptr. |
| 4923 |
void PermuteUpdate16bitDenseFromSparse(const uintptr_t* __restrict src_subset, const void* __restrict src_vals, const uint32_t* __restrict old_sample_idx_to_new, uint32_t sample_ct, uint32_t val_ct, uintptr_t* __restrict dst_subset, void* __restrict dst_vals) { |
| 4924 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 4925 |
ZeroWArr(sample_ctl, dst_subset); |
| 4926 |
const uint16_t* src_vals_u16 = S_CAST(const uint16_t*, src_vals); |
| 4927 |
uint16_t* dst_vals_u16 = S_CAST(uint16_t*, dst_vals); |
| 4928 |
|
| 4929 |
uintptr_t cur_bits = src_subset[0]; |
| 4930 |
uintptr_t old_sample_idx_base = 0; |
| 4931 |
if (dst_subset) { |
| 4932 |
for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) { |
| 4933 |
const uint32_t old_sample_idx = BitIter1(src_subset, &old_sample_idx_base, &cur_bits); |
| 4934 |
const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx]; |
| 4935 |
SetBit(new_sample_idx, dst_subset); |
| 4936 |
dst_vals_u16[new_sample_idx] = src_vals_u16[old_val_idx]; |
| 4937 |
} |
| 4938 |
} else { |
| 4939 |
for (uint32_t old_val_idx = 0; old_val_idx != val_ct; ++old_val_idx) { |
| 4940 |
const uint32_t old_sample_idx = BitIter1(src_subset, &old_sample_idx_base, &cur_bits); |
| 4941 |
const uint32_t new_sample_idx = old_sample_idx_to_new[old_sample_idx]; |
| 4942 |
dst_vals_u16[new_sample_idx] = src_vals_u16[old_val_idx]; |
| 4943 |
} |
| 4944 |
} |
| 4945 |
} |
| 4946 |
|
| 4947 |
void PermuteUpdateGenovec(const uintptr_t* __restrict r_genovec, const uint32_t* __restrict clobber_sample_idx_to_new, uint32_t clobber_sample_ct, uintptr_t* __restrict genovec) { |
| 4948 |
// possible todo: add most-common-geno optimization when clobber_sample_ct is |
| 4949 |
// sufficiently large. That should be unlikely, though. |
| 4950 |
const uint32_t read_genoword_ct_m1 = (clobber_sample_ct - 1) / kBitsPerWordD2; |
| 4951 |
for (uint32_t widx = 0; ; ++widx) { |
| 4952 |
// We know the existing genovec bits at the positions we're clobbering are |
| 4953 |
// all set, so xor operations make sense here. |
| 4954 |
uintptr_t geno_word_xor; |
| 4955 |
if (widx >= read_genoword_ct_m1) { |
| 4956 |
if (widx > read_genoword_ct_m1) { |
| 4957 |
break; |
| 4958 |
} |
| 4959 |
geno_word_xor = bzhi_max(~(r_genovec[widx]), 2 * ModNz(clobber_sample_ct, kBitsPerWordD2)); |
| 4960 |
} else { |
| 4961 |
geno_word_xor = ~(r_genovec[widx]); |
| 4962 |
} |
| 4963 |
if (!geno_word_xor) { |
| 4964 |
continue; |
| 4965 |
} |
| 4966 |
const uint32_t* cur_old_sample_idx_to_new = &(clobber_sample_idx_to_new[widx * kBitsPerWordD2]); |
| 4967 |
// possible todo: branch between this and tighter loop, depending on number |
| 4968 |
// of missing genotypes |
| 4969 |
do { |
| 4970 |
const uint32_t bit_read_shift_ct = ctzw(geno_word_xor) & (kBitsPerWord - 2); |
| 4971 |
const uintptr_t cur_geno_xor = (geno_word_xor >> bit_read_shift_ct) & 3; |
| 4972 |
const uint32_t new_sample_idx = cur_old_sample_idx_to_new[bit_read_shift_ct / 2]; |
| 4973 |
const uint32_t new_word_idx = new_sample_idx / kBitsPerWordD2; |
| 4974 |
const uint32_t bit_write_shift_ct = 2 * (new_sample_idx % kBitsPerWordD2); |
| 4975 |
genovec[new_word_idx] ^= cur_geno_xor << bit_write_shift_ct; |
| 4976 |
geno_word_xor &= (~(3 * k1LU)) << bit_read_shift_ct; |
| 4977 |
} while (geno_word_xor); |
| 4978 |
} |
| 4979 |
} |
| 4980 |
|
| 4981 |
void PermuteUpdateHphase(const uintptr_t* __restrict r_phasepresent, const uintptr_t* __restrict r_phaseinfo, const uint32_t* __restrict old_sample_idx_to_new, uint32_t phasepresent_ct, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo) { |
| 4982 |
uintptr_t read_widx = 0; |
| 4983 |
uintptr_t cur_bits = r_phasepresent[0]; |
| 4984 |
for (uint32_t phasepresent_idx = 0; phasepresent_idx != phasepresent_ct; ++phasepresent_idx) { |
| 4985 |
const uintptr_t read_sample_idx_lowbit_idx = BitIter1x(r_phasepresent, &read_widx, &cur_bits); |
| 4986 |
const uintptr_t is_phaseinfo = (r_phaseinfo[read_widx] >> read_sample_idx_lowbit_idx) & 1; |
| 4987 |
const uint32_t read_sample_idx = read_widx * kBitsPerWord + read_sample_idx_lowbit_idx; |
| 4988 |
const uint32_t write_sample_idx = old_sample_idx_to_new[read_sample_idx]; |
| 4989 |
const uint32_t write_widx = write_sample_idx / kBitsPerWord; |
| 4990 |
const uintptr_t write_bit = k1LU << (write_sample_idx % kBitsPerWord); |
| 4991 |
phasepresent[write_widx] |= write_bit; |
| 4992 |
phaseinfo[write_widx] |= write_bit & (-is_phaseinfo); |
| 4993 |
} |
| 4994 |
} |
| 4995 |
|
| 4996 |
void CopyAndPermuteHphase(const uintptr_t* __restrict read_phasepresent, const uintptr_t* __restrict read_phaseinfo, const uint32_t* __restrict old_sample_idx_to_new, uint32_t write_sample_ctl, uint32_t phasepresent_ct, uintptr_t* __restrict write_phasepresent, uintptr_t* __restrict write_phaseinfo) { |
| 4997 |
ZeroWArr(write_sample_ctl, write_phasepresent); |
| 4998 |
ZeroWArr(write_sample_ctl, write_phaseinfo); |
| 4999 |
PermuteUpdateHphase(read_phasepresent, read_phaseinfo, old_sample_idx_to_new, phasepresent_ct, write_phasepresent, write_phaseinfo); |
| 5000 |
} |
| 5001 |
|
| 5002 |
void Compare8bitDense(const uintptr_t* __restrict present1, const void* __restrict dense1, const uintptr_t* __restrict present2, const void* __restrict dense2, uint32_t word_ct, uintptr_t* __restrict compare_mask) { |
| 5003 |
const unsigned char* dense1_uc = S_CAST(const unsigned char*, dense1); |
| 5004 |
const unsigned char* dense2_uc = S_CAST(const unsigned char*, dense2); |
| 5005 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5006 |
uintptr_t compare_word = compare_mask[widx]; |
| 5007 |
if (!compare_word) { |
| 5008 |
continue; |
| 5009 |
} |
| 5010 |
const uintptr_t present1_word = present1[widx]; |
| 5011 |
const uintptr_t present2_word = present2[widx]; |
| 5012 |
uintptr_t byte_compare_word = compare_word & present1_word & present2_word; |
| 5013 |
compare_word &= ~(present1_word ^ present2_word); |
| 5014 |
if (byte_compare_word) { |
| 5015 |
// possible todo: when byte_compare_word has enough set bits, use |
| 5016 |
// movemask instead |
| 5017 |
const unsigned char* cur_dense1_uc = &(dense1_uc[widx * kBitsPerWord]); |
| 5018 |
const unsigned char* cur_dense2_uc = &(dense2_uc[widx * kBitsPerWord]); |
| 5019 |
do { |
| 5020 |
const uint32_t sample_idx_lowbits = ctzw(byte_compare_word); |
| 5021 |
if (cur_dense1_uc[sample_idx_lowbits] != cur_dense2_uc[sample_idx_lowbits]) { |
| 5022 |
// (byte_compare_word & (-byte_compare_word)) also isolates low bit |
| 5023 |
compare_word -= k1LU << sample_idx_lowbits; |
| 5024 |
} |
| 5025 |
byte_compare_word &= byte_compare_word - 1; |
| 5026 |
} while (byte_compare_word); |
| 5027 |
} |
| 5028 |
compare_mask[widx] = compare_word; |
| 5029 |
} |
| 5030 |
} |
| 5031 |
|
| 5032 |
void Compare16bitDense(const uintptr_t* __restrict present1, const void* __restrict dense1, const uintptr_t* __restrict present2, const void* __restrict dense2, uint32_t word_ct, uintptr_t* __restrict compare_mask) { |
| 5033 |
const uint16_t* dense1_u16 = S_CAST(const uint16_t*, dense1); |
| 5034 |
const uint16_t* dense2_u16 = S_CAST(const uint16_t*, dense2); |
| 5035 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5036 |
uintptr_t compare_word = compare_mask[widx]; |
| 5037 |
if (!compare_word) { |
| 5038 |
continue; |
| 5039 |
} |
| 5040 |
const uintptr_t present1_word = present1[widx]; |
| 5041 |
const uintptr_t present2_word = present2[widx]; |
| 5042 |
uintptr_t byte_compare_word = compare_word & present1_word & present2_word; |
| 5043 |
compare_word &= ~(present1_word ^ present2_word); |
| 5044 |
if (byte_compare_word) { |
| 5045 |
const uint16_t* cur_dense1_u16 = &(dense1_u16[widx * kBitsPerWord]); |
| 5046 |
const uint16_t* cur_dense2_u16 = &(dense2_u16[widx * kBitsPerWord]); |
| 5047 |
do { |
| 5048 |
const uint32_t sample_idx_lowbits = ctzw(byte_compare_word); |
| 5049 |
if (cur_dense1_u16[sample_idx_lowbits] != cur_dense2_u16[sample_idx_lowbits]) { |
| 5050 |
compare_word -= k1LU << sample_idx_lowbits; |
| 5051 |
} |
| 5052 |
byte_compare_word &= byte_compare_word - 1; |
| 5053 |
} while (byte_compare_word); |
| 5054 |
} |
| 5055 |
compare_mask[widx] = compare_word; |
| 5056 |
} |
| 5057 |
} |
| 5058 |
|
| 5059 |
void Update8bitDense(const uintptr_t* __restrict update_mask, const uintptr_t* __restrict src_present, const void* __restrict src_dense, uint32_t word_ct, uintptr_t* __restrict dst_present, void* __restrict dst_dense) { |
| 5060 |
const unsigned char* src_dense_uc = S_CAST(const unsigned char*, src_dense); |
| 5061 |
unsigned char* dst_dense_uc = S_CAST(unsigned char*, dst_dense); |
| 5062 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5063 |
const uintptr_t update_word = update_mask[widx]; |
| 5064 |
if (!update_word) { |
| 5065 |
continue; |
| 5066 |
} |
| 5067 |
uintptr_t src_present_word = src_present[widx] & update_word; |
| 5068 |
if (!src_present_word) { |
| 5069 |
continue; |
| 5070 |
} |
| 5071 |
dst_present[widx] |= src_present_word; |
| 5072 |
const unsigned char* cur_src_dense = &(src_dense_uc[widx * kBitsPerWord]); |
| 5073 |
unsigned char* cur_dst_dense = &(dst_dense_uc[widx * kBitsPerWord]); |
| 5074 |
do { |
| 5075 |
const uint32_t sample_idx_lowbits = ctzw(src_present_word); |
| 5076 |
cur_dst_dense[sample_idx_lowbits] = cur_src_dense[sample_idx_lowbits]; |
| 5077 |
src_present_word &= src_present_word - 1; |
| 5078 |
} while (src_present_word); |
| 5079 |
} |
| 5080 |
} |
| 5081 |
|
| 5082 |
void Update16bitDense(const uintptr_t* __restrict update_mask, const uintptr_t* __restrict src_present, const void* __restrict src_dense, uint32_t word_ct, uintptr_t* __restrict dst_present, void* __restrict dst_dense) { |
| 5083 |
const uint16_t* src_dense_u16 = S_CAST(const uint16_t*, src_dense); |
| 5084 |
uint16_t* dst_dense_u16 = S_CAST(uint16_t*, dst_dense); |
| 5085 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5086 |
const uintptr_t update_word = update_mask[widx]; |
| 5087 |
if (!update_word) { |
| 5088 |
continue; |
| 5089 |
} |
| 5090 |
uintptr_t src_present_word = src_present[widx] & update_word; |
| 5091 |
if (!src_present_word) { |
| 5092 |
continue; |
| 5093 |
} |
| 5094 |
dst_present[widx] |= src_present_word; |
| 5095 |
const uint16_t* cur_src_dense = &(src_dense_u16[widx * kBitsPerWord]); |
| 5096 |
uint16_t* cur_dst_dense = &(dst_dense_u16[widx * kBitsPerWord]); |
| 5097 |
do { |
| 5098 |
const uint32_t sample_idx_lowbits = ctzw(src_present_word); |
| 5099 |
cur_dst_dense[sample_idx_lowbits] = cur_src_dense[sample_idx_lowbits]; |
| 5100 |
src_present_word &= src_present_word - 1; |
| 5101 |
} while (src_present_word); |
| 5102 |
} |
| 5103 |
} |
| 5104 |
|
| 5105 |
typedef struct MergeReaderStruct { |
| 5106 |
PgenReader pgr; |
| 5107 |
uintptr_t* sample_include; |
| 5108 |
// yes, this breaks the standard "local variable only" usage rule; we don't |
| 5109 |
// want to clear the LD-cache on every single variant. Not dangerous here |
| 5110 |
// since we never change the sample-subset. |
| 5111 |
PgrSampleSubsetIndex pssi; |
| 5112 |
|
| 5113 |
uintptr_t* sample_span; |
| 5114 |
uint32_t* old_sample_idx_to_new; |
| 5115 |
uint32_t sample_idx_increasing; // =2 in simplest case |
| 5116 |
|
| 5117 |
uint32_t sample_ct; |
| 5118 |
} MergeReader; |
| 5119 |
|
| 5120 |
typedef struct MergeWriterStruct { |
| 5121 |
STPgenWriter spgw; |
| 5122 |
// Main write buffers. |
| 5123 |
// probable todo: define PgenVariant-based write functions, and replace these |
| 5124 |
// fields with a third PgenVariant buffer. |
| 5125 |
// todo: document which buffers must be allocated up to next vector boundary. |
| 5126 |
// Not urgent since we're allocating up to that point by default, but this |
| 5127 |
// would make it easier to patch in debug-allocator logic to test for |
| 5128 |
// out-of-bounds memory writes. |
| 5129 |
uintptr_t* genovec; |
| 5130 |
uintptr_t* patch_01_set; |
| 5131 |
AlleleCode* patch_01_vals; |
| 5132 |
uintptr_t* patch_10_set; |
| 5133 |
AlleleCode* patch_10_vals; |
| 5134 |
uintptr_t* phasepresent; |
| 5135 |
uintptr_t* phaseinfo; |
| 5136 |
uintptr_t* dosage_present; |
| 5137 |
uint16_t* dosage_main; |
| 5138 |
uintptr_t* dphase_present; |
| 5139 |
int16_t* dphase_delta; |
| 5140 |
|
| 5141 |
PgenVariant pgv_readbuf; |
| 5142 |
|
| 5143 |
uintptr_t* unlocked_set; |
| 5144 |
// "--merge-mode nm-match" only |
| 5145 |
uintptr_t* unlocked_missing_set; |
| 5146 |
|
| 5147 |
// "--merge-mode nm-match"-specific temporary buffers |
| 5148 |
uintptr_t* clobber_sample_span; |
| 5149 |
uintptr_t* unlocked_nonmissing_sample_span; |
| 5150 |
|
| 5151 |
// Buffers supporting efficient clobber when only some of the currently-read |
| 5152 |
// samples qualify. |
| 5153 |
uintptr_t* unlocked_sample_span; |
| 5154 |
uint32_t* clobber_sample_idx_to_new; |
| 5155 |
uintptr_t* mask_buf; |
| 5156 |
PgenVariant pgv_midbuf; |
| 5157 |
uintptr_t* phaseinfo_xor; |
| 5158 |
AlleleCode* wide_codes; |
| 5159 |
|
| 5160 |
MergeMode merge_mode; |
| 5161 |
} MergeWriter; |
| 5162 |
|
| 5163 |
PglErr MergePgenVariantNoTmpLocked(SamePosPvarRecord** same_id_records, const AlleleCode* master_allele_remap, uintptr_t merge_rec_ct, uint32_t write_allele_ct, uint32_t allele_remap_stride, MergeReader** mrp_arr, MergeWriter* mwp) { |
| 5164 |
PglErr reterr = kPglRetSuccess; |
| 5165 |
{ |
| 5166 |
STPgenWriter* spgwp = &(mwp->spgw); |
| 5167 |
PgenVariant* pgvp = &(mwp->pgv_readbuf); |
| 5168 |
const uint32_t write_sample_ct = SpgwGetSampleCt(spgwp); |
| 5169 |
const uint32_t write_sample_ctl = BitCtToWordCt(write_sample_ct); |
| 5170 |
|
| 5171 |
// Only used in multi-file case. |
| 5172 |
uint32_t hphase_exists = 0; |
| 5173 |
uint32_t dosage_exists = 0; |
| 5174 |
uint32_t dphase_exists = 0; |
| 5175 |
// "simple" = either non-allele-permuting, or {[0] = kMissingAlleleCode, |
| 5176 |
// [1] = 0}. |
| 5177 |
// (These are the only possibilities when merge_rec_ct == 1.) |
| 5178 |
uint32_t simple_first_allele_remap = 1; |
| 5179 |
if (merge_rec_ct > 1) { |
| 5180 |
const uint32_t read_allele_ct = same_id_records[0]->allele_ct; |
| 5181 |
for (uint32_t allele_idx = 0; allele_idx != read_allele_ct; ++allele_idx) { |
| 5182 |
if (master_allele_remap[allele_idx] != allele_idx) { |
| 5183 |
if (read_allele_ct == 2) { |
| 5184 |
// Check for permitted kMissingAlleleCode cases. |
| 5185 |
if (!allele_idx) { |
| 5186 |
if (((master_allele_remap[0] == kMissingAlleleCode) && ((master_allele_remap[1] <= 1) || (master_allele_remap[1] == kMissingAlleleCode))) || ((master_allele_remap[0] == 1) && (master_allele_remap[1] == kMissingAlleleCode))) { |
| 5187 |
break; |
| 5188 |
} |
| 5189 |
} else { |
| 5190 |
if (master_allele_remap[1] == kMissingAlleleCode) { |
| 5191 |
break; |
| 5192 |
} |
| 5193 |
} |
| 5194 |
} |
| 5195 |
simple_first_allele_remap = 0; |
| 5196 |
break; |
| 5197 |
} |
| 5198 |
} |
| 5199 |
uint32_t vrtype_or = 0; |
| 5200 |
for (uintptr_t rec_idx = 0; rec_idx != merge_rec_ct; ++rec_idx) { |
| 5201 |
const uint32_t file_idx = same_id_records[rec_idx]->secondary_key >> 32; |
| 5202 |
const uint32_t read_variant_uidx = S_CAST(uint32_t, same_id_records[0]->secondary_key); |
| 5203 |
MergeReader* cur_mrp = mrp_arr[file_idx]; |
| 5204 |
PgenReader* pgrp = &(cur_mrp->pgr); |
| 5205 |
vrtype_or |= PgrGetVrtype(pgrp, read_variant_uidx); |
| 5206 |
} |
| 5207 |
hphase_exists = (vrtype_or / 0x10) & 1; |
| 5208 |
dosage_exists = !!(vrtype_or & 0x60); |
| 5209 |
dphase_exists = (vrtype_or / 0x80) & 1; |
| 5210 |
assert((!dphase_exists) || dosage_exists); |
| 5211 |
if (dosage_exists && (write_allele_ct > 2)) { |
| 5212 |
logerrputs("Error: --pmerge[-list] multiallelic-variant dosage support is under development.\n"); |
| 5213 |
reterr = kPglRetNotYetSupported; |
| 5214 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5215 |
} |
| 5216 |
} |
| 5217 |
const MergeMode merge_mode = mwp->merge_mode; |
| 5218 |
if (simple_first_allele_remap) { |
| 5219 |
const uint32_t file_idx = same_id_records[0]->secondary_key >> 32; |
| 5220 |
const uint32_t read_variant_uidx = S_CAST(uint32_t, same_id_records[0]->secondary_key); |
| 5221 |
MergeReader* cur_mrp = mrp_arr[file_idx]; |
| 5222 |
const uint32_t read_sample_ct = cur_mrp->sample_ct; |
| 5223 |
const uint32_t read_allele_ct = same_id_records[0]->allele_ct; |
| 5224 |
PgenReader* pgrp = &(cur_mrp->pgr); |
| 5225 |
const uint32_t vrtype = PgrGetVrtype(pgrp, read_variant_uidx); |
| 5226 |
const uint32_t read_phase_present = !!(vrtype & 0x90); |
| 5227 |
const uint32_t read_dosage_present = !!(vrtype & 0x60); |
| 5228 |
const uintptr_t* sample_include = cur_mrp->sample_include; |
| 5229 |
if ((read_allele_ct == 2) && (!read_dosage_present)) { |
| 5230 |
pgvp->patch_01_ct = 0; |
| 5231 |
pgvp->patch_10_ct = 0; |
| 5232 |
pgvp->dosage_ct = 0; |
| 5233 |
if (!read_phase_present) { |
| 5234 |
pgvp->phasepresent_ct = 0; |
| 5235 |
reterr = PgrGet(sample_include, cur_mrp->pssi, read_sample_ct, read_variant_uidx, pgrp, pgvp->genovec); |
| 5236 |
} else { |
| 5237 |
reterr = PgrGetP(sample_include, cur_mrp->pssi, read_sample_ct, read_variant_uidx, pgrp, pgvp->genovec, pgvp->phasepresent, pgvp->phaseinfo, &pgvp->phasepresent_ct); |
| 5238 |
} |
| 5239 |
} else { |
| 5240 |
reterr = PgrGetMDp(sample_include, cur_mrp->pssi, read_sample_ct, read_variant_uidx, pgrp, pgvp); |
| 5241 |
} |
| 5242 |
if (unlikely(reterr)) { |
| 5243 |
PgenErrPrintNV(reterr, read_variant_uidx); |
| 5244 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5245 |
} |
| 5246 |
if ((master_allele_remap[0] == kMissingAlleleCode) || (master_allele_remap[1] == kMissingAlleleCode)) { |
| 5247 |
reterr = ValidateBiallelicVariantWithMissingCode(master_allele_remap, read_sample_ct, 1, pgvp); |
| 5248 |
if (unlikely(reterr)) { |
| 5249 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5250 |
} |
| 5251 |
} |
| 5252 |
uintptr_t* read_genovec = pgvp->genovec; |
| 5253 |
ZeroTrailingNyps(read_sample_ct, read_genovec); |
| 5254 |
const uint32_t sample_idx_increasing = cur_mrp->sample_idx_increasing; |
| 5255 |
const uint32_t write_biallelic = (!pgvp->patch_01_ct) && (!pgvp->patch_10_ct); |
| 5256 |
uint32_t unlocked_ct = 0; |
| 5257 |
if (sample_idx_increasing == 2) { |
| 5258 |
// read_sample_ct == write_sample_ct |
| 5259 |
if ((merge_rec_ct != 1) && (merge_mode != kMergeModeFirst)) { |
| 5260 |
// If there are any missing genotypes/dosages, those are still |
| 5261 |
// unlocked. |
| 5262 |
uintptr_t* missingness = (merge_mode == kMergeModeNmFirst)? mwp->unlocked_set : mwp->unlocked_missing_set; |
| 5263 |
GenoarrToMissingnessUnsafe(read_genovec, write_sample_ct, missingness); |
| 5264 |
if (pgvp->dosage_ct) { |
| 5265 |
BitvecInvmask(pgvp->dosage_present, write_sample_ctl, missingness); |
| 5266 |
} |
| 5267 |
if (merge_mode == kMergeModeNmFirst) { |
| 5268 |
unlocked_ct = PopcountWords(missingness, write_sample_ctl); |
| 5269 |
} else { |
| 5270 |
// kMergeModeNmMatch |
| 5271 |
SetAllBits(write_sample_ct, mwp->unlocked_set); |
| 5272 |
unlocked_ct = write_sample_ct; |
| 5273 |
} |
| 5274 |
} |
| 5275 |
if (unlocked_ct == 0) { |
| 5276 |
if (write_biallelic) { |
| 5277 |
// Simplest cases: write directly from pgvp, no need to use |
| 5278 |
// mwp.genovec, etc. |
| 5279 |
// We explicitly branch on phasepresent_ct since otherwise we'd |
| 5280 |
// need to pass phasepresent == nullptr. |
| 5281 |
if (pgvp->dosage_ct == 0) { |
| 5282 |
if (!pgvp->phasepresent_ct) { |
| 5283 |
reterr = SpgwAppendBiallelicGenovec(read_genovec, spgwp); |
| 5284 |
} else { |
| 5285 |
reterr = SpgwAppendBiallelicGenovecHphase(read_genovec, pgvp->phasepresent, pgvp->phaseinfo, spgwp); |
| 5286 |
} |
| 5287 |
} else { |
| 5288 |
if ((!pgvp->phasepresent_ct) && (!pgvp->dphase_ct)) { |
| 5289 |
reterr = SpgwAppendBiallelicGenovecDosage16(read_genovec, pgvp->dosage_present, pgvp->dosage_main, pgvp->dosage_ct, spgwp); |
| 5290 |
} else { |
| 5291 |
if (!pgvp->phasepresent_ct) { |
| 5292 |
ZeroWArr(write_sample_ctl, pgvp->phasepresent); |
| 5293 |
} |
| 5294 |
reterr = SpgwAppendBiallelicGenovecDphase16(read_genovec, pgvp->phasepresent, pgvp->phaseinfo, pgvp->dosage_present, pgvp->dphase_present, pgvp->dosage_main, pgvp->dphase_delta, pgvp->dosage_ct, pgvp->dphase_ct, spgwp); |
| 5295 |
} |
| 5296 |
} |
| 5297 |
} else { |
| 5298 |
// Multiallelic. |
| 5299 |
ZeroTrailingNyps(write_sample_ct, read_genovec); |
| 5300 |
assert(!pgvp->dosage_ct); // not yet supported |
| 5301 |
if (!pgvp->phasepresent_ct) { |
| 5302 |
reterr = SpgwAppendMultiallelicSparse(read_genovec, pgvp->patch_01_set, pgvp->patch_01_vals, pgvp->patch_10_set, pgvp->patch_10_vals, write_allele_ct, pgvp->patch_01_ct, pgvp->patch_10_ct, spgwp); |
| 5303 |
} else { |
| 5304 |
reterr = SpgwAppendMultiallelicGenovecHphase(read_genovec, pgvp->patch_01_set, pgvp->patch_01_vals, pgvp->patch_10_set, pgvp->patch_10_vals, pgvp->phasepresent, pgvp->phaseinfo, write_allele_ct, pgvp->patch_01_ct, pgvp->patch_10_ct, spgwp); |
| 5305 |
} |
| 5306 |
} |
| 5307 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5308 |
} |
| 5309 |
// Copy to write buffers. |
| 5310 |
// bugfix (2 Mar 2021): did not copy enough bytes here |
| 5311 |
const uint32_t write_sample_ctl2 = NypCtToWordCt(write_sample_ct); |
| 5312 |
memcpy(mwp->genovec, read_genovec, write_sample_ctl2 * sizeof(intptr_t)); |
| 5313 |
const uint32_t write_sample_ctb = write_sample_ctl * sizeof(intptr_t); |
| 5314 |
if (write_allele_ct > 2) { |
| 5315 |
if (pgvp->patch_01_ct) { |
| 5316 |
memcpy(mwp->patch_01_set, pgvp->patch_01_set, write_sample_ctb); |
| 5317 |
Update8bitDenseFromSparse(pgvp->patch_01_set, pgvp->patch_01_vals, pgvp->patch_01_ct, mwp->patch_01_vals); |
| 5318 |
} else { |
| 5319 |
ZeroWArr(write_sample_ctl, mwp->patch_01_set); |
| 5320 |
} |
| 5321 |
if (pgvp->patch_10_ct) { |
| 5322 |
memcpy(mwp->patch_10_set, pgvp->patch_10_set, write_sample_ctb); |
| 5323 |
Update16bitDenseFromSparse(pgvp->patch_10_set, pgvp->patch_10_vals, pgvp->patch_10_ct, mwp->patch_10_vals); |
| 5324 |
} else { |
| 5325 |
ZeroWArr(write_sample_ctl, mwp->patch_10_set); |
| 5326 |
} |
| 5327 |
} |
| 5328 |
if (hphase_exists || dphase_exists) { |
| 5329 |
if (pgvp->phasepresent_ct) { |
| 5330 |
memcpy(mwp->phasepresent, pgvp->phasepresent, write_sample_ctb); |
| 5331 |
memcpy(mwp->phaseinfo, pgvp->phaseinfo, write_sample_ctb); |
| 5332 |
} else { |
| 5333 |
ZeroWArr(write_sample_ctl, mwp->phasepresent); |
| 5334 |
} |
| 5335 |
} |
| 5336 |
if (dosage_exists) { |
| 5337 |
if (pgvp->dosage_ct) { |
| 5338 |
memcpy(mwp->dosage_present, pgvp->dosage_present, write_sample_ctb); |
| 5339 |
Update16bitDenseFromSparse(pgvp->dosage_present, pgvp->dosage_main, pgvp->dosage_ct, mwp->dosage_main); |
| 5340 |
} else { |
| 5341 |
ZeroWArr(write_sample_ctl, mwp->dosage_present); |
| 5342 |
} |
| 5343 |
if (dphase_exists) { |
| 5344 |
if (pgvp->dphase_ct) { |
| 5345 |
memcpy(mwp->dphase_present, pgvp->dphase_present, write_sample_ctb); |
| 5346 |
Update16bitDenseFromSparse(pgvp->dphase_present, pgvp->dphase_delta, pgvp->dosage_ct, mwp->dphase_delta); |
| 5347 |
} else { |
| 5348 |
ZeroWArr(write_sample_ctl, mwp->dphase_present); |
| 5349 |
} |
| 5350 |
} |
| 5351 |
} |
| 5352 |
} else { |
| 5353 |
// Necessary to expand and/or permute. |
| 5354 |
// We'd rather not iterate over every single genotype. So we exploit |
| 5355 |
// sparsity, efficiently prefilling all relevant genotypes in the |
| 5356 |
// output array with the most common value, and then patching only the |
| 5357 |
// exceptions. |
| 5358 |
|
| 5359 |
// (strictly speaking, we don't need to recompute genocounts if we |
| 5360 |
// already did so in the kMissingAlleleCode cases above, but that event |
| 5361 |
// should be rare enough that it's not worth deduplicating.) |
| 5362 |
const uintptr_t most_common_geno_word = MostCommonGenoUnsafe(read_genovec, read_sample_ct) * kMask5555; |
| 5363 |
|
| 5364 |
const uint32_t* old_sample_idx_to_new = cur_mrp->old_sample_idx_to_new; |
| 5365 |
const uintptr_t* sample_span = cur_mrp->sample_span; |
| 5366 |
// This part is very similar to GenovecPermute(). (We could just call |
| 5367 |
// it in the read_sample_ct == write_sample_ct case.) |
| 5368 |
uintptr_t* genovec = mwp->genovec; |
| 5369 |
const uint32_t write_sample_ctl2 = NypCtToWordCt(write_sample_ct); |
| 5370 |
if (read_sample_ct == write_sample_ct) { |
| 5371 |
for (uint32_t hwidx = 0; hwidx != write_sample_ctl2; ++hwidx) { |
| 5372 |
genovec[hwidx] = most_common_geno_word; |
| 5373 |
} |
| 5374 |
} else { |
| 5375 |
const Halfword* sample_span_hw = DowncastKWToHW(sample_span); |
| 5376 |
for (uint32_t hwidx = 0; hwidx != write_sample_ctl2; ++hwidx) { |
| 5377 |
// Initialize each genotype outside the single source's sample-span |
| 5378 |
// to missing (both bits set). |
| 5379 |
const Halfword inv_sample_span_hw = ~sample_span_hw[hwidx]; |
| 5380 |
genovec[hwidx] = most_common_geno_word | (UnpackHalfwordToWord(inv_sample_span_hw) * 3); |
| 5381 |
} |
| 5382 |
} |
| 5383 |
ZeroTrailingNyps(write_sample_ct, genovec); |
| 5384 |
const uint32_t read_genoword_ct_m1 = (read_sample_ct - 1) / kBitsPerWordD2; |
| 5385 |
for (uint32_t widx = 0; ; ++widx) { |
| 5386 |
uintptr_t geno_word_xor; |
| 5387 |
if (widx >= read_genoword_ct_m1) { |
| 5388 |
if (widx > read_genoword_ct_m1) { |
| 5389 |
break; |
| 5390 |
} |
| 5391 |
geno_word_xor = bzhi_max(most_common_geno_word ^ read_genovec[widx], 2 * ModNz(read_sample_ct, kBitsPerWordD2)); |
| 5392 |
} else { |
| 5393 |
geno_word_xor = most_common_geno_word ^ read_genovec[widx]; |
| 5394 |
} |
| 5395 |
if (!geno_word_xor) { |
| 5396 |
continue; |
| 5397 |
} |
| 5398 |
const uint32_t* cur_old_sample_idx_to_new = &(old_sample_idx_to_new[widx * kBitsPerWordD2]); |
| 5399 |
do { |
| 5400 |
const uint32_t bit_read_shift_ct = ctzw(geno_word_xor) & (kBitsPerWord - 2); |
| 5401 |
const uintptr_t cur_geno_xor = (geno_word_xor >> bit_read_shift_ct) & 3; |
| 5402 |
const uint32_t new_sample_idx = cur_old_sample_idx_to_new[bit_read_shift_ct / 2]; |
| 5403 |
const uint32_t new_word_idx = new_sample_idx / kBitsPerWordD2; |
| 5404 |
const uint32_t bit_write_shift_ct = 2 * (new_sample_idx % kBitsPerWordD2); |
| 5405 |
// Value has been preset to most_common_geno, so if we xor it with |
| 5406 |
// (most_common_geno ^ actual_geno), the result is actual_geno. |
| 5407 |
genovec[new_word_idx] ^= cur_geno_xor << bit_write_shift_ct; |
| 5408 |
geno_word_xor &= (~(3 * k1LU)) << bit_read_shift_ct; |
| 5409 |
} while (geno_word_xor); |
| 5410 |
} |
| 5411 |
// Resolve dosage_present first, so we know unlocked_ct status and can |
| 5412 |
// select correct (sparse vs. dense) conversion for patch_01_vals, |
| 5413 |
// patch_10_vals, dosage_main, and dphase_delta. |
| 5414 |
const uint32_t dosage_ct = pgvp->dosage_ct; |
| 5415 |
if (dosage_ct) { |
| 5416 |
assert(write_biallelic); |
| 5417 |
if (sample_idx_increasing) { |
| 5418 |
ExpandBytearr(pgvp->dosage_present, sample_span, write_sample_ctl, read_sample_ct, 0, mwp->dosage_present); |
| 5419 |
} else { |
| 5420 |
CopyAndPermuteBitarr(pgvp->dosage_present, old_sample_idx_to_new, write_sample_ctl, dosage_ct, mwp->dosage_present); |
| 5421 |
} |
| 5422 |
} |
| 5423 |
if (merge_rec_ct != 1) { |
| 5424 |
if (merge_mode == kMergeModeFirst) { |
| 5425 |
if (read_sample_ct != write_sample_ct) { |
| 5426 |
unlocked_ct = write_sample_ct - read_sample_ct; |
| 5427 |
BitvecInvertCopy(sample_span, write_sample_ctl, mwp->unlocked_set); |
| 5428 |
ZeroTrailingBits(write_sample_ct, mwp->unlocked_set); |
| 5429 |
} |
| 5430 |
} else { |
| 5431 |
// If there are any missing genotypes/dosages, those are still |
| 5432 |
// unlocked. |
| 5433 |
uintptr_t* missingness = (merge_mode == kMergeModeNmFirst)? mwp->unlocked_set : mwp->unlocked_missing_set; |
| 5434 |
GenoarrToMissingnessUnsafe(mwp->genovec, write_sample_ct, missingness); |
| 5435 |
if (dosage_ct) { |
| 5436 |
BitvecInvmask(mwp->dosage_present, write_sample_ctl, missingness); |
| 5437 |
} |
| 5438 |
if (merge_mode == kMergeModeNmFirst) { |
| 5439 |
unlocked_ct = PopcountWords(missingness, write_sample_ctl); |
| 5440 |
} else { |
| 5441 |
// kMergeModeNmMatch |
| 5442 |
SetAllBits(write_sample_ct, mwp->unlocked_set); |
| 5443 |
unlocked_ct = write_sample_ct; |
| 5444 |
} |
| 5445 |
} |
| 5446 |
} |
| 5447 |
uint32_t patch_01_ct = 0; |
| 5448 |
uint32_t patch_10_ct = 0; |
| 5449 |
if (!write_biallelic) { |
| 5450 |
patch_01_ct = pgvp->patch_01_ct; |
| 5451 |
if (patch_01_ct) { |
| 5452 |
if (sample_idx_increasing) { |
| 5453 |
ExpandBytearr(pgvp->patch_01_set, sample_span, write_sample_ctl, read_sample_ct, 0, mwp->patch_01_set); |
| 5454 |
if (!unlocked_ct) { |
| 5455 |
memcpy(mwp->patch_01_vals, pgvp->patch_01_vals, patch_01_ct); |
| 5456 |
} else { |
| 5457 |
Update8bitDenseFromSparse(mwp->patch_01_set, pgvp->patch_01_vals, pgvp->patch_01_ct, mwp->patch_01_vals); |
| 5458 |
} |
| 5459 |
} else { |
| 5460 |
if (!unlocked_ct) { |
| 5461 |
CopyAndPermute8bit(nullptr, pgvp->patch_01_set, pgvp->patch_01_vals, old_sample_idx_to_new, read_sample_ct, patch_01_ct, mwp->patch_01_set, mwp->patch_01_vals); |
| 5462 |
} else { |
| 5463 |
PermuteUpdate8bitDenseFromSparse(pgvp->patch_01_set, pgvp->patch_01_vals, old_sample_idx_to_new, read_sample_ct, patch_01_ct, mwp->patch_01_set, mwp->patch_01_vals); |
| 5464 |
} |
| 5465 |
} |
| 5466 |
} |
| 5467 |
patch_10_ct = pgvp->patch_10_ct; |
| 5468 |
if (patch_10_ct) { |
| 5469 |
if (sample_idx_increasing) { |
| 5470 |
ExpandBytearr(pgvp->patch_10_set, sample_span, write_sample_ctl, read_sample_ct, 0, mwp->patch_10_set); |
| 5471 |
if (!unlocked_ct) { |
| 5472 |
memcpy(mwp->patch_10_vals, pgvp->patch_10_vals, patch_10_ct * 2); |
| 5473 |
} else { |
| 5474 |
Update16bitDenseFromSparse(mwp->patch_10_set, pgvp->patch_10_vals, patch_10_ct, mwp->patch_10_vals); |
| 5475 |
} |
| 5476 |
} else { |
| 5477 |
if (!unlocked_ct) { |
| 5478 |
CopyAndPermute16bit(nullptr, pgvp->patch_10_set, pgvp->patch_10_vals, old_sample_idx_to_new, read_sample_ct, patch_10_ct, mwp->patch_10_set, mwp->patch_10_vals); |
| 5479 |
} else { |
| 5480 |
PermuteUpdate16bitDenseFromSparse(pgvp->patch_10_set, pgvp->patch_10_vals, old_sample_idx_to_new, read_sample_ct, patch_10_ct, mwp->patch_10_set, mwp->patch_10_vals); |
| 5481 |
} |
| 5482 |
} |
| 5483 |
} |
| 5484 |
} |
| 5485 |
const uint32_t phasepresent_ct = pgvp->phasepresent_ct; |
| 5486 |
if (phasepresent_ct) { |
| 5487 |
if (sample_idx_increasing) { |
| 5488 |
ExpandBytearr(pgvp->phasepresent, sample_span, write_sample_ctl, read_sample_ct, 0, mwp->phasepresent); |
| 5489 |
ExpandBytearr(pgvp->phaseinfo, sample_span, write_sample_ctl, read_sample_ct, 0, mwp->phaseinfo); |
| 5490 |
} else { |
| 5491 |
CopyAndPermuteHphase(pgvp->phasepresent, pgvp->phaseinfo, old_sample_idx_to_new, write_sample_ctl, phasepresent_ct, mwp->phasepresent, mwp->phaseinfo); |
| 5492 |
} |
| 5493 |
} |
| 5494 |
uint32_t dphase_ct = 0; |
| 5495 |
if (dosage_ct) { |
| 5496 |
assert(write_biallelic); |
| 5497 |
// mwp->dosage_present already correct |
| 5498 |
if (sample_idx_increasing) { |
| 5499 |
if (!unlocked_ct) { |
| 5500 |
memcpy(mwp->dosage_main, pgvp->dosage_main, dosage_ct * 2); |
| 5501 |
} else { |
| 5502 |
Update16bitDenseFromSparse(mwp->dosage_present, pgvp->dosage_main, dosage_ct, mwp->dosage_main); |
| 5503 |
} |
| 5504 |
} else { |
| 5505 |
if (!unlocked_ct) { |
| 5506 |
CopyAndPermute16bit(nullptr, pgvp->dosage_present, pgvp->dosage_main, old_sample_idx_to_new, read_sample_ct, dosage_ct, mwp->dosage_present, mwp->dosage_main); |
| 5507 |
} else { |
| 5508 |
PermuteUpdate16bitDenseFromSparse(pgvp->dosage_present, pgvp->dosage_main, old_sample_idx_to_new, read_sample_ct, dosage_ct, nullptr, mwp->dosage_main); |
| 5509 |
} |
| 5510 |
} |
| 5511 |
dphase_ct = pgvp->dphase_ct; |
| 5512 |
if (dphase_ct) { |
| 5513 |
if (sample_idx_increasing) { |
| 5514 |
ExpandBytearr(pgvp->dphase_present, sample_span, write_sample_ctl, read_sample_ct, 0, mwp->dphase_present); |
| 5515 |
if (!unlocked_ct) { |
| 5516 |
memcpy(mwp->dphase_delta, pgvp->dphase_delta, dphase_ct * 2); |
| 5517 |
} else { |
| 5518 |
Update16bitDenseFromSparse(mwp->dphase_present, pgvp->dphase_delta, dosage_ct, mwp->dphase_delta); |
| 5519 |
} |
| 5520 |
} else { |
| 5521 |
if (!unlocked_ct) { |
| 5522 |
CopyAndPermute16bit(nullptr, pgvp->dphase_present, pgvp->dphase_delta, old_sample_idx_to_new, read_sample_ct, dphase_ct, mwp->dphase_present, mwp->dphase_delta); |
| 5523 |
} else { |
| 5524 |
PermuteUpdate16bitDenseFromSparse(pgvp->dphase_present, pgvp->dphase_delta, old_sample_idx_to_new, read_sample_ct, dphase_ct, mwp->dphase_present, mwp->dphase_delta); |
| 5525 |
} |
| 5526 |
} |
| 5527 |
} |
| 5528 |
} |
| 5529 |
if (unlocked_ct == 0) { |
| 5530 |
if (!dosage_ct) { |
| 5531 |
if (write_biallelic) { |
| 5532 |
if (!phasepresent_ct) { |
| 5533 |
reterr = SpgwAppendBiallelicGenovec(genovec, spgwp); |
| 5534 |
} else { |
| 5535 |
reterr = SpgwAppendBiallelicGenovecHphase(genovec, mwp->phasepresent, mwp->phaseinfo, spgwp); |
| 5536 |
} |
| 5537 |
} else { |
| 5538 |
if (!phasepresent_ct) { |
| 5539 |
reterr = SpgwAppendMultiallelicSparse(genovec, mwp->patch_01_set, mwp->patch_01_vals, mwp->patch_10_set, mwp->patch_10_vals, write_allele_ct, patch_01_ct, patch_10_ct, spgwp); |
| 5540 |
} else { |
| 5541 |
reterr = SpgwAppendMultiallelicGenovecHphase(genovec, mwp->patch_01_set, mwp->patch_01_vals, mwp->patch_10_set, mwp->patch_10_vals, mwp->phasepresent, mwp->phaseinfo, write_allele_ct, patch_01_ct, patch_10_ct, spgwp); |
| 5542 |
} |
| 5543 |
} |
| 5544 |
} else { |
| 5545 |
if ((!phasepresent_ct) && (!dphase_ct)) { |
| 5546 |
reterr = SpgwAppendBiallelicGenovecDosage16(genovec, mwp->dosage_present, mwp->dosage_main, dosage_ct, spgwp); |
| 5547 |
} else { |
| 5548 |
if (!phasepresent_ct) { |
| 5549 |
ZeroWArr(write_sample_ctl, mwp->phasepresent); |
| 5550 |
} |
| 5551 |
reterr = SpgwAppendBiallelicGenovecDphase16(genovec, mwp->phasepresent, mwp->phaseinfo, mwp->dosage_present, mwp->dphase_present, mwp->dosage_main, mwp->dphase_delta, dosage_ct, dphase_ct, spgwp); |
| 5552 |
} |
| 5553 |
} |
| 5554 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5555 |
} |
| 5556 |
// unlocked_ct > 0, some write buffers already copied to. Only need |
| 5557 |
// to initialize write buffers which don't happen to have been touched |
| 5558 |
// by processing of the first file. |
| 5559 |
if (write_allele_ct > 2) { |
| 5560 |
if (!patch_01_ct) { |
| 5561 |
ZeroWArr(write_sample_ctl, mwp->patch_01_set); |
| 5562 |
} |
| 5563 |
if (!patch_10_ct) { |
| 5564 |
ZeroWArr(write_sample_ctl, mwp->patch_10_set); |
| 5565 |
} |
| 5566 |
} |
| 5567 |
if ((hphase_exists || dphase_exists) && (!phasepresent_ct)) { |
| 5568 |
ZeroWArr(write_sample_ctl, mwp->phasepresent); |
| 5569 |
} |
| 5570 |
if (dosage_exists && (!dosage_ct)) { |
| 5571 |
ZeroWArr(write_sample_ctl, mwp->dosage_present); |
| 5572 |
if (dphase_exists && (!dphase_ct)) { |
| 5573 |
ZeroWArr(write_sample_ctl, mwp->dphase_present); |
| 5574 |
} |
| 5575 |
} |
| 5576 |
} |
| 5577 |
} else { |
| 5578 |
SetAllBits(write_sample_ct * 2, mwp->genovec); |
| 5579 |
SetAllBits(write_sample_ct, mwp->unlocked_set); |
| 5580 |
if (mwp->unlocked_missing_set) { |
| 5581 |
SetAllBits(write_sample_ct, mwp->unlocked_missing_set); |
| 5582 |
} |
| 5583 |
if (write_allele_ct > 2) { |
| 5584 |
ZeroWArr(write_sample_ctl, mwp->patch_01_set); |
| 5585 |
ZeroWArr(write_sample_ctl, mwp->patch_10_set); |
| 5586 |
} |
| 5587 |
if (hphase_exists || dphase_exists) { |
| 5588 |
ZeroWArr(write_sample_ctl, mwp->phasepresent); |
| 5589 |
} |
| 5590 |
if (dosage_exists) { |
| 5591 |
ZeroWArr(write_sample_ctl, mwp->dosage_present); |
| 5592 |
if (dphase_exists) { |
| 5593 |
ZeroWArr(write_sample_ctl, mwp->dphase_present); |
| 5594 |
} |
| 5595 |
} |
| 5596 |
} |
| 5597 |
|
| 5598 |
// Multiple variants to merge. |
| 5599 |
// 1. Missing-initialize write buffer and unlocked_set. Dense |
| 5600 |
// representation of patch_01_vals, patch_10_vals, dosage_vals, and |
| 5601 |
// dphase_deltas. |
| 5602 |
// 2. Incrementally update write buffer. |
| 5603 |
// 3. Pack patch_01_vals, patch_10_vals, dosage_vals, and dphase_deltas, |
| 5604 |
// and flush. |
| 5605 |
uintptr_t* genovec = mwp->genovec; |
| 5606 |
uintptr_t* unlocked_set = mwp->unlocked_set; |
| 5607 |
uintptr_t* unlocked_missing_set = mwp->unlocked_missing_set; |
| 5608 |
uintptr_t* patch_01_set = nullptr; |
| 5609 |
AlleleCode* patch_01_dense = nullptr; |
| 5610 |
uintptr_t* patch_10_set = nullptr; |
| 5611 |
AlleleCode* patch_10_dense = nullptr; |
| 5612 |
if (write_allele_ct > 2) { |
| 5613 |
patch_01_set = mwp->patch_01_set; |
| 5614 |
patch_01_dense = mwp->patch_01_vals; |
| 5615 |
patch_10_set = mwp->patch_10_set; |
| 5616 |
patch_10_dense = mwp->patch_10_vals; |
| 5617 |
} |
| 5618 |
uintptr_t* phasepresent = nullptr; |
| 5619 |
uintptr_t* phaseinfo = nullptr; |
| 5620 |
if (hphase_exists || dphase_exists) { |
| 5621 |
phasepresent = mwp->phasepresent; |
| 5622 |
phaseinfo = mwp->phaseinfo; |
| 5623 |
} |
| 5624 |
uintptr_t* dosage_present = nullptr; |
| 5625 |
uint16_t* dosage_dense = nullptr; |
| 5626 |
uintptr_t* dphase_present = nullptr; |
| 5627 |
int16_t* dphase_dense = nullptr; |
| 5628 |
if (dosage_exists) { |
| 5629 |
dosage_present = mwp->dosage_present; |
| 5630 |
dosage_dense = mwp->dosage_main; |
| 5631 |
if (dphase_exists) { |
| 5632 |
dphase_present = mwp->dphase_present; |
| 5633 |
dphase_dense = mwp->dphase_delta; |
| 5634 |
} |
| 5635 |
} |
| 5636 |
const uint32_t write_sample_ctl2 = NypCtToWordCt(write_sample_ct); |
| 5637 |
for (uintptr_t rec_idx = simple_first_allele_remap; rec_idx != merge_rec_ct; ++rec_idx) { |
| 5638 |
const uint32_t file_idx = same_id_records[rec_idx]->secondary_key >> 32; |
| 5639 |
MergeReader* cur_mrp = mrp_arr[file_idx]; |
| 5640 |
uintptr_t* sample_span = cur_mrp->sample_span; |
| 5641 |
// Note that there should be a fast path for read_sample_ct == 1 in the |
| 5642 |
// generic version of this function. But probably not worth the effort |
| 5643 |
// here; we'll only get here on a large merge of single-sample filesets |
| 5644 |
// when the user has specified --merge-mode nm-first. |
| 5645 |
const uint32_t read_sample_ct = cur_mrp->sample_ct; |
| 5646 |
uintptr_t* unlocked_sample_span = mwp->unlocked_sample_span; |
| 5647 |
BitvecAndCopy(sample_span, unlocked_set, write_sample_ctl, unlocked_sample_span); |
| 5648 |
uint32_t unlocked_sample_ct = PopcountWords(unlocked_sample_span, write_sample_ctl); |
| 5649 |
if (!unlocked_sample_ct) { |
| 5650 |
// No point in loading this entry, all genotypes for these samples are |
| 5651 |
// already locked. |
| 5652 |
continue; |
| 5653 |
} |
| 5654 |
const uintptr_t* sample_include = cur_mrp->sample_include; |
| 5655 |
const uint32_t read_variant_uidx = S_CAST(uint32_t, same_id_records[rec_idx]->secondary_key); |
| 5656 |
// not const since there's an allele-rotation case where we change it |
| 5657 |
uint32_t read_allele_ct = same_id_records[rec_idx]->allele_ct; |
| 5658 |
PgenReader* pgrp = &(cur_mrp->pgr); |
| 5659 |
const uint32_t vrtype = PgrGetVrtype(pgrp, read_variant_uidx); |
| 5660 |
const uint32_t read_hphase_present = (vrtype / 0x10) & 1; |
| 5661 |
const uint32_t read_dosage_present = !!(vrtype & 0x60); |
| 5662 |
if ((read_allele_ct == 2) && (!read_dosage_present)) { |
| 5663 |
pgvp->patch_01_ct = 0; |
| 5664 |
pgvp->patch_10_ct = 0; |
| 5665 |
pgvp->dosage_ct = 0; |
| 5666 |
if (!read_hphase_present) { |
| 5667 |
pgvp->phasepresent_ct = 0; |
| 5668 |
reterr = PgrGet(sample_include, cur_mrp->pssi, read_sample_ct, read_variant_uidx, pgrp, pgvp->genovec); |
| 5669 |
} else { |
| 5670 |
reterr = PgrGetP(sample_include, cur_mrp->pssi, read_sample_ct, read_variant_uidx, pgrp, pgvp->genovec, pgvp->phasepresent, pgvp->phaseinfo, &pgvp->phasepresent_ct); |
| 5671 |
} |
| 5672 |
} else { |
| 5673 |
reterr = PgrGetMDp(sample_include, cur_mrp->pssi, read_sample_ct, read_variant_uidx, pgrp, pgvp); |
| 5674 |
} |
| 5675 |
// bugfix (9 Aug 2022) |
| 5676 |
ZeroTrailingNyps(read_sample_ct, pgvp->genovec); |
| 5677 |
if (unlikely(reterr)) { |
| 5678 |
PgenErrPrintNV(reterr, read_variant_uidx); |
| 5679 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5680 |
} |
| 5681 |
|
| 5682 |
// Identify which samples we can blindly clobber the previous entry for, |
| 5683 |
// and then do it. |
| 5684 |
// For "--merge-mode nm-first" or "--merge-mode first", this set covers |
| 5685 |
// every unlocked sample. |
| 5686 |
// For "--merge-mode nm-match", this set covers only unlocked-and-missing |
| 5687 |
// samples. We check concordance of unlocked-and-nonmissing entries in a |
| 5688 |
// subsequent loop. |
| 5689 |
uint32_t clobber_sample_ct = unlocked_sample_ct; |
| 5690 |
uintptr_t* clobber_sample_span = unlocked_sample_span; |
| 5691 |
const AlleleCode* cur_allele_remap = &(master_allele_remap[rec_idx * allele_remap_stride]); |
| 5692 |
if (unlocked_missing_set) { |
| 5693 |
// If allele rotation is needed, do it on all of pgvp in this case. |
| 5694 |
// (In the "--merge-mode nm-first" and "--merge-mode first" cases, we |
| 5695 |
// wait until after we've subsetted down to the samples we'll be |
| 5696 |
// clobbering.) |
| 5697 |
uint32_t read_allele_idx = 0; |
| 5698 |
for (; read_allele_idx != read_allele_ct; ++read_allele_idx) { |
| 5699 |
if (cur_allele_remap[read_allele_idx] != read_allele_idx) { |
| 5700 |
break; |
| 5701 |
} |
| 5702 |
} |
| 5703 |
if (read_allele_idx != read_allele_ct) { |
| 5704 |
// Allele rotation may be needed. |
| 5705 |
if ((cur_allele_remap[0] == kMissingAlleleCode) || (cur_allele_remap[1] == kMissingAlleleCode)) { |
| 5706 |
reterr = ValidateBiallelicVariantWithMissingCode(cur_allele_remap, read_sample_ct, (write_allele_ct == 2), pgvp); |
| 5707 |
if (unlikely(reterr)) { |
| 5708 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5709 |
} |
| 5710 |
} else { |
| 5711 |
const uint32_t read_sample_ctl = BitCtToWordCt(read_sample_ct); |
| 5712 |
if (write_allele_ct == 2) { |
| 5713 |
// Only possibility is cur_allele_remap[0] == 1, |
| 5714 |
// cur_allele_remap[1] == 0. |
| 5715 |
GenovecInvertUnsafe(read_sample_ct, pgvp->genovec); |
| 5716 |
ZeroTrailingNyps(read_sample_ct, pgvp->genovec); |
| 5717 |
if (pgvp->phasepresent_ct) { |
| 5718 |
BitvecInvert(read_sample_ct, pgvp->phaseinfo); |
| 5719 |
} |
| 5720 |
if (pgvp->dosage_ct) { |
| 5721 |
BiallelicDosage16Invert(pgvp->dosage_ct, pgvp->dosage_main); |
| 5722 |
if (pgvp->dphase_ct) { |
| 5723 |
BiallelicDphase16Invert(pgvp->dphase_ct, pgvp->dphase_delta); |
| 5724 |
} |
| 5725 |
} |
| 5726 |
} else { |
| 5727 |
uintptr_t* phaseinfo_xor = nullptr; |
| 5728 |
if (pgvp->phasepresent_ct) { |
| 5729 |
phaseinfo_xor = mwp->phaseinfo_xor; |
| 5730 |
} |
| 5731 |
AlleleCode* wide_codes = mwp->wide_codes; |
| 5732 |
PglMultiallelicSparseToDense(pgvp->genovec, pgvp->patch_01_set, pgvp->patch_01_vals, pgvp->patch_10_set, pgvp->patch_10_vals, cur_allele_remap, read_sample_ct, pgvp->patch_01_ct, pgvp->patch_10_ct, phaseinfo_xor, wide_codes); |
| 5733 |
if (phaseinfo_xor) { |
| 5734 |
BitvecXor(phaseinfo_xor, read_sample_ctl, pgvp->phaseinfo); |
| 5735 |
} |
| 5736 |
PglMultiallelicDenseToSparse(wide_codes, read_sample_ct, pgvp->genovec, pgvp->patch_01_set, pgvp->patch_01_vals, pgvp->patch_10_set, pgvp->patch_10_vals, &(pgvp->patch_01_ct), &(pgvp->patch_10_ct)); |
| 5737 |
if (pgvp->patch_01_ct || pgvp->patch_10_ct) { |
| 5738 |
// Only need to distinguish between 2 vs. greater-than-2 for |
| 5739 |
// now. |
| 5740 |
read_allele_ct = 3; |
| 5741 |
} |
| 5742 |
} |
| 5743 |
} |
| 5744 |
} |
| 5745 |
cur_allele_remap = nullptr; |
| 5746 |
clobber_sample_span = mwp->clobber_sample_span; |
| 5747 |
BitvecAndCopy(unlocked_missing_set, sample_span, write_sample_ctl, clobber_sample_span); |
| 5748 |
clobber_sample_ct = PopcountWords(clobber_sample_span, write_sample_ctl); |
| 5749 |
} |
| 5750 |
if ((merge_mode == kMergeModeNmMatch) && (clobber_sample_ct != read_sample_ct)) { |
| 5751 |
// Need to scan some samples for conflicts (clearing unlocked_set bit |
| 5752 |
// whenever one exists), and maybe clobber some others. |
| 5753 |
// Number of samples involved is likely to be a large fraction of |
| 5754 |
// write_sample_ct, so current logic is just optimized for the dense |
| 5755 |
// case. Can add a separate codepath for the sparse case later. |
| 5756 |
// 1a. Expand+permute all fields from pgvp to compare_pgvp. (Although |
| 5757 |
// clobber_pgvp can be modified after pointing to pgvp above, that |
| 5758 |
// can only happen when clobber_sample_ct == read_sample_ct.) |
| 5759 |
// 1b. Perform the following word-based comparisons, incrementally |
| 5760 |
// updating compare_mask: |
| 5761 |
// (2->1)(compare_pgvp->genovec ^ genovec) & compare_mask |
| 5762 |
// if r_patch_01_ct: |
| 5763 |
// (compare_pgvp->patch_01_set ^ patch_01_set) & compare_mask |
| 5764 |
// iterate over compare_pgvp->patch_01_vals |
| 5765 |
// r_patch_10_ct is similar |
| 5766 |
// if r_phasepresent_ct: |
| 5767 |
// (compare_pgvp->phasepresent ^ phasepresent) & compare_mask |
| 5768 |
// compare_pgvp->phasepresent & phasepresent & compare_mask & |
| 5769 |
// (compare_pgvp->phaseinfo ^ phaseinfo) |
| 5770 |
// dosage, dphase identical to patch_10 |
| 5771 |
// This is interleaved with (1a). |
| 5772 |
// 2. Clear unlocked_set bits. |
| 5773 |
PgenVariant* compare_pgvp = &(mwp->pgv_midbuf); |
| 5774 |
BitvecInvmaskCopy(unlocked_sample_span, clobber_sample_span, write_sample_ctl, mwp->unlocked_nonmissing_sample_span); |
| 5775 |
uintptr_t* compare_mask = mwp->mask_buf; |
| 5776 |
memcpy(compare_mask, mwp->unlocked_nonmissing_sample_span, write_sample_ctl * sizeof(intptr_t)); |
| 5777 |
uintptr_t* orig_genovec = pgvp->genovec; |
| 5778 |
uintptr_t* r_genovec = compare_pgvp->genovec; |
| 5779 |
ZeroWArr(write_sample_ctl2, r_genovec); |
| 5780 |
const uint32_t* old_sample_idx_to_new = cur_mrp->old_sample_idx_to_new; |
| 5781 |
const uint32_t read_sample_ctl2 = NypCtToWordCt(read_sample_ct); |
| 5782 |
for (uint32_t widx = 0; widx != read_sample_ctl2; ++widx) { |
| 5783 |
uintptr_t geno_word = orig_genovec[widx]; |
| 5784 |
if (!geno_word) { |
| 5785 |
continue; |
| 5786 |
} |
| 5787 |
const uint32_t* cur_old_sample_idx_to_new = &(old_sample_idx_to_new[widx * kBitsPerWordD2]); |
| 5788 |
do { |
| 5789 |
const uint32_t bit_read_shift_ct = ctzw(geno_word) & (kBitsPerWord - 2); |
| 5790 |
const uintptr_t cur_geno = (geno_word >> bit_read_shift_ct) & 3; |
| 5791 |
const uint32_t new_sample_idx = cur_old_sample_idx_to_new[bit_read_shift_ct / 2]; |
| 5792 |
const uint32_t new_word_idx = new_sample_idx / kBitsPerWordD2; |
| 5793 |
const uint32_t bit_write_shift_ct = 2 * (new_sample_idx % kBitsPerWordD2); |
| 5794 |
r_genovec[new_word_idx] |= cur_geno << bit_write_shift_ct; |
| 5795 |
geno_word &= (~(3 * k1LU)) << bit_read_shift_ct; |
| 5796 |
} while (geno_word); |
| 5797 |
} |
| 5798 |
Halfword* compare_mask_hwalias = R_CAST(Halfword*, compare_mask); |
| 5799 |
for (uint32_t widx = 0; widx != write_sample_ctl2; ++widx) { |
| 5800 |
Halfword compare_mask_hw = compare_mask_hwalias[widx]; |
| 5801 |
if (!compare_mask_hw) { |
| 5802 |
continue; |
| 5803 |
} |
| 5804 |
const uintptr_t diff_bits = r_genovec[widx] ^ genovec[widx]; |
| 5805 |
const Halfword diff_hw = PackWordToHalfwordMask5555(diff_bits | (diff_bits >> 1)); |
| 5806 |
compare_mask_hwalias[widx] = compare_mask_hw & (~diff_hw); |
| 5807 |
} |
| 5808 |
// possible todo: check if performance gain from switching to single |
| 5809 |
// compare+clobber loops is significant |
| 5810 |
if (clobber_sample_ct) { |
| 5811 |
const Halfword* clobber_span_hwalias = R_CAST(const Halfword*, clobber_sample_span); |
| 5812 |
for (uint32_t widx = 0; widx != write_sample_ctl2; ++widx) { |
| 5813 |
const Halfword clobber_span_hw = clobber_span_hwalias[widx]; |
| 5814 |
if (!clobber_span_hw) { |
| 5815 |
continue; |
| 5816 |
} |
| 5817 |
genovec[widx] ^= (UnpackHalfwordToWord(clobber_span_hw) * 3) & (~r_genovec[widx]); |
| 5818 |
} |
| 5819 |
} |
| 5820 |
if (write_allele_ct > 2) { |
| 5821 |
if (pgvp->patch_01_ct) { |
| 5822 |
uintptr_t* r_patch_01_set = compare_pgvp->patch_01_set; |
| 5823 |
AlleleCode* r_patch_01_dense = compare_pgvp->patch_01_vals; |
| 5824 |
ZeroWArr(write_sample_ctl, r_patch_01_set); |
| 5825 |
PermuteUpdate8bitDenseFromSparse(pgvp->patch_01_set, pgvp->patch_01_vals, old_sample_idx_to_new, read_sample_ct, pgvp->patch_01_ct, r_patch_01_set, r_patch_01_dense); |
| 5826 |
Compare8bitDense(r_patch_01_set, r_patch_01_dense, patch_01_set, patch_01_dense, write_sample_ctl, compare_mask); |
| 5827 |
if (clobber_sample_ct) { |
| 5828 |
Update8bitDense(clobber_sample_span, r_patch_01_set, r_patch_01_dense, write_sample_ctl, patch_01_set, patch_01_dense); |
| 5829 |
} |
| 5830 |
} else { |
| 5831 |
// Anything which is currently marked as multiallelic ref-altx, and |
| 5832 |
// is in the current comparison set, must be a mismatch since there |
| 5833 |
// isn't a single multiallelic ref-altx in the current source. |
| 5834 |
BitvecInvmask(patch_01_set, write_sample_ctl, compare_mask); |
| 5835 |
} |
| 5836 |
if (pgvp->patch_10_ct) { |
| 5837 |
uintptr_t* r_patch_10_set = compare_pgvp->patch_10_set; |
| 5838 |
AlleleCode* r_patch_10_dense = compare_pgvp->patch_10_vals; |
| 5839 |
ZeroWArr(write_sample_ctl, r_patch_10_set); |
| 5840 |
PermuteUpdate16bitDenseFromSparse(pgvp->patch_10_set, pgvp->patch_10_vals, old_sample_idx_to_new, read_sample_ct, pgvp->patch_10_ct, r_patch_10_set, r_patch_10_dense); |
| 5841 |
Compare16bitDense(r_patch_10_set, r_patch_10_dense, patch_10_set, patch_10_dense, write_sample_ctl, compare_mask); |
| 5842 |
if (clobber_sample_ct) { |
| 5843 |
Update16bitDense(clobber_sample_span, r_patch_10_set, r_patch_10_dense, write_sample_ctl, patch_10_set, patch_10_dense); |
| 5844 |
} |
| 5845 |
} else { |
| 5846 |
BitvecInvmask(patch_10_set, write_sample_ctl, compare_mask); |
| 5847 |
} |
| 5848 |
} |
| 5849 |
if (phasepresent) { |
| 5850 |
if (pgvp->phasepresent_ct) { |
| 5851 |
uintptr_t* r_phasepresent = compare_pgvp->phasepresent; |
| 5852 |
uintptr_t* r_phaseinfo = compare_pgvp->phaseinfo; |
| 5853 |
CopyAndPermuteHphase(pgvp->phasepresent, pgvp->phaseinfo, old_sample_idx_to_new, write_sample_ctl, pgvp->phasepresent_ct, r_phasepresent, r_phaseinfo); |
| 5854 |
for (uint32_t widx = 0; widx != write_sample_ctl; ++widx) { |
| 5855 |
uintptr_t compare_word = compare_mask[widx]; |
| 5856 |
if (!compare_word) { |
| 5857 |
continue; |
| 5858 |
} |
| 5859 |
const uintptr_t r_phasepresent_word = r_phasepresent[widx]; |
| 5860 |
const uintptr_t w_phasepresent_word = phasepresent[widx]; |
| 5861 |
compare_word &= ~((r_phasepresent_word ^ w_phasepresent_word) | (r_phasepresent_word & w_phasepresent_word & (r_phaseinfo[widx] ^ phaseinfo[widx]))); |
| 5862 |
compare_mask[widx] = compare_word; |
| 5863 |
} |
| 5864 |
if (clobber_sample_ct) { |
| 5865 |
for (uint32_t widx = 0; widx != write_sample_ctl; ++widx) { |
| 5866 |
const uintptr_t update_word = clobber_sample_span[widx]; |
| 5867 |
if (!update_word) { |
| 5868 |
continue; |
| 5869 |
} |
| 5870 |
const uintptr_t src_present_word = r_phasepresent[widx] & update_word; |
| 5871 |
if (!src_present_word) { |
| 5872 |
continue; |
| 5873 |
} |
| 5874 |
phasepresent[widx] |= src_present_word; |
| 5875 |
phaseinfo[widx] |= src_present_word & r_phaseinfo[widx]; |
| 5876 |
} |
| 5877 |
} |
| 5878 |
} else { |
| 5879 |
BitvecInvmask(phasepresent, write_sample_ctl, compare_mask); |
| 5880 |
} |
| 5881 |
} |
| 5882 |
if (dosage_present) { |
| 5883 |
if (pgvp->dosage_ct) { |
| 5884 |
uintptr_t* r_dosage_present = compare_pgvp->dosage_present; |
| 5885 |
uint16_t* r_dosage_dense = compare_pgvp->dosage_main; |
| 5886 |
ZeroWArr(write_sample_ctl, r_dosage_present); |
| 5887 |
PermuteUpdate16bitDenseFromSparse(pgvp->dosage_present, pgvp->dosage_main, old_sample_idx_to_new, read_sample_ct, pgvp->dosage_ct, r_dosage_present, r_dosage_dense); |
| 5888 |
Compare16bitDense(r_dosage_present, r_dosage_dense, dosage_present, dosage_dense, write_sample_ctl, compare_mask); |
| 5889 |
if (clobber_sample_ct) { |
| 5890 |
Update16bitDense(clobber_sample_span, r_dosage_present, r_dosage_dense, write_sample_ctl, dosage_present, dosage_dense); |
| 5891 |
} |
| 5892 |
} else { |
| 5893 |
BitvecInvmask(dosage_present, write_sample_ctl, compare_mask); |
| 5894 |
} |
| 5895 |
if (dphase_present) { |
| 5896 |
if (pgvp->dphase_ct) { |
| 5897 |
uintptr_t* r_dphase_present = compare_pgvp->dphase_present; |
| 5898 |
int16_t* r_dphase_dense = compare_pgvp->dphase_delta; |
| 5899 |
ZeroWArr(write_sample_ctl, r_dphase_present); |
| 5900 |
PermuteUpdate16bitDenseFromSparse(pgvp->dphase_present, pgvp->dphase_delta, old_sample_idx_to_new, read_sample_ct, pgvp->dphase_ct, r_dphase_present, r_dphase_dense); |
| 5901 |
Compare16bitDense(r_dphase_present, r_dphase_dense, dphase_present, dphase_dense, write_sample_ctl, compare_mask); |
| 5902 |
if (clobber_sample_ct) { |
| 5903 |
Update16bitDense(clobber_sample_span, r_dphase_present, r_dphase_dense, write_sample_ctl, dosage_present, dosage_dense); |
| 5904 |
} |
| 5905 |
} else { |
| 5906 |
BitvecInvmask(dphase_present, write_sample_ctl, compare_mask); |
| 5907 |
} |
| 5908 |
} |
| 5909 |
} |
| 5910 |
// unlocked_set ^= unlocked_nonmissing_sample_span ^ compare_mask |
| 5911 |
BitvecXor(mwp->unlocked_nonmissing_sample_span, write_sample_ctl, unlocked_set); |
| 5912 |
BitvecXor(compare_mask, write_sample_ctl, unlocked_set); |
| 5913 |
} else if (clobber_sample_ct) { |
| 5914 |
// possible todo: only use this branch on sufficiently small |
| 5915 |
// clobber_sample_ct |
| 5916 |
const uint32_t clobber_sample_ctl = BitCtToWordCt(clobber_sample_ct); |
| 5917 |
PgenVariant* clobber_pgvp = pgvp; |
| 5918 |
uint32_t* clobber_sample_idx_to_new = cur_mrp->old_sample_idx_to_new; |
| 5919 |
if (read_sample_ct != clobber_sample_ct) { |
| 5920 |
// merge_mode is either 'first' or 'nm-first'. |
| 5921 |
// Similar to subsetting logic in MakePgenThread(). |
| 5922 |
uintptr_t* clobber_subset_of_read = mwp->mask_buf; |
| 5923 |
CopyBitarrSubset(clobber_sample_span, sample_span, read_sample_ct, clobber_subset_of_read); |
| 5924 |
clobber_sample_idx_to_new = mwp->clobber_sample_idx_to_new; |
| 5925 |
const uint32_t* old_sample_idx_to_new = cur_mrp->old_sample_idx_to_new; |
| 5926 |
const uint32_t sample_idx_increasing = cur_mrp->sample_idx_increasing; |
| 5927 |
uintptr_t read_idx_base = 0; |
| 5928 |
uintptr_t cur_bits = clobber_subset_of_read[0]; |
| 5929 |
if (sample_idx_increasing < 2) { |
| 5930 |
for (uint32_t clobber_idx = 0; clobber_idx != clobber_sample_ct; ++clobber_idx) { |
| 5931 |
const uint32_t read_idx = BitIter1(clobber_subset_of_read, &read_idx_base, &cur_bits); |
| 5932 |
clobber_sample_idx_to_new[clobber_idx] = old_sample_idx_to_new[read_idx]; |
| 5933 |
} |
| 5934 |
} else { |
| 5935 |
for (uint32_t clobber_idx = 0; clobber_idx != clobber_sample_ct; ++clobber_idx) { |
| 5936 |
const uint32_t read_idx = BitIter1(clobber_subset_of_read, &read_idx_base, &cur_bits); |
| 5937 |
clobber_sample_idx_to_new[clobber_idx] = read_idx; |
| 5938 |
} |
| 5939 |
} |
| 5940 |
clobber_pgvp = &(mwp->pgv_midbuf); |
| 5941 |
CopyNyparrNonemptySubset(pgvp->genovec, clobber_subset_of_read, read_sample_ct, clobber_sample_ct, clobber_pgvp->genovec); |
| 5942 |
if (read_allele_ct > 2) { |
| 5943 |
clobber_pgvp->patch_01_ct = Copy1bit8Subset(pgvp->patch_01_set, pgvp->patch_01_vals, clobber_subset_of_read, pgvp->patch_01_ct, clobber_sample_ct, clobber_pgvp->patch_01_set, clobber_pgvp->patch_01_vals); |
| 5944 |
clobber_pgvp->patch_10_ct = Copy1bit16Subset(pgvp->patch_10_set, pgvp->patch_10_vals, clobber_subset_of_read, pgvp->patch_10_ct, clobber_sample_ct, clobber_pgvp->patch_10_set, clobber_pgvp->patch_10_vals); |
| 5945 |
} |
| 5946 |
clobber_pgvp->phasepresent_ct = 0; |
| 5947 |
if (pgvp->phasepresent_ct) { |
| 5948 |
CopyBitarrSubset(pgvp->phasepresent, clobber_subset_of_read, clobber_sample_ct, clobber_pgvp->phasepresent); |
| 5949 |
clobber_pgvp->phasepresent_ct = PopcountWords(clobber_pgvp->phasepresent, clobber_sample_ctl); |
| 5950 |
if (clobber_pgvp->phasepresent_ct) { |
| 5951 |
CopyBitarrSubset(pgvp->phaseinfo, clobber_subset_of_read, clobber_sample_ct, clobber_pgvp->phaseinfo); |
| 5952 |
} |
| 5953 |
} |
| 5954 |
clobber_pgvp->dosage_ct = 0; |
| 5955 |
if (pgvp->dosage_ct) { |
| 5956 |
clobber_pgvp->dosage_ct = Copy1bit16Subset(pgvp->dosage_present, pgvp->dosage_main, clobber_subset_of_read, pgvp->dosage_ct, clobber_sample_ct, clobber_pgvp->dosage_present, clobber_pgvp->dosage_main); |
| 5957 |
clobber_pgvp->dphase_ct = Copy1bit16Subset(pgvp->dphase_present, pgvp->dphase_delta, clobber_subset_of_read, pgvp->dphase_ct, clobber_sample_ct, clobber_pgvp->dphase_present, clobber_pgvp->dphase_delta); |
| 5958 |
} |
| 5959 |
} |
| 5960 |
if (cur_allele_remap && ((cur_allele_remap[0] == kMissingAlleleCode) || (cur_allele_remap[1] == kMissingAlleleCode))) { |
| 5961 |
reterr = ValidateBiallelicVariantWithMissingCode(cur_allele_remap, clobber_sample_ct, (write_allele_ct == 2), clobber_pgvp); |
| 5962 |
if (unlikely(reterr)) { |
| 5963 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 5964 |
} |
| 5965 |
} |
| 5966 |
uintptr_t* r_genovec = clobber_pgvp->genovec; |
| 5967 |
const uint32_t r_phasepresent_ct = clobber_pgvp->phasepresent_ct; |
| 5968 |
if (write_allele_ct == 2) { |
| 5969 |
const uint32_t r_dosage_ct = clobber_pgvp->dosage_ct; |
| 5970 |
uint32_t r_dphase_ct = r_dosage_ct? clobber_pgvp->dphase_ct : 0; |
| 5971 |
if (cur_allele_remap && (cur_allele_remap[0] == 1) && (cur_allele_remap[1] == 0)) { |
| 5972 |
// This is the only remaining case where clobber_pgvp is still |
| 5973 |
// flipped relative to the write buffers; we already flipped the |
| 5974 |
// kMissingAlleleCode cases. |
| 5975 |
GenovecInvertUnsafe(clobber_sample_ct, r_genovec); |
| 5976 |
ZeroTrailingNyps(clobber_sample_ct, r_genovec); |
| 5977 |
if (r_phasepresent_ct) { |
| 5978 |
BitvecInvert(clobber_sample_ctl, clobber_pgvp->phaseinfo); |
| 5979 |
} |
| 5980 |
if (r_dosage_ct) { |
| 5981 |
BiallelicDosage16Invert(r_dosage_ct, clobber_pgvp->dosage_main); |
| 5982 |
if (r_dphase_ct) { |
| 5983 |
BiallelicDphase16Invert(r_dphase_ct, clobber_pgvp->dphase_delta); |
| 5984 |
} |
| 5985 |
} |
| 5986 |
} |
| 5987 |
PermuteUpdateGenovec(r_genovec, clobber_sample_idx_to_new, clobber_sample_ct, genovec); |
| 5988 |
if (r_phasepresent_ct) { |
| 5989 |
PermuteUpdateHphase(clobber_pgvp->phasepresent, clobber_pgvp->phaseinfo, clobber_sample_idx_to_new, r_phasepresent_ct, phasepresent, phaseinfo); |
| 5990 |
} |
| 5991 |
if (r_dosage_ct) { |
| 5992 |
PermuteUpdate16bitDenseFromSparse(clobber_pgvp->dosage_present, clobber_pgvp->dosage_main, clobber_sample_idx_to_new, clobber_sample_ct, r_dosage_ct, dosage_present, dosage_dense); |
| 5993 |
if (r_dphase_ct) { |
| 5994 |
PermuteUpdate16bitDenseFromSparse(clobber_pgvp->dphase_present, clobber_pgvp->dphase_delta, clobber_sample_idx_to_new, clobber_sample_ct, r_dosage_ct, dphase_present, dphase_dense); |
| 5995 |
} |
| 5996 |
} |
| 5997 |
} else { |
| 5998 |
// Multiallelic variant. |
| 5999 |
uintptr_t* r_patch_01_set = clobber_pgvp->patch_01_set; |
| 6000 |
AlleleCode* r_patch_01_vals = clobber_pgvp->patch_01_vals; |
| 6001 |
uintptr_t* r_patch_10_set = clobber_pgvp->patch_10_set; |
| 6002 |
AlleleCode* r_patch_10_vals = clobber_pgvp->patch_10_vals; |
| 6003 |
uint32_t r_patch_01_ct = 0; |
| 6004 |
uint32_t r_patch_10_ct = 0; |
| 6005 |
if (read_allele_ct > 2) { |
| 6006 |
r_patch_01_ct = clobber_pgvp->patch_01_ct; |
| 6007 |
r_patch_10_ct = clobber_pgvp->patch_10_ct; |
| 6008 |
} |
| 6009 |
if (cur_allele_remap) { |
| 6010 |
uint32_t read_allele_idx = 0; |
| 6011 |
for (; read_allele_idx != read_allele_ct; ++read_allele_idx) { |
| 6012 |
if (cur_allele_remap[read_allele_idx] != read_allele_idx) { |
| 6013 |
break; |
| 6014 |
} |
| 6015 |
} |
| 6016 |
if (read_allele_idx != read_allele_ct) { |
| 6017 |
// Allele rotation needed. |
| 6018 |
uintptr_t* phaseinfo_xor = nullptr; |
| 6019 |
if (r_phasepresent_ct) { |
| 6020 |
phaseinfo_xor = mwp->phaseinfo_xor; |
| 6021 |
} |
| 6022 |
AlleleCode* wide_codes = mwp->wide_codes; |
| 6023 |
PglMultiallelicSparseToDense(r_genovec, r_patch_01_set, r_patch_01_vals, r_patch_10_set, r_patch_10_vals, cur_allele_remap, clobber_sample_ct, r_patch_01_ct, r_patch_10_ct, phaseinfo_xor, wide_codes); |
| 6024 |
if (phaseinfo_xor) { |
| 6025 |
BitvecXor(phaseinfo_xor, clobber_sample_ctl, clobber_pgvp->phaseinfo); |
| 6026 |
} |
| 6027 |
PglMultiallelicDenseToSparse(wide_codes, clobber_sample_ct, r_genovec, r_patch_01_set, r_patch_01_vals, r_patch_10_set, r_patch_10_vals, &r_patch_01_ct, &r_patch_10_ct); |
| 6028 |
} |
| 6029 |
} |
| 6030 |
PermuteUpdateGenovec(r_genovec, clobber_sample_idx_to_new, clobber_sample_ct, genovec); |
| 6031 |
if (r_patch_01_ct) { |
| 6032 |
PermuteUpdate8bitDenseFromSparse(r_patch_01_set, r_patch_01_vals, clobber_sample_idx_to_new, clobber_sample_ct, r_patch_01_ct, patch_01_set, patch_01_dense); |
| 6033 |
} |
| 6034 |
if (r_patch_10_ct) { |
| 6035 |
PermuteUpdate16bitDenseFromSparse(r_patch_10_set, r_patch_10_vals, clobber_sample_idx_to_new, clobber_sample_ct, r_patch_10_ct, patch_10_set, patch_10_dense); |
| 6036 |
} |
| 6037 |
if (r_phasepresent_ct) { |
| 6038 |
PermuteUpdateHphase(clobber_pgvp->phasepresent, clobber_pgvp->phaseinfo, clobber_sample_idx_to_new, r_phasepresent_ct, phasepresent, phaseinfo); |
| 6039 |
} |
| 6040 |
} |
| 6041 |
} |
| 6042 |
if (clobber_sample_ct && (rec_idx + 1 != merge_rec_ct)) { |
| 6043 |
// Update unlocked_set for modes 'first'/'nm-first', or |
| 6044 |
// unlocked_missing_set for mode 'nm-match'. |
| 6045 |
// 'first': clear all bits intersecting clobber_sample_span. |
| 6046 |
// 'nm-first', 'nm-match': clear all bits corresponding to nonmissing |
| 6047 |
// genotypes. |
| 6048 |
// Skip this on last input file, since this only affects eligibility |
| 6049 |
// for future clobbers, which don't exist. |
| 6050 |
uintptr_t* untouched_set = unlocked_missing_set? unlocked_missing_set : unlocked_set; |
| 6051 |
if (merge_mode == kMergeModeFirst) { |
| 6052 |
BitvecInvmask(clobber_sample_span, write_sample_ctl, untouched_set); |
| 6053 |
} else { |
| 6054 |
GenoarrToMissingnessUnsafe(genovec, write_sample_ct, untouched_set); |
| 6055 |
if (dosage_present) { |
| 6056 |
// Possible for dosage to be present when hardcall is missing. |
| 6057 |
BitvecInvmask(dosage_present, write_sample_ctl, untouched_set); |
| 6058 |
} |
| 6059 |
} |
| 6060 |
} |
| 6061 |
} |
| 6062 |
if (merge_mode == kMergeModeNmMatch) { |
| 6063 |
const Halfword* unlocked_set_hwalias = R_CAST(Halfword*, unlocked_set); |
| 6064 |
for (uint32_t widx = 0; widx != write_sample_ctl2; ++widx) { |
| 6065 |
const Halfword locked_hw = ~unlocked_set_hwalias[widx]; |
| 6066 |
if (!locked_hw) { |
| 6067 |
continue; |
| 6068 |
} |
| 6069 |
genovec[widx] |= UnpackHalfwordToWord(locked_hw) * 3; |
| 6070 |
} |
| 6071 |
ZeroTrailingNyps(write_sample_ct, genovec); |
| 6072 |
if (write_allele_ct > 2) { |
| 6073 |
BitvecAnd(unlocked_set, write_sample_ctl, patch_01_set); |
| 6074 |
BitvecAnd(unlocked_set, write_sample_ctl, patch_10_set); |
| 6075 |
} |
| 6076 |
if (phasepresent) { |
| 6077 |
BitvecAnd(unlocked_set, write_sample_ctl, phasepresent); |
| 6078 |
} |
| 6079 |
if (dosage_present) { |
| 6080 |
BitvecAnd(unlocked_set, write_sample_ctl, dosage_present); |
| 6081 |
if (dphase_present) { |
| 6082 |
BitvecAnd(unlocked_set, write_sample_ctl, dphase_present); |
| 6083 |
} |
| 6084 |
} |
| 6085 |
} |
| 6086 |
// Collapse dense representations to sparse when the latter is expected by |
| 6087 |
// the writer. |
| 6088 |
uint32_t patch_01_ct = 0; |
| 6089 |
uint32_t patch_10_ct = 0; |
| 6090 |
if (write_allele_ct > 2) { |
| 6091 |
patch_01_ct = Dense8bitToSparse(patch_01_set, write_sample_ctl, patch_01_dense); |
| 6092 |
patch_10_ct = Dense16bitToSparse(patch_10_set, write_sample_ctl, patch_10_dense); |
| 6093 |
} |
| 6094 |
// rename for clarity |
| 6095 |
AlleleCode* patch_01_vals = patch_01_dense; |
| 6096 |
AlleleCode* patch_10_vals = patch_10_dense; |
| 6097 |
|
| 6098 |
uint32_t dosage_ct = 0; |
| 6099 |
uint32_t dphase_ct = 0; |
| 6100 |
if (dosage_present) { |
| 6101 |
dosage_ct = Dense16bitToSparse(dosage_present, write_sample_ctl, dosage_dense); |
| 6102 |
if (dphase_present) { |
| 6103 |
dphase_ct = Dense16bitToSparse(dphase_present, write_sample_ctl, dphase_dense); |
| 6104 |
} |
| 6105 |
} |
| 6106 |
uint16_t* dosage_main = dosage_dense; |
| 6107 |
int16_t* dphase_delta = dphase_dense; |
| 6108 |
|
| 6109 |
uint32_t phasepresent_ct = 0; |
| 6110 |
if (phasepresent) { |
| 6111 |
phasepresent_ct = PopcountWords(phasepresent, write_sample_ctl); |
| 6112 |
} |
| 6113 |
if (write_allele_ct == 2) { |
| 6114 |
if (!dosage_ct) { |
| 6115 |
if (!phasepresent_ct) { |
| 6116 |
reterr = SpgwAppendBiallelicGenovec(genovec, spgwp); |
| 6117 |
} else { |
| 6118 |
reterr = SpgwAppendBiallelicGenovecHphase(genovec, phasepresent, phaseinfo, spgwp); |
| 6119 |
} |
| 6120 |
} else { |
| 6121 |
if ((!phasepresent_ct) && (!dphase_ct)) { |
| 6122 |
reterr = SpgwAppendBiallelicGenovecDosage16(genovec, dosage_present, dosage_main, dosage_ct, spgwp); |
| 6123 |
} else { |
| 6124 |
reterr = SpgwAppendBiallelicGenovecDphase16(genovec, phasepresent, phaseinfo, dosage_present, dphase_present, dosage_main, dphase_delta, dosage_ct, dphase_ct, spgwp); |
| 6125 |
} |
| 6126 |
} |
| 6127 |
} else { |
| 6128 |
assert(!dosage_ct); // not yet supported |
| 6129 |
if (!phasepresent_ct) { |
| 6130 |
reterr = SpgwAppendMultiallelicSparse(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, write_allele_ct, patch_01_ct, patch_10_ct, spgwp); |
| 6131 |
} else { |
| 6132 |
reterr = SpgwAppendMultiallelicGenovecHphase(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, phasepresent, phaseinfo, write_allele_ct, patch_01_ct, patch_10_ct, spgwp); |
| 6133 |
} |
| 6134 |
} |
| 6135 |
if (unlikely(reterr)) { |
| 6136 |
goto MergePgenVariantNoTmpLocked_ret_1; |
| 6137 |
} |
| 6138 |
} |
| 6139 |
MergePgenVariantNoTmpLocked_ret_1: |
| 6140 |
return reterr; |
| 6141 |
} |
| 6142 |
|
| 6143 |
// TODO: --merge-mode 'first'/'nm-match' + intermediate-file support |
| 6144 |
|
| 6145 |
typedef struct SamePosPvarRecordAsorterStruct { |
| 6146 |
SamePosPvarRecord* pp; |
| 6147 |
#ifdef __cplusplus |
| 6148 |
bool operator<(const struct SamePosPvarRecordAsorterStruct& rhs) const { |
| 6149 |
const int32_t strcmp_result = strcmp_overread(pp->variant_id, rhs.pp->variant_id); |
| 6150 |
if (strcmp_result) { |
| 6151 |
return strcmp_result < 0; |
| 6152 |
} |
| 6153 |
return pp->secondary_key < rhs.pp->secondary_key; |
| 6154 |
} |
| 6155 |
#endif |
| 6156 |
} SamePosPvarRecordAsorter; |
| 6157 |
|
| 6158 |
typedef struct SamePosPvarRecordNsorterStruct { |
| 6159 |
SamePosPvarRecord* pp; |
| 6160 |
#ifdef __cplusplus |
| 6161 |
bool operator<(const struct SamePosPvarRecordNsorterStruct& rhs) const { |
| 6162 |
const int32_t strcmp_result = strcmp_natural_uncasted(pp->variant_id, rhs.pp->variant_id); |
| 6163 |
if (strcmp_result) { |
| 6164 |
return strcmp_result < 0; |
| 6165 |
} |
| 6166 |
return pp->secondary_key < rhs.pp->secondary_key; |
| 6167 |
} |
| 6168 |
#endif |
| 6169 |
} SamePosPvarRecordNsorter; |
| 6170 |
|
| 6171 |
#ifndef __cplusplus |
| 6172 |
int32_t SamePosPvarRecordAcmp(const void* r1, const void* r2) { |
| 6173 |
const SamePosPvarRecord* rec1 = S_CAST(const SamePosPvarRecordAsorter*, r1)->pp; |
| 6174 |
const SamePosPvarRecord* rec2 = S_CAST(const SamePosPvarRecordAsorter*, r2)->pp; |
| 6175 |
const int32_t strcmp_result = strcmp_overread(rec1->variant_id, rec2->variant_id); |
| 6176 |
if (strcmp_result) { |
| 6177 |
return strcmp_result; |
| 6178 |
} |
| 6179 |
if (rec1->secondary_key < rec2->secondary_key) { |
| 6180 |
return -1; |
| 6181 |
} |
| 6182 |
return (rec1->secondary_key > rec2->secondary_key); |
| 6183 |
} |
| 6184 |
|
| 6185 |
int32_t SamePosPvarRecordNcmp(const void* r1, const void* r2) { |
| 6186 |
const SamePosPvarRecord* rec1 = S_CAST(const SamePosPvarRecordNsorter*, r1)->pp; |
| 6187 |
const SamePosPvarRecord* rec2 = S_CAST(const SamePosPvarRecordNsorter*, r2)->pp; |
| 6188 |
const int32_t strcmp_result = strcmp_natural_uncasted(rec1->variant_id, rec2->variant_id); |
| 6189 |
if (strcmp_result) { |
| 6190 |
return strcmp_result; |
| 6191 |
} |
| 6192 |
if (rec1->secondary_key < rec2->secondary_key) { |
| 6193 |
return -1; |
| 6194 |
} |
| 6195 |
return (rec1->secondary_key > rec2->secondary_key); |
| 6196 |
} |
| 6197 |
#endif |
| 6198 |
|
| 6199 |
PglErr ConcatPvariantPos(int32_t cur_bp, uintptr_t variant_ct, PvariantPosMergeContext* ppmcp, SamePosPvarRecord** same_pos_records, MergeReader* mrp, MergeWriter* mwp) { |
| 6200 |
if (!variant_ct) { |
| 6201 |
return kPglRetSuccess; |
| 6202 |
} |
| 6203 |
if (ppmcp->sort_vars_mode == kSortAscii) { |
| 6204 |
SamePosPvarRecordAsorter* asorter = R_CAST(SamePosPvarRecordAsorter*, same_pos_records); |
| 6205 |
STD_SORT(variant_ct, SamePosPvarRecordAcmp, asorter); |
| 6206 |
} else { |
| 6207 |
SamePosPvarRecordNsorter* nsorter = R_CAST(SamePosPvarRecordNsorter*, same_pos_records); |
| 6208 |
STD_SORT(variant_ct, SamePosPvarRecordNcmp, nsorter); |
| 6209 |
} |
| 6210 |
ppmcp->pmc.cur_bp = cur_bp; |
| 6211 |
uintptr_t* write_nonref_flags = ppmcp->write_nonref_flags; |
| 6212 |
uint32_t write_variant_idx = ppmcp->write_variant_idx; |
| 6213 |
uint32_t next_print_variant_idx = ppmcp->next_print_variant_idx; |
| 6214 |
uintptr_t* write_allele_idx_offsets = ppmcp->write_allele_idx_offsets; |
| 6215 |
|
| 6216 |
for (uintptr_t rec_idx_start = 0; ; ) { |
| 6217 |
char* cur_variant_id = same_pos_records[rec_idx_start]->variant_id; |
| 6218 |
const uint32_t cur_variant_id_slen = strlen(cur_variant_id); |
| 6219 |
uintptr_t rec_idx_end = rec_idx_start + 1; |
| 6220 |
for (; rec_idx_end != variant_ct; ++rec_idx_end) { |
| 6221 |
if (!strequal_unsafe(same_pos_records[rec_idx_end]->variant_id, cur_variant_id, cur_variant_id_slen)) { |
| 6222 |
break; |
| 6223 |
} |
| 6224 |
} |
| 6225 |
SamePosPvarRecord** same_id_records = &(same_pos_records[rec_idx_start]); |
| 6226 |
const uintptr_t merge_rec_ct = rec_idx_end - rec_idx_start; |
| 6227 |
uint32_t is_pr = 0; |
| 6228 |
uint32_t allele_ct; |
| 6229 |
uint64_t cur_line_blen; |
| 6230 |
PglErr reterr = MergePvariant(merge_rec_ct, &ppmcp->pmc, same_id_records, write_nonref_flags? (&is_pr) : nullptr, &allele_ct, &cur_line_blen); |
| 6231 |
if (unlikely(reterr)) { |
| 6232 |
return reterr; |
| 6233 |
} |
| 6234 |
// bugfix (8 Sep 2021): forgot that allele_ct == 0 indicates variant skip |
| 6235 |
if (allele_ct) { |
| 6236 |
if (unlikely(cur_line_blen > kMaxLongLine)) { |
| 6237 |
logerrprintfww("Error: Merged .pvar entry for variant '%s' at %s:%d is too long for this " PROG_NAME_STR " build.\n", cur_variant_id, ppmcp->pmc.chr_buf, cur_bp); |
| 6238 |
return kPglRetNotYetSupported; |
| 6239 |
} |
| 6240 |
if (write_allele_idx_offsets) { |
| 6241 |
write_allele_idx_offsets[write_variant_idx + 1] = write_allele_idx_offsets[write_variant_idx] + allele_ct; |
| 6242 |
} |
| 6243 |
if (write_nonref_flags) { |
| 6244 |
AssignBit(write_variant_idx, is_pr, write_nonref_flags); |
| 6245 |
} |
| 6246 |
|
| 6247 |
reterr = MergePgenVariantNoTmpLocked(same_id_records, ppmcp->pmc.allele_remap, merge_rec_ct, allele_ct, ppmcp->pmc.read_max_allele_ct, &mrp, mwp); |
| 6248 |
if (unlikely(reterr)) { |
| 6249 |
return reterr; |
| 6250 |
} |
| 6251 |
|
| 6252 |
++write_variant_idx; |
| 6253 |
if (write_variant_idx == next_print_variant_idx) { |
| 6254 |
printf("\rConcatenating... %u/%u variants complete.", write_variant_idx, ppmcp->write_variant_ct); |
| 6255 |
fflush(stdout); |
| 6256 |
next_print_variant_idx += 10000; |
| 6257 |
ppmcp->next_print_variant_idx = next_print_variant_idx; |
| 6258 |
} |
| 6259 |
} |
| 6260 |
if (rec_idx_end == variant_ct) { |
| 6261 |
ppmcp->write_variant_idx = write_variant_idx; |
| 6262 |
return kPglRetSuccess; |
| 6263 |
} |
| 6264 |
rec_idx_start = rec_idx_end; |
| 6265 |
} |
| 6266 |
} |
| 6267 |
|
| 6268 |
void CleanupPvariantPosMergeContext(PvariantPosMergeContext* ppmcp) { |
| 6269 |
CswriteCloseCond(&ppmcp->pmc.css, ppmcp->pmc.cswritep); |
| 6270 |
} |
| 6271 |
|
| 6272 |
// This can actually deviate from pure concatenation: same-position variants |
| 6273 |
// are reordered by ID, and same-position same-ID variants are merged. The |
| 6274 |
// distinction from the general case is that we never need to have more than |
| 6275 |
// one .pvar + .pgen open for reading at a time. |
| 6276 |
PglErr PmergeConcat(const PmergeInfo* pmip, const SampleIdInfo* siip, const ChrInfo* cip, const PmergeInputFilesetLl* filesets, const char* missing_varid_match, const char* const* info_keys, const uint32_t* info_keys_htable, uint32_t sample_ct, FamCol fam_cols, uintptr_t fileset_ct, uint32_t psam_linebuf_capacity, uint32_t missing_varid_match_slen, uint32_t info_key_ct, uint32_t info_keys_htable_size, uint32_t info_conflict_present, char input_missing_geno_char, uint32_t max_thread_ct, SortMode sort_vars_mode, VaridTemplate* varid_templatep, VaridTemplate* varid_multi_templatep, VaridTemplate* varid_multi_nonsnp_templatep, char* outname, char* outname_end) { |
| 6277 |
// Don't need to reset bigstack at function end, since Pmerge() will do it. |
| 6278 |
const char* read_pgen_fname = nullptr; |
| 6279 |
const char* read_pvar_fname = nullptr; |
| 6280 |
PglErr reterr = kPglRetSuccess; |
| 6281 |
PvariantPosMergeContext ppmc; |
| 6282 |
PreinitPvariantPosMergeContext(&ppmc); |
| 6283 |
uintptr_t pvar_line_idx = 0; |
| 6284 |
TextStream pvar_txs; |
| 6285 |
PreinitTextStream(&pvar_txs); |
| 6286 |
PgenFileInfo pgfi; |
| 6287 |
MergeReader mr; |
| 6288 |
MergeWriter mw; |
| 6289 |
PreinitPgfi(&pgfi); |
| 6290 |
PreinitPgr(&mr.pgr); |
| 6291 |
PreinitSpgw(&mw.spgw); |
| 6292 |
{ |
| 6293 |
// 1. Scan .pgen headers, to determine appropriate write_gflags. |
| 6294 |
// 2. Initialize single-threaded .pgen writer. (Possible todo: |
| 6295 |
// support multithreaded writer when sufficient memory is available.) |
| 6296 |
// 3. Iterate through filesets: |
| 6297 |
// a. Scan .psam, save sample subset/order. |
| 6298 |
// b. Scan through .pvar and .pgen simultaneously. |
| 6299 |
uintptr_t write_variant_ct = 0; |
| 6300 |
uint32_t write_qual = 0; |
| 6301 |
uint32_t write_filter = 0; |
| 6302 |
uint32_t write_info = 0; |
| 6303 |
uint32_t write_cm = 0; |
| 6304 |
uintptr_t overflow_buf_size = 0; |
| 6305 |
uint32_t vrtype_8bit_needed = 0; |
| 6306 |
// 1 = all known, 2 = all provisional-REF, 3 = enough evidence for mixed |
| 6307 |
uint32_t nonref_flags_storage = 0; |
| 6308 |
|
| 6309 |
uint32_t read_max_allele_ct = 2; |
| 6310 |
uint32_t write_max_allele_ct = 2; |
| 6311 |
uint32_t max_single_pos_ct = 1; |
| 6312 |
uintptr_t max_single_pos_blen = 0; |
| 6313 |
uint32_t read_max_nonpass_filter_ct = 0; |
| 6314 |
const PmergeInputFilesetLl* filesets_iter = filesets; |
| 6315 |
for (uintptr_t fileset_idx = 0; fileset_idx != fileset_ct; ++fileset_idx) { |
| 6316 |
write_variant_ct += filesets_iter->write_nondoomed_variant_ct; |
| 6317 |
write_qual |= filesets_iter->nm_qual_exists; |
| 6318 |
write_filter |= filesets_iter->nm_filter_exists; |
| 6319 |
write_info |= filesets_iter->nm_info_exists; |
| 6320 |
write_cm |= filesets_iter->nz_cm_present; |
| 6321 |
if (overflow_buf_size < filesets_iter->max_pvar_line_blen) { |
| 6322 |
overflow_buf_size = filesets_iter->max_pvar_line_blen; |
| 6323 |
} |
| 6324 |
if (read_max_allele_ct < filesets_iter->read_max_allele_ct) { |
| 6325 |
read_max_allele_ct = filesets_iter->read_max_allele_ct; |
| 6326 |
} |
| 6327 |
if (write_max_allele_ct < filesets_iter->write_nondoomed_max_allele_ct) { |
| 6328 |
write_max_allele_ct = filesets_iter->write_nondoomed_max_allele_ct; |
| 6329 |
} |
| 6330 |
if (max_single_pos_ct < filesets_iter->max_single_pos_ct) { |
| 6331 |
max_single_pos_ct = filesets_iter->max_single_pos_ct; |
| 6332 |
} |
| 6333 |
if (max_single_pos_blen < filesets_iter->max_single_pos_blen) { |
| 6334 |
max_single_pos_blen = filesets_iter->max_single_pos_blen; |
| 6335 |
} |
| 6336 |
if (read_max_nonpass_filter_ct < filesets_iter->read_max_nonpass_filter_ct) { |
| 6337 |
read_max_nonpass_filter_ct = filesets_iter->read_max_nonpass_filter_ct; |
| 6338 |
} |
| 6339 |
vrtype_8bit_needed |= filesets_iter->vrtype_8bit_needed; |
| 6340 |
const uint32_t cur_nonref_flags_storage = filesets_iter->nonref_flags_storage; |
| 6341 |
if (!cur_nonref_flags_storage) { |
| 6342 |
nonref_flags_storage = 3; |
| 6343 |
} else { |
| 6344 |
nonref_flags_storage |= cur_nonref_flags_storage; |
| 6345 |
} |
| 6346 |
filesets_iter = filesets_iter->next; |
| 6347 |
} |
| 6348 |
if (unlikely(write_variant_ct > kPglMaxVariantCt)) { |
| 6349 |
logerrputs("Error: " PROG_NAME_STR " does not support more than 2^31 - 3 variants. We recommend using\nother software for very deep studies of small numbers of genomes.\n"); |
| 6350 |
goto PmergeConcat_ret_INCONSISTENT_INPUT; |
| 6351 |
} |
| 6352 |
if (unlikely(!write_variant_ct)) { |
| 6353 |
logerrputs("Error: All variants filtered out by --merge-max-alleles.\n"); |
| 6354 |
goto PmergeConcat_ret_INCONSISTENT_INPUT; |
| 6355 |
} |
| 6356 |
|
| 6357 |
// a few extra bytes for miscellaneous delimiters |
| 6358 |
overflow_buf_size += 32; |
| 6359 |
if (info_key_ct) { |
| 6360 |
// We'd rather not be forced to perform a bunch of write-buffer flushes |
| 6361 |
// at the end of each INFO Number=A or =R field, or when expanding a |
| 6362 |
// Number=<positive #> field when there's a conflict. |
| 6363 |
// Each INFO Number=A requires up to 2 * (n-2) extra bytes, and each INFO |
| 6364 |
// Number=R requires up to 2 * (n-1). |
| 6365 |
// Each INFO Number=k requires up to 2 * (k-1) extra bytes. |
| 6366 |
uint32_t info_ra_cts[2]; |
| 6367 |
info_ra_cts[0] = 0; // R |
| 6368 |
info_ra_cts[1] = 0; // A |
| 6369 |
uintptr_t num_m1_sum = 0; |
| 6370 |
for (uint32_t info_key_idx = 0; info_key_idx != info_key_ct; ++info_key_idx) { |
| 6371 |
const int32_t info_vtype = const_container_of(info_keys[info_key_idx], InfoVtype, key)->num; |
| 6372 |
if (!IsInfoVtypeARSkip(info_vtype)) { |
| 6373 |
if (info_vtype > 1) { |
| 6374 |
num_m1_sum += info_vtype - 1; |
| 6375 |
} |
| 6376 |
continue; |
| 6377 |
} |
| 6378 |
info_ra_cts[info_vtype - kInfoVtypeR] += 1; |
| 6379 |
} |
| 6380 |
const uintptr_t max_extra_cost = 2 * (info_ra_cts[1] * (write_max_allele_ct - 2) + info_ra_cts[0] * (write_max_allele_ct - 1) + num_m1_sum); |
| 6381 |
overflow_buf_size += max_extra_cost; |
| 6382 |
} |
| 6383 |
if (overflow_buf_size < kCompressStreamBlock) { |
| 6384 |
overflow_buf_size = kCompressStreamBlock; |
| 6385 |
} |
| 6386 |
overflow_buf_size += kCompressStreamBlock; |
| 6387 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".pvar"); |
| 6388 |
const uint32_t pvar_zst = (pmip->flags / kfPmergeOutputVzs) & 1; |
| 6389 |
if (pvar_zst) { |
| 6390 |
snprintf(&(outname_end[5]), kMaxOutfnameExtBlen - 5, ".zst"); |
| 6391 |
} |
| 6392 |
uintptr_t line_idx_body_start = 0; |
| 6393 |
reterr = InitPvariantPosMergeContext(pmip, outname, info_keys, info_keys_htable, &read_pvar_fname, &line_idx_body_start, write_qual, write_filter, write_info, write_cm, info_key_ct, info_keys_htable_size, info_conflict_present, sort_vars_mode, 0, 1, pvar_zst, overflow_buf_size, read_max_allele_ct, write_max_allele_ct, max_single_pos_ct, read_max_nonpass_filter_ct, &ppmc); |
| 6394 |
if (unlikely(reterr)) { |
| 6395 |
goto PmergeConcat_ret_1; |
| 6396 |
} |
| 6397 |
|
| 6398 |
ppmc.write_variant_ct = write_variant_ct; |
| 6399 |
if (write_max_allele_ct > 2) { |
| 6400 |
// bugfix (13 Apr 2021): forgot +1 |
| 6401 |
if (bigstack_alloc_w(write_variant_ct + 1, &ppmc.write_allele_idx_offsets)) { |
| 6402 |
goto PmergeConcat_ret_NOMEM; |
| 6403 |
} |
| 6404 |
ppmc.write_allele_idx_offsets[0] = 0; |
| 6405 |
} |
| 6406 |
const uint32_t write_variant_ctl = BitCtToWordCt(write_variant_ct); |
| 6407 |
if (nonref_flags_storage == 3) { |
| 6408 |
if (bigstack_calloc_w(write_variant_ctl, &ppmc.write_nonref_flags)) { |
| 6409 |
goto PmergeConcat_ret_NOMEM; |
| 6410 |
} |
| 6411 |
} |
| 6412 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".pgen"); |
| 6413 |
const PgenGlobalFlags write_gflags = vrtype_8bit_needed? (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent) : kfPgenGlobal0; |
| 6414 |
uintptr_t spgw_alloc_cacheline_ct; |
| 6415 |
uint32_t max_vrec_len; |
| 6416 |
// bugfix (1 Jun 2022): in multiallelic case, contents of |
| 6417 |
// write_allele_idx_offsets have not been initialized, and this triggered |
| 6418 |
// an assert-failure in debug builds or a write_max_allele_ct |
| 6419 |
// miscalculation otherwise (practically always a harmless overestimate) |
| 6420 |
reterr = SpgwInitPhase1(outname, nullptr, ppmc.write_nonref_flags, write_variant_ct, sample_ct, write_max_allele_ct, kPgenWriteBackwardSeek, write_gflags, nonref_flags_storage, &mw.spgw, &spgw_alloc_cacheline_ct, &max_vrec_len); |
| 6421 |
if (unlikely(reterr)) { |
| 6422 |
if (reterr == kPglRetOpenFail) { |
| 6423 |
logerrprintfww(kErrprintfFopen, outname, strerror(errno)); |
| 6424 |
} |
| 6425 |
goto PmergeConcat_ret_1; |
| 6426 |
} |
| 6427 |
const uint32_t sample_id_htable_size = GetHtableMinSize(sample_ct); |
| 6428 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 6429 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 6430 |
unsigned char* spgw_alloc; |
| 6431 |
uint32_t* sample_id_htable; |
| 6432 |
uint32_t* old_sample_idx_to_new_buf; |
| 6433 |
if (unlikely(bigstack_alloc_uc(spgw_alloc_cacheline_ct * kCacheline, &spgw_alloc) || |
| 6434 |
bigstack_alloc_u32(sample_id_htable_size, &sample_id_htable) || |
| 6435 |
bigstack_alloc_u32(sample_ct, &old_sample_idx_to_new_buf) || |
| 6436 |
bigstack_alloc_w(sample_ctl2, &mw.genovec))) { |
| 6437 |
goto PmergeConcat_ret_NOMEM; |
| 6438 |
} |
| 6439 |
SpgwInitPhase2(max_vrec_len, &mw.spgw, spgw_alloc); |
| 6440 |
mw.patch_01_set = nullptr; |
| 6441 |
mw.patch_01_vals = nullptr; |
| 6442 |
mw.patch_10_set = nullptr; |
| 6443 |
mw.patch_10_vals = nullptr; |
| 6444 |
if (write_max_allele_ct > 2) { |
| 6445 |
if (unlikely(bigstack_alloc_w(sample_ctl, &mw.patch_01_set) || |
| 6446 |
bigstack_alloc_ac(sample_ct, &mw.patch_01_vals) || |
| 6447 |
bigstack_alloc_w(sample_ctl, &mw.patch_10_set) || |
| 6448 |
bigstack_alloc_ac(2 * sample_ct, &mw.patch_10_vals) || |
| 6449 |
bigstack_alloc_ac(2 * sample_ct, &mw.wide_codes))) { |
| 6450 |
goto PmergeConcat_ret_NOMEM; |
| 6451 |
} |
| 6452 |
} |
| 6453 |
mw.phasepresent = nullptr; |
| 6454 |
mw.phaseinfo = nullptr; |
| 6455 |
mw.dosage_present = nullptr; |
| 6456 |
mw.dosage_main = nullptr; |
| 6457 |
mw.dphase_present = nullptr; |
| 6458 |
mw.dphase_delta = nullptr; |
| 6459 |
if (vrtype_8bit_needed) { |
| 6460 |
if (unlikely(bigstack_alloc_w(sample_ctl, &mw.phasepresent) || |
| 6461 |
bigstack_alloc_w(sample_ctl, &mw.phaseinfo) || |
| 6462 |
bigstack_alloc_w(sample_ctl, &mw.dosage_present) || |
| 6463 |
bigstack_alloc_dosage(sample_ct, &mw.dosage_main) || |
| 6464 |
bigstack_alloc_w(sample_ctl, &mw.dphase_present) || |
| 6465 |
bigstack_alloc_dphase(sample_ct, &mw.dphase_delta) || |
| 6466 |
bigstack_alloc_w(sample_ctl, &mw.phaseinfo_xor))) { |
| 6467 |
goto PmergeConcat_ret_NOMEM; |
| 6468 |
} |
| 6469 |
} |
| 6470 |
// pgv_readbuf reinitialized for each file we're reading from |
| 6471 |
if (unlikely(bigstack_alloc_w(sample_ctl, &mw.unlocked_set) || |
| 6472 |
bigstack_alloc_w(sample_ctl, &mw.unlocked_sample_span) || |
| 6473 |
bigstack_alloc_u32(sample_ct, &mw.clobber_sample_idx_to_new) || |
| 6474 |
bigstack_alloc_w(sample_ctl, &mw.mask_buf) || |
| 6475 |
BigstackAllocPgv(sample_ct, write_max_allele_ct > 2, write_gflags, &mw.pgv_midbuf))) { |
| 6476 |
goto PmergeConcat_ret_NOMEM; |
| 6477 |
} |
| 6478 |
mw.unlocked_missing_set = nullptr; |
| 6479 |
mw.clobber_sample_span = nullptr; |
| 6480 |
mw.unlocked_nonmissing_sample_span = nullptr; |
| 6481 |
if (pmip->merge_mode == kMergeModeNmMatch) { |
| 6482 |
if (unlikely(bigstack_alloc_w(sample_ctl, &mw.unlocked_missing_set) || |
| 6483 |
bigstack_alloc_w(sample_ctl, &mw.clobber_sample_span) || |
| 6484 |
bigstack_alloc_w(sample_ctl, &mw.unlocked_nonmissing_sample_span))) { |
| 6485 |
goto PmergeConcat_ret_NOMEM; |
| 6486 |
} |
| 6487 |
} |
| 6488 |
mw.merge_mode = pmip->merge_mode; |
| 6489 |
|
| 6490 |
InitXidHtable(siip, sample_ct, sample_id_htable_size, sample_id_htable, g_textbuf); |
| 6491 |
|
| 6492 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 6493 |
filesets_iter = filesets; |
| 6494 |
logputs("Concatenating... "); |
| 6495 |
printf("0/%" PRIuPTR " variant%s complete.", write_variant_ct, (write_variant_ct == 1)? "" : "s"); |
| 6496 |
fflush(stdout); |
| 6497 |
for (uintptr_t fileset_idx = 0; fileset_idx != fileset_ct; ++fileset_idx, filesets_iter = filesets_iter->next) { |
| 6498 |
if (!filesets_iter->write_nondoomed_variant_ct) { |
| 6499 |
continue; |
| 6500 |
} |
| 6501 |
BigstackReset(bigstack_mark); |
| 6502 |
const uint32_t read_sample_ct = filesets_iter->read_sample_ct; |
| 6503 |
const uint32_t read_sample_ctl = BitCtToWordCt(read_sample_ct); |
| 6504 |
uint32_t* read_cumulative_popcounts; |
| 6505 |
if (unlikely(bigstack_alloc_w(read_sample_ctl, &mr.sample_include) || |
| 6506 |
bigstack_alloc_u32(read_sample_ctl, &read_cumulative_popcounts) || |
| 6507 |
bigstack_alloc_w(sample_ctl, &mr.sample_span))) { |
| 6508 |
goto PmergeConcat_ret_NOMEM; |
| 6509 |
} |
| 6510 |
mr.old_sample_idx_to_new = old_sample_idx_to_new_buf; |
| 6511 |
uint32_t cur_write_sample_ct; |
| 6512 |
reterr = ScrapeSampleOrder(filesets_iter->psam_fname, siip, sample_id_htable, read_sample_ct, sample_ct, sample_id_htable_size, fam_cols, psam_linebuf_capacity, max_thread_ct, mr.old_sample_idx_to_new, &mr.sample_idx_increasing, &cur_write_sample_ct, mr.sample_include, mr.sample_span); |
| 6513 |
if (unlikely(reterr)) { |
| 6514 |
goto PmergeConcat_ret_1; |
| 6515 |
} |
| 6516 |
FillCumulativePopcounts(mr.sample_include, read_sample_ctl, read_cumulative_popcounts); |
| 6517 |
if (mr.sample_idx_increasing && (cur_write_sample_ct == sample_ct)) { |
| 6518 |
mr.sample_idx_increasing = 2; |
| 6519 |
} |
| 6520 |
mr.sample_ct = cur_write_sample_ct; |
| 6521 |
|
| 6522 |
read_pgen_fname = filesets_iter->pgen_fname; |
| 6523 |
const uint32_t read_variant_ct = filesets_iter->read_variant_ct; |
| 6524 |
PgenHeaderCtrl header_ctrl; |
| 6525 |
uintptr_t cur_alloc_cacheline_ct; |
| 6526 |
reterr = PgfiInitPhase1(read_pgen_fname, nullptr, read_variant_ct, read_sample_ct, &header_ctrl, &pgfi, &cur_alloc_cacheline_ct, g_logbuf); |
| 6527 |
if (unlikely(reterr)) { |
| 6528 |
if (reterr == kPglRetInconsistentInput) { |
| 6529 |
// .pgen was not checked for consistency with .pvar on the first |
| 6530 |
// pass. |
| 6531 |
logputs("\n"); |
| 6532 |
WordWrapB(0); |
| 6533 |
logerrputsb(); |
| 6534 |
goto PmergeConcat_ret_1; |
| 6535 |
} |
| 6536 |
goto PmergeConcat_ret_PGEN_REWIND_FAIL_N; |
| 6537 |
} |
| 6538 |
unsigned char* pgfi_alloc; |
| 6539 |
if (unlikely(bigstack_alloc_uc(cur_alloc_cacheline_ct * kCacheline, &pgfi_alloc))) { |
| 6540 |
goto PmergeConcat_ret_NOMEM; |
| 6541 |
} |
| 6542 |
if ((header_ctrl & 192) == 192) { |
| 6543 |
if (unlikely(bigstack_alloc_w(BitCtToWordCt(read_variant_ct), &pgfi.nonref_flags))) { |
| 6544 |
goto PmergeConcat_ret_NOMEM; |
| 6545 |
} |
| 6546 |
} |
| 6547 |
read_pvar_fname = filesets_iter->pvar_fname; |
| 6548 |
if (filesets_iter->read_max_allele_ct > 2) { |
| 6549 |
if (bigstack_alloc_w(read_variant_ct + 1, &pgfi.allele_idx_offsets)) { |
| 6550 |
goto PmergeConcat_ret_NOMEM; |
| 6551 |
} |
| 6552 |
pgfi.allele_idx_offsets[0] = 0; |
| 6553 |
pgfi.max_allele_ct = filesets_iter->read_max_allele_ct; |
| 6554 |
} |
| 6555 |
uint32_t max_vrec_width; |
| 6556 |
reterr = PgfiInitPhase2(header_ctrl, 0, 0, 0, 0, read_variant_ct, &max_vrec_width, &pgfi, pgfi_alloc, &cur_alloc_cacheline_ct, g_logbuf); |
| 6557 |
if (unlikely(reterr)) { |
| 6558 |
logputs("\n"); |
| 6559 |
WordWrapB(0); |
| 6560 |
logerrputsb(); |
| 6561 |
goto PmergeConcat_ret_1; |
| 6562 |
} |
| 6563 |
unsigned char* pgr_alloc; |
| 6564 |
if (unlikely(bigstack_alloc_uc(cur_alloc_cacheline_ct * kCacheline, &pgr_alloc))) { |
| 6565 |
goto PmergeConcat_ret_NOMEM; |
| 6566 |
} |
| 6567 |
reterr = PgrInit(read_pgen_fname, max_vrec_width, &pgfi, &mr.pgr, pgr_alloc); |
| 6568 |
if (unlikely(reterr)) { |
| 6569 |
goto PmergeConcat_ret_PGEN_REWIND_FAIL_N; |
| 6570 |
} |
| 6571 |
PgrSetSampleSubsetIndex(read_cumulative_popcounts, &mr.pgr, &mr.pssi); |
| 6572 |
// Must check write_max_allele_ct instead of just whether the input file |
| 6573 |
// has multiallelic variants, since we may need to rotate a biallelic |
| 6574 |
// variant into a "multiallelic variant" in these buffers. |
| 6575 |
if (unlikely(BigstackAllocPgv(read_sample_ct, write_max_allele_ct > 2, write_gflags, &mw.pgv_readbuf))) { |
| 6576 |
goto PmergeConcat_ret_NOMEM; |
| 6577 |
} |
| 6578 |
reterr = InitTextStream(read_pvar_fname, MAXV(filesets_iter->max_pvar_line_blen, kDecompressMinBlen), 1, &pvar_txs); |
| 6579 |
if (unlikely(reterr)) { |
| 6580 |
goto PmergeConcat_ret_PVAR_TSTREAM_REWIND_FAIL_N; |
| 6581 |
} |
| 6582 |
char* line_start = TextLineEnd(&pvar_txs); |
| 6583 |
for (pvar_line_idx = 1; ; ++pvar_line_idx) { |
| 6584 |
if (unlikely(!TextGetUnsafe2(&pvar_txs, &line_start))) { |
| 6585 |
reterr = TextStreamRawErrcode(&pvar_txs); |
| 6586 |
goto PmergeConcat_ret_PVAR_TSTREAM_REWIND_FAIL_N; |
| 6587 |
} |
| 6588 |
if ((line_start[0] != '#') || tokequal_k(line_start, "#CHROM")) { |
| 6589 |
break; |
| 6590 |
} |
| 6591 |
line_start = AdvPastDelim(line_start, '\n'); |
| 6592 |
} |
| 6593 |
uint32_t col_skips[8]; |
| 6594 |
uint32_t col_types[8]; |
| 6595 |
const uint32_t read_qual = filesets_iter->nm_qual_exists; |
| 6596 |
const uint32_t read_filter = filesets_iter->nm_filter_exists; |
| 6597 |
const uint32_t read_info_pr = filesets_iter->pvar_info_pr_exists; |
| 6598 |
const uint32_t read_info = read_info_pr | filesets_iter->nm_info_exists; |
| 6599 |
const uint32_t pgen_pr_status_base = 2 * read_info_pr + (filesets_iter->nonref_flags_storage == 2); |
| 6600 |
const uint32_t read_cm = filesets_iter->nz_cm_present; |
| 6601 |
uint32_t relevant_postchr_col_ct; |
| 6602 |
if (line_start[0] == '#') { |
| 6603 |
char* token_end = &(line_start[6]); |
| 6604 |
relevant_postchr_col_ct = 0; |
| 6605 |
for (uint32_t col_idx = 1; ; ++col_idx) { |
| 6606 |
char* token_start = FirstNonTspace(token_end); |
| 6607 |
if (IsEolnKns(*token_start)) { |
| 6608 |
break; |
| 6609 |
} |
| 6610 |
token_end = CurTokenEnd(token_start); |
| 6611 |
const uint32_t token_slen = token_end - token_start; |
| 6612 |
uint32_t cur_col_type; |
| 6613 |
if (token_slen <= 3) { |
| 6614 |
if (token_slen == 3) { |
| 6615 |
if (memequal_sk(token_start, "POS")) { |
| 6616 |
cur_col_type = 0; |
| 6617 |
} else if (memequal_sk(token_start, "REF")) { |
| 6618 |
cur_col_type = 2; |
| 6619 |
} else if (memequal_sk(token_start, "ALT")) { |
| 6620 |
cur_col_type = 3; |
| 6621 |
} else { |
| 6622 |
continue; |
| 6623 |
} |
| 6624 |
} else if (token_slen == 2) { |
| 6625 |
if (memequal_sk(token_start, "ID")) { |
| 6626 |
cur_col_type = 1; |
| 6627 |
} else if (memequal_sk(token_start, "CM")) { |
| 6628 |
if (!read_cm) { |
| 6629 |
continue; |
| 6630 |
} |
| 6631 |
cur_col_type = 7; |
| 6632 |
} else { |
| 6633 |
continue; |
| 6634 |
} |
| 6635 |
} else { |
| 6636 |
continue; |
| 6637 |
} |
| 6638 |
} else if (strequal_k(token_start, "QUAL", token_slen)) { |
| 6639 |
if (!read_qual) { |
| 6640 |
continue; |
| 6641 |
} |
| 6642 |
cur_col_type = 4; |
| 6643 |
} else if (strequal_k(token_start, "INFO", token_slen)) { |
| 6644 |
if (!read_info) { |
| 6645 |
continue; |
| 6646 |
} |
| 6647 |
cur_col_type = 6; |
| 6648 |
} else if (token_slen == 6) { |
| 6649 |
if (memequal_sk(token_start, "FILTER")) { |
| 6650 |
if (!read_filter) { |
| 6651 |
continue; |
| 6652 |
} |
| 6653 |
cur_col_type = 5; |
| 6654 |
} else if (memequal_sk(token_start, "FORMAT")) { |
| 6655 |
break; |
| 6656 |
} else { |
| 6657 |
continue; |
| 6658 |
} |
| 6659 |
} else { |
| 6660 |
continue; |
| 6661 |
} |
| 6662 |
col_skips[relevant_postchr_col_ct] = col_idx; |
| 6663 |
col_types[relevant_postchr_col_ct++] = cur_col_type; |
| 6664 |
} |
| 6665 |
for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) { |
| 6666 |
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1]; |
| 6667 |
} |
| 6668 |
line_start = AdvPastDelim(token_end, '\n'); |
| 6669 |
++pvar_line_idx; |
| 6670 |
} else { |
| 6671 |
col_skips[0] = 1; |
| 6672 |
col_skips[1] = 1; |
| 6673 |
col_skips[2] = 1; |
| 6674 |
col_skips[3] = 1; |
| 6675 |
col_types[0] = 1; |
| 6676 |
if (!read_cm) { |
| 6677 |
relevant_postchr_col_ct = 4; |
| 6678 |
col_types[1] = 0; |
| 6679 |
col_types[2] = 3; |
| 6680 |
col_types[3] = 2; |
| 6681 |
const char* sixth_col_start = NextTokenMult(line_start, 5); |
| 6682 |
if (sixth_col_start) { |
| 6683 |
// bugfix (25 Mar 2021) |
| 6684 |
col_skips[1] = 2; |
| 6685 |
} |
| 6686 |
} else { |
| 6687 |
relevant_postchr_col_ct = 5; |
| 6688 |
col_skips[4] = 1; |
| 6689 |
col_types[1] = 7; |
| 6690 |
col_types[2] = 0; |
| 6691 |
col_types[3] = 3; |
| 6692 |
col_types[4] = 2; |
| 6693 |
} |
| 6694 |
} |
| 6695 |
|
| 6696 |
max_single_pos_ct = filesets_iter->max_single_pos_ct; |
| 6697 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 6698 |
char* cur_pos_readbuf; |
| 6699 |
SamePosPvarRecord** same_pos_records; |
| 6700 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &ppmc.pmc.chr_buf) || |
| 6701 |
bigstack_alloc_c(max_single_pos_blen + (sizeof(SamePosPvarRecord) + 1) * max_single_pos_ct, &cur_pos_readbuf) || |
| 6702 |
BIGSTACK_ALLOC_X(SamePosPvarRecord*, max_single_pos_ct, &same_pos_records))) { |
| 6703 |
goto PmergeConcat_ret_NOMEM; |
| 6704 |
} |
| 6705 |
if (varid_templatep) { |
| 6706 |
varid_templatep->chr_output_name_buf = ppmc.pmc.chr_buf; |
| 6707 |
if (varid_multi_templatep) { |
| 6708 |
varid_multi_templatep->chr_output_name_buf = ppmc.pmc.chr_buf; |
| 6709 |
} |
| 6710 |
if (varid_multi_nonsnp_templatep) { |
| 6711 |
varid_multi_nonsnp_templatep->chr_output_name_buf = ppmc.pmc.chr_buf; |
| 6712 |
} |
| 6713 |
} |
| 6714 |
line_idx_body_start = pvar_line_idx; |
| 6715 |
char* cur_pos_readbuf_iter = cur_pos_readbuf; |
| 6716 |
uint32_t cur_single_pos_ct = 0; |
| 6717 |
uint32_t prev_chr_idx = UINT32_MAX; |
| 6718 |
int32_t prev_bp = 0; |
| 6719 |
for (uint32_t read_variant_idx = 0; read_variant_idx != read_variant_ct; ++read_variant_idx) { |
| 6720 |
if (unlikely(!TextGetUnsafe2(&pvar_txs, &line_start))) { |
| 6721 |
reterr = TextStreamRawErrcode(&pvar_txs); |
| 6722 |
goto PmergeConcat_ret_PVAR_TSTREAM_REWIND_FAIL_N; |
| 6723 |
} |
| 6724 |
char* chr_token_end = CurTokenEnd(line_start); |
| 6725 |
const uint32_t chr_idx = GetChrCodeCounted(cip, chr_token_end - line_start, line_start); |
| 6726 |
assert(chr_idx < UINT32_MAXM1); |
| 6727 |
if (!IsSet(cip->chr_mask, chr_idx)) { |
| 6728 |
if (pgfi.allele_idx_offsets) { |
| 6729 |
// No need to actually parse ALT: we only need |
| 6730 |
// (pgfi.allele_idx_offsets[x+1] - pgfi.allele_idx_offsets[x]) to |
| 6731 |
// account for extra ALT alleles for variants we're properly |
| 6732 |
// reading. We may still process the *biallelic* portion of |
| 6733 |
// variants we aren't explicitly reading (due to how LD-compression |
| 6734 |
// works), so we defensively set the allele count to 2. |
| 6735 |
pgfi.allele_idx_offsets[read_variant_idx + 1] = pgfi.allele_idx_offsets[read_variant_idx] + 2; |
| 6736 |
} |
| 6737 |
line_start = AdvPastDelim(chr_token_end, '\n'); |
| 6738 |
continue; |
| 6739 |
} |
| 6740 |
if (chr_idx != prev_chr_idx) { |
| 6741 |
reterr = ConcatPvariantPos(prev_bp, cur_single_pos_ct, &ppmc, same_pos_records, &mr, &mw); |
| 6742 |
if (unlikely(reterr)) { |
| 6743 |
goto PmergeConcat_ret_N; |
| 6744 |
} |
| 6745 |
cur_pos_readbuf_iter = cur_pos_readbuf; |
| 6746 |
cur_single_pos_ct = 0; |
| 6747 |
char* chr_name_end = chrtoa(cip, chr_idx, ppmc.pmc.chr_buf); |
| 6748 |
*chr_name_end = '\0'; |
| 6749 |
const uint32_t chr_slen = chr_name_end - ppmc.pmc.chr_buf; |
| 6750 |
ppmc.pmc.chr_slen = chr_slen; |
| 6751 |
if (varid_templatep) { |
| 6752 |
const int32_t chr_slen_delta = chr_slen - varid_templatep->chr_slen; |
| 6753 |
varid_templatep->chr_slen = chr_slen; |
| 6754 |
varid_templatep->base_len += chr_slen_delta; |
| 6755 |
if (varid_multi_templatep) { |
| 6756 |
varid_multi_templatep->chr_slen = chr_slen; |
| 6757 |
varid_multi_templatep->base_len += chr_slen_delta; |
| 6758 |
} |
| 6759 |
if (varid_multi_nonsnp_templatep) { |
| 6760 |
varid_multi_nonsnp_templatep->chr_slen = chr_slen; |
| 6761 |
varid_multi_nonsnp_templatep->base_len += chr_slen_delta; |
| 6762 |
} |
| 6763 |
} |
| 6764 |
prev_chr_idx = chr_idx; |
| 6765 |
prev_bp = -1; |
| 6766 |
} |
| 6767 |
char* token_ptrs[8]; |
| 6768 |
uint32_t token_slens[8]; |
| 6769 |
char* line_iter = TokenLex(chr_token_end, col_types, col_skips, relevant_postchr_col_ct, token_ptrs, token_slens); |
| 6770 |
if (unlikely(!line_iter)) { |
| 6771 |
goto PmergeConcat_ret_PVAR_REWIND_FAIL_N; |
| 6772 |
} |
| 6773 |
line_start = AdvPastDelim(line_iter, '\n'); |
| 6774 |
int32_t cur_bp; |
| 6775 |
if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp))) { |
| 6776 |
goto PmergeConcat_ret_PVAR_REWIND_FAIL_N; |
| 6777 |
} |
| 6778 |
if (cur_bp < 0) { |
| 6779 |
if (pgfi.allele_idx_offsets) { |
| 6780 |
pgfi.allele_idx_offsets[read_variant_idx + 1] = pgfi.allele_idx_offsets[read_variant_idx] + 2; |
| 6781 |
} |
| 6782 |
continue; |
| 6783 |
} |
| 6784 |
if (cur_bp > prev_bp) { |
| 6785 |
reterr = ConcatPvariantPos(prev_bp, cur_single_pos_ct, &ppmc, same_pos_records, &mr, &mw); |
| 6786 |
if (unlikely(reterr)) { |
| 6787 |
goto PmergeConcat_ret_N; |
| 6788 |
} |
| 6789 |
cur_pos_readbuf_iter = cur_pos_readbuf; |
| 6790 |
cur_single_pos_ct = 0; |
| 6791 |
prev_bp = cur_bp; |
| 6792 |
} |
| 6793 |
SamePosPvarRecord* cur_record = R_CAST(SamePosPvarRecord*, cur_pos_readbuf_iter); |
| 6794 |
uint32_t* other_field_offsets = cur_record->other_field_offsets; |
| 6795 |
cur_record->secondary_key = read_variant_idx; |
| 6796 |
uint32_t variant_id_slen = token_slens[1]; |
| 6797 |
char* cur_variant_id_start = cur_record->variant_id; |
| 6798 |
char* ref_start = token_ptrs[2]; |
| 6799 |
const uint32_t ref_slen = token_slens[2]; |
| 6800 |
char* alt_start = token_ptrs[3]; |
| 6801 |
const uint32_t alt_slen = token_slens[3]; |
| 6802 |
const uint32_t extra_alt_ct = CountByte(alt_start, ',', alt_slen); |
| 6803 |
if (varid_templatep && ((!missing_varid_match_slen) || ((variant_id_slen == missing_varid_match_slen) && memequal(token_ptrs[1], missing_varid_match, missing_varid_match_slen)))) { |
| 6804 |
const VaridTemplate* cur_varid_templatep = varid_templatep; |
| 6805 |
if (extra_alt_ct && (varid_multi_templatep || varid_multi_nonsnp_templatep)) { |
| 6806 |
if (varid_multi_templatep) { |
| 6807 |
cur_varid_templatep = varid_multi_templatep; |
| 6808 |
} |
| 6809 |
if (varid_multi_nonsnp_templatep) { |
| 6810 |
if ((ref_slen > 1) || (alt_slen != 2 * extra_alt_ct + 1)) { |
| 6811 |
cur_varid_templatep = varid_multi_nonsnp_templatep; |
| 6812 |
} |
| 6813 |
} |
| 6814 |
} |
| 6815 |
// already scanned, shouldn't be possible for this to fail |
| 6816 |
uint32_t discard; |
| 6817 |
cur_pos_readbuf_iter = VaridTemplateWrite(cur_varid_templatep, ref_start, alt_start, cur_bp, ref_slen, extra_alt_ct, alt_slen, &discard, cur_variant_id_start); |
| 6818 |
variant_id_slen = cur_pos_readbuf_iter - cur_variant_id_start; |
| 6819 |
} else { |
| 6820 |
cur_pos_readbuf_iter = memcpya(cur_variant_id_start, token_ptrs[1], variant_id_slen); |
| 6821 |
} |
| 6822 |
*cur_pos_readbuf_iter++ = '\0'; |
| 6823 |
other_field_offsets[0] = variant_id_slen + 1; |
| 6824 |
|
| 6825 |
if ((ref_start[0] != input_missing_geno_char) || (ref_slen != 1)) { |
| 6826 |
cur_pos_readbuf_iter = memcpya(cur_pos_readbuf_iter, ref_start, ref_slen); |
| 6827 |
} else { |
| 6828 |
*cur_pos_readbuf_iter++ = '.'; |
| 6829 |
} |
| 6830 |
*cur_pos_readbuf_iter++ = '\0'; |
| 6831 |
other_field_offsets[1] = cur_pos_readbuf_iter - cur_variant_id_start; |
| 6832 |
|
| 6833 |
if ((alt_start[0] != input_missing_geno_char) || (alt_slen != 1)) { |
| 6834 |
cur_pos_readbuf_iter = memcpya(cur_pos_readbuf_iter, alt_start, alt_slen); |
| 6835 |
} else { |
| 6836 |
*cur_pos_readbuf_iter++ = '.'; |
| 6837 |
} |
| 6838 |
*cur_pos_readbuf_iter++ = '\0'; |
| 6839 |
other_field_offsets[2] = cur_pos_readbuf_iter - cur_variant_id_start; |
| 6840 |
cur_record->allele_ct = 2 + extra_alt_ct; |
| 6841 |
if (pgfi.allele_idx_offsets) { |
| 6842 |
pgfi.allele_idx_offsets[read_variant_idx + 1] = pgfi.allele_idx_offsets[read_variant_idx] + 2 + extra_alt_ct; |
| 6843 |
} |
| 6844 |
|
| 6845 |
uint32_t pgen_pr_status = pgen_pr_status_base; |
| 6846 |
if (pgfi.nonref_flags) { |
| 6847 |
pgen_pr_status |= IsSet(pgfi.nonref_flags, read_variant_idx); |
| 6848 |
} |
| 6849 |
cur_record->pgen_pr_status = pgen_pr_status; |
| 6850 |
|
| 6851 |
if (read_qual) { |
| 6852 |
cur_pos_readbuf_iter = memcpyax(cur_pos_readbuf_iter, token_ptrs[4], token_slens[4], '\0'); |
| 6853 |
} |
| 6854 |
other_field_offsets[3] = cur_pos_readbuf_iter - cur_variant_id_start; |
| 6855 |
|
| 6856 |
if (read_filter) { |
| 6857 |
cur_pos_readbuf_iter = memcpyax(cur_pos_readbuf_iter, token_ptrs[5], token_slens[5], '\0'); |
| 6858 |
} |
| 6859 |
other_field_offsets[4] = cur_pos_readbuf_iter - cur_variant_id_start; |
| 6860 |
|
| 6861 |
if (read_info) { |
| 6862 |
cur_pos_readbuf_iter = memcpyax(cur_pos_readbuf_iter, token_ptrs[6], token_slens[6], '\0'); |
| 6863 |
} |
| 6864 |
other_field_offsets[5] = cur_pos_readbuf_iter - cur_variant_id_start; |
| 6865 |
|
| 6866 |
if (read_cm) { |
| 6867 |
cur_pos_readbuf_iter = memcpya(cur_pos_readbuf_iter, token_ptrs[7], token_slens[7]); |
| 6868 |
} |
| 6869 |
*cur_pos_readbuf_iter++ = '\0'; |
| 6870 |
// could align up to 8-byte boundary? |
| 6871 |
assert(cur_pos_readbuf_iter <= R_CAST(char*, same_pos_records)); |
| 6872 |
|
| 6873 |
same_pos_records[cur_single_pos_ct] = cur_record; |
| 6874 |
++cur_single_pos_ct; |
| 6875 |
} |
| 6876 |
reterr = ConcatPvariantPos(prev_bp, cur_single_pos_ct, &ppmc, same_pos_records, &mr, &mw); |
| 6877 |
if (unlikely(reterr)) { |
| 6878 |
goto PmergeConcat_ret_N; |
| 6879 |
} |
| 6880 |
// bugfix (14 Apr 2021): forgot to close .pgen |
| 6881 |
if (unlikely(CleanupTextStream2(read_pvar_fname, &pvar_txs, &reterr) || |
| 6882 |
CleanupPgr2(read_pgen_fname, &mr.pgr, &reterr) || |
| 6883 |
CleanupPgfi2(read_pgen_fname, &pgfi, &reterr))) { |
| 6884 |
goto PmergeConcat_ret_N; |
| 6885 |
} |
| 6886 |
} |
| 6887 |
reterr = SpgwFinish(&mw.spgw); |
| 6888 |
if (unlikely(reterr)) { |
| 6889 |
goto PmergeConcat_ret_1; |
| 6890 |
} |
| 6891 |
if (unlikely(CswriteCloseNull(&ppmc.pmc.css, ppmc.pmc.cswritep))) { |
| 6892 |
goto PmergeConcat_ret_WRITE_FAIL_N; |
| 6893 |
} |
| 6894 |
fputs("\rConcatenating... ", stdout); |
| 6895 |
logprintf("%" PRIuPTR "/%" PRIuPTR " variant%s complete.\n", write_variant_ct, write_variant_ct, (write_variant_ct == 1)? "" : "s"); |
| 6896 |
*outname_end = '\0'; |
| 6897 |
logprintfww("Results written to %s.pgen + %s.pvar%s .\n", outname, outname, pvar_zst? ".zst" : ""); |
| 6898 |
} |
| 6899 |
while (0) { |
| 6900 |
PmergeConcat_ret_NOMEM: |
| 6901 |
reterr = kPglRetNomem; |
| 6902 |
break; |
| 6903 |
PmergeConcat_ret_PVAR_TSTREAM_REWIND_FAIL_N: |
| 6904 |
logputs("\n"); |
| 6905 |
TextStreamErrPrintRewind(read_pvar_fname, &pvar_txs, &reterr); |
| 6906 |
break; |
| 6907 |
PmergeConcat_ret_PVAR_REWIND_FAIL_N: |
| 6908 |
logputs("\n"); |
| 6909 |
logerrprintfww(kErrprintfRewind, read_pvar_fname); |
| 6910 |
reterr = kPglRetRewindFail; |
| 6911 |
break; |
| 6912 |
PmergeConcat_ret_PGEN_REWIND_FAIL_N: |
| 6913 |
logputs("\n"); |
| 6914 |
logerrprintfww(kErrprintfRewind, read_pgen_fname); |
| 6915 |
reterr = kPglRetRewindFail; |
| 6916 |
break; |
| 6917 |
PmergeConcat_ret_WRITE_FAIL_N: |
| 6918 |
logputs("\n"); |
| 6919 |
reterr = kPglRetWriteFail; |
| 6920 |
break; |
| 6921 |
PmergeConcat_ret_INCONSISTENT_INPUT: |
| 6922 |
reterr = kPglRetInconsistentInput; |
| 6923 |
break; |
| 6924 |
PmergeConcat_ret_N: |
| 6925 |
logputs("\n"); |
| 6926 |
break; |
| 6927 |
} |
| 6928 |
PmergeConcat_ret_1: |
| 6929 |
CleanupPvariantPosMergeContext(&ppmc); |
| 6930 |
CleanupTextStream2(read_pvar_fname, &pvar_txs, &reterr); |
| 6931 |
CleanupSpgw(&mw.spgw, &reterr); |
| 6932 |
CleanupPgr2(read_pgen_fname, &mr.pgr, &reterr); |
| 6933 |
CleanupPgfi2(read_pgen_fname, &pgfi, &reterr); |
| 6934 |
return reterr; |
| 6935 |
} |
| 6936 |
|
| 6937 |
// Performs one pass of a possibly-multipass merge. |
| 6938 |
// *input_filesets_ptr is advanced as files are processed, and temporary files |
| 6939 |
// are deleted while this happens. |
| 6940 |
// next_filesets is left as nullptr on the last pass. |
| 6941 |
PglErr PmergePass(__attribute__((unused)) const PmergeInfo* pmip, __attribute__((unused)) const SampleIdInfo* siip, __attribute__((unused)) const ChrInfo* cip, __attribute__((unused)) const char* const* info_keys, __attribute__((unused)) const uint32_t* info_keys_htable, __attribute__((unused)) uint32_t pass_idx, __attribute__((unused)) uint32_t sample_ct, __attribute__((unused)) FamCol fam_cols, uintptr_t fileset_ct, __attribute__((unused)) uint32_t psam_linebuf_capacity, __attribute__((unused)) uint32_t info_key_ct, __attribute__((unused)) uint32_t info_keys_htable_size, __attribute__((unused)) uint32_t info_conflict_present, __attribute__((unused)) uint32_t max_thread_ct, __attribute__((unused)) SortMode sort_vars_mode, __attribute__((unused)) char* outname, __attribute__((unused)) char* outname_end, __attribute__((unused)) PmergeInputFilesetLl** input_filesets_ptr, __attribute__((unused)) PmergeInputFilesetLl** next_filesets_ptr, __attribute__((unused)) uint32_t* next_fileset_ctp) { |
| 6942 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 6943 |
PglErr reterr = kPglRetSuccess; |
| 6944 |
{ |
| 6945 |
// 1. Determine how many input filesets from the front of the list can be |
| 6946 |
// processed in the current loop iteration. It's bounded by |
| 6947 |
// kMaxOpenFiles and workspace memory. The workspace memory computation |
| 6948 |
// is annoying. |
| 6949 |
// - If there's only one input fileset left, just move that entry to the |
| 6950 |
// tail of next_filesets, and exit. |
| 6951 |
// - If all input filesets can be merged at once, write to the final |
| 6952 |
// output filenames, and leave next_filesets as nullptr. |
| 6953 |
// - If we don't obviously have enough memory to even merge the next two |
| 6954 |
// filesets... could either error out, or speculatively continue with |
| 6955 |
// two depending on how much we might overestimate memory usage. |
| 6956 |
// 2. Incremental-merge them. |
| 6957 |
// 3. Return to step 1 if input fileset(s) remain. |
| 6958 |
uintptr_t input_filesets_remaining = fileset_ct; |
| 6959 |
PmergeInputFilesetLl** next_filesets_end_ptr = next_filesets_ptr; |
| 6960 |
do { |
| 6961 |
logerrputs("Error: Non-concatenating --pmerge[-list] is under development.\n"); |
| 6962 |
reterr = kPglRetNotYetSupported; |
| 6963 |
goto PmergePass_ret_1; |
| 6964 |
} while (input_filesets_remaining > 1); |
| 6965 |
if (input_filesets_remaining == 1) { |
| 6966 |
*next_filesets_end_ptr = *input_filesets_ptr; |
| 6967 |
*input_filesets_ptr = nullptr; |
| 6968 |
} |
| 6969 |
} |
| 6970 |
while (0) { |
| 6971 |
} |
| 6972 |
PmergePass_ret_1: |
| 6973 |
BigstackReset(bigstack_mark); |
| 6974 |
return reterr; |
| 6975 |
} |
| 6976 |
|
| 6977 |
PglErr Pmerge(const PmergeInfo* pmip, const char* sample_sort_fname, const char* missing_catname, const char* varid_template_str, const char* varid_multi_template_str, const char* varid_multi_nonsnp_template_str, const char* missing_varid_match, MiscFlags misc_flags, SortMode sample_sort_mode, FamCol fam_cols, int32_t missing_pheno, uint32_t new_variant_id_max_allele_slen, char input_missing_geno_char, uint32_t max_thread_ct, SortMode sort_vars_mode, char* pgenname, char* psamname, char* pvarname, char* outname, char* outname_end, ChrInfo* cip) { |
| 6978 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 6979 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 6980 |
|
| 6981 |
// nodes and filenames are heap-allocated, not just first_varid/last_varid |
| 6982 |
PmergeInputFilesetLl* input_filesets = nullptr; |
| 6983 |
PmergeInputFilesetLl* next_filesets = nullptr; |
| 6984 |
|
| 6985 |
PglErr reterr = kPglRetSuccess; |
| 6986 |
{ |
| 6987 |
// 1. Construct/load fileset list. |
| 6988 |
// 2. Merge .psam files. |
| 6989 |
// 3. Global .pvar scan, to determine merged header, chromosome sort order, |
| 6990 |
// and track first/last position in each fileset. |
| 6991 |
// 4. If filesets cover disjoint positions, handle this as a concatenation |
| 6992 |
// job (or error out on --variant-inner-join). |
| 6993 |
// 5. Otherwise, perform general-purpose incremental merge. |
| 6994 |
uintptr_t fileset_ct = 2; |
| 6995 |
{ |
| 6996 |
PmergeInputFilesetLl** filesets_endp = &input_filesets; |
| 6997 |
if (pgenname[0]) { |
| 6998 |
PmergeInputFilesetLl* cur_entry = AllocFilesetLlEntry(&filesets_endp); |
| 6999 |
if (unlikely(!cur_entry)) { |
| 7000 |
goto Pmerge_ret_NOMEM; |
| 7001 |
} |
| 7002 |
cur_entry->is_temporary = 0; |
| 7003 |
const uint32_t pgen_fname_blen = strlen(pgenname) + 1; |
| 7004 |
const uint32_t pvar_fname_blen = strlen(pvarname) + 1; |
| 7005 |
const uint32_t psam_fname_blen = strlen(psamname) + 1; |
| 7006 |
char* fname_iter; |
| 7007 |
if (unlikely(bigstack_end_alloc_c(pgen_fname_blen + pvar_fname_blen + psam_fname_blen, &fname_iter))) { |
| 7008 |
goto Pmerge_ret_NOMEM; |
| 7009 |
} |
| 7010 |
cur_entry->pgen_fname = fname_iter; |
| 7011 |
fname_iter = memcpya(fname_iter, pgenname, pgen_fname_blen); |
| 7012 |
cur_entry->pvar_fname = fname_iter; |
| 7013 |
fname_iter = memcpya(fname_iter, pvarname, pvar_fname_blen); |
| 7014 |
cur_entry->psam_fname = fname_iter; |
| 7015 |
memcpy(fname_iter, psamname, psam_fname_blen); |
| 7016 |
cur_entry->pgen_locked_fname = nullptr; |
| 7017 |
cur_entry->first_varid = nullptr; |
| 7018 |
cur_entry->last_varid = nullptr; |
| 7019 |
} |
| 7020 |
if (!pmip->list_fname) { |
| 7021 |
PmergeInputFilesetLl* cur_entry = AllocFilesetLlEntry(&filesets_endp); |
| 7022 |
if (unlikely(!cur_entry)) { |
| 7023 |
goto Pmerge_ret_NOMEM; |
| 7024 |
} |
| 7025 |
cur_entry->is_temporary = 0; |
| 7026 |
cur_entry->pgen_fname = pmip->pgen_fname; |
| 7027 |
cur_entry->pvar_fname = pmip->pvar_fname; |
| 7028 |
cur_entry->psam_fname = pmip->psam_fname; |
| 7029 |
cur_entry->pgen_locked_fname = nullptr; |
| 7030 |
cur_entry->first_varid = nullptr; |
| 7031 |
cur_entry->last_varid = nullptr; |
| 7032 |
} else { |
| 7033 |
reterr = LoadPmergeList(pmip->list_fname, pmip->list_base_dir, pmip->list_mode, pgenname[0] != '\0', &filesets_endp, &fileset_ct); |
| 7034 |
if (unlikely(reterr)) { |
| 7035 |
goto Pmerge_ret_1; |
| 7036 |
} |
| 7037 |
} |
| 7038 |
} |
| 7039 |
|
| 7040 |
SampleIdInfo sii; |
| 7041 |
uint32_t sample_ct = 0; |
| 7042 |
uint32_t psam_linebuf_capacity = 0; |
| 7043 |
reterr = MergePsams(pmip, sample_sort_fname, missing_catname, misc_flags, sample_sort_mode, fam_cols, missing_pheno, max_thread_ct, outname, outname_end, input_filesets, &sii, &sample_ct, &psam_linebuf_capacity); |
| 7044 |
if (unlikely(reterr)) { |
| 7045 |
goto Pmerge_ret_1; |
| 7046 |
} |
| 7047 |
reterr = ScanPgenHeaders(!!(pmip->list_fname), misc_flags, input_filesets); |
| 7048 |
if (unlikely(reterr)) { |
| 7049 |
goto Pmerge_ret_1; |
| 7050 |
} |
| 7051 |
|
| 7052 |
VaridTemplate* varid_templatep = nullptr; |
| 7053 |
VaridTemplate* varid_multi_templatep = nullptr; |
| 7054 |
VaridTemplate* varid_multi_nonsnp_templatep = nullptr; |
| 7055 |
uint32_t missing_varid_match_slen = 0; |
| 7056 |
if (varid_template_str) { |
| 7057 |
if (unlikely(VaridInitAll(g_bigstack_end, varid_template_str, varid_multi_template_str, varid_multi_nonsnp_template_str, misc_flags, new_variant_id_max_allele_slen, &g_bigstack_base, &missing_varid_match, nullptr, &varid_templatep, &varid_multi_templatep, &varid_multi_nonsnp_templatep, nullptr, &missing_varid_match_slen))) { |
| 7058 |
goto Pmerge_ret_NOMEM; |
| 7059 |
} |
| 7060 |
} |
| 7061 |
|
| 7062 |
uint32_t info_has_g_key = 0; |
| 7063 |
const char* const* info_keys = nullptr; |
| 7064 |
uint32_t* info_keys_htable = nullptr; |
| 7065 |
uint32_t info_key_ct = 0; |
| 7066 |
uint32_t info_keys_htable_size = 0; |
| 7067 |
uint32_t info_conflict_present; |
| 7068 |
reterr = ScanPvarsAndMergeHeader(pmip, missing_varid_match, misc_flags, missing_varid_match_slen, input_missing_geno_char, max_thread_ct, sort_vars_mode, varid_templatep, varid_multi_templatep, varid_multi_nonsnp_templatep, outname, outname_end, &input_filesets, cip, &fileset_ct, &info_has_g_key, &info_keys, &info_key_ct, &info_keys_htable, &info_keys_htable_size, &info_conflict_present); |
| 7069 |
if (unlikely(reterr)) { |
| 7070 |
goto Pmerge_ret_1; |
| 7071 |
} |
| 7072 |
uint32_t is_concat_job = 0; |
| 7073 |
if (!(pmip->flags & kfPmergeVariantInnerJoin)) { |
| 7074 |
reterr = DetectConcatJob(cip->chr_idx_to_foidx, fileset_ct, sort_vars_mode, &input_filesets, &is_concat_job); |
| 7075 |
if (unlikely(reterr)) { |
| 7076 |
goto Pmerge_ret_1; |
| 7077 |
} |
| 7078 |
} |
| 7079 |
if (is_concat_job) { |
| 7080 |
reterr = PmergeConcat(pmip, &sii, cip, input_filesets, missing_varid_match, info_keys, info_keys_htable, sample_ct, fam_cols, fileset_ct, psam_linebuf_capacity, missing_varid_match_slen, info_key_ct, info_keys_htable_size, info_conflict_present, input_missing_geno_char, max_thread_ct, sort_vars_mode, varid_templatep, varid_multi_templatep, varid_multi_nonsnp_templatep, outname, outname_end); |
| 7081 |
} else { |
| 7082 |
for (uint32_t pass_idx = 1; ; ++pass_idx) { |
| 7083 |
uint32_t next_fileset_ct; |
| 7084 |
reterr = PmergePass(pmip, &sii, cip, info_keys, info_keys_htable, pass_idx, sample_ct, fam_cols, fileset_ct, psam_linebuf_capacity, info_key_ct, info_keys_htable_size, info_conflict_present, max_thread_ct, sort_vars_mode, outname, outname_end, &input_filesets, &next_filesets, &next_fileset_ct); |
| 7085 |
if (unlikely(reterr)) { |
| 7086 |
goto Pmerge_ret_1; |
| 7087 |
} |
| 7088 |
if (!next_filesets) { |
| 7089 |
break; |
| 7090 |
} |
| 7091 |
assert(input_filesets == nullptr); |
| 7092 |
fileset_ct = next_fileset_ct; |
| 7093 |
input_filesets = next_filesets; |
| 7094 |
next_filesets = nullptr; |
| 7095 |
} |
| 7096 |
} |
| 7097 |
const uint32_t outname_slen = outname_end - outname; |
| 7098 |
memcpy(pgenname, outname, outname_slen); |
| 7099 |
strcpy_k(&(pgenname[outname_slen]), ".pgen"); |
| 7100 |
memcpy(pvarname, outname, outname_slen); |
| 7101 |
const uint32_t output_zst = (pmip->flags / kfPmergeOutputVzs) & 1; |
| 7102 |
if (output_zst) { |
| 7103 |
strcpy_k(&(pvarname[outname_slen]), ".pvar.zst"); |
| 7104 |
} else { |
| 7105 |
strcpy_k(&(pvarname[outname_slen]), ".pvar"); |
| 7106 |
} |
| 7107 |
memcpy(psamname, outname, outname_slen); |
| 7108 |
strcpy_k(&(psamname[outname_slen]), ".psam"); |
| 7109 |
if ((pmip->flags & kfPmergeVariantInnerJoin) || pmip->max_allele_ct) { |
| 7110 |
// Some input variants that pass the chromosome filter might still be |
| 7111 |
// excluded from the merged dataset. |
| 7112 |
ForgetExtraChrNames(1, cip); |
| 7113 |
} |
| 7114 |
} |
| 7115 |
while (0) { |
| 7116 |
Pmerge_ret_NOMEM: |
| 7117 |
reterr = kPglRetNomem; |
| 7118 |
break; |
| 7119 |
} |
| 7120 |
Pmerge_ret_1: |
| 7121 |
CleanupFilesetLl(input_filesets, &reterr); |
| 7122 |
CleanupFilesetLl(next_filesets, &reterr); |
| 7123 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 7124 |
return reterr; |
| 7125 |
} |
| 7126 |
|
| 7127 |
uint32_t DuplicateAllelePresent(const AlleleCode* remap, uint32_t remap_len, uint32_t merged_allele_ctl, uintptr_t* remap_seen) { |
| 7128 |
ZeroWArr(merged_allele_ctl, remap_seen); |
| 7129 |
for (uint32_t allele_idx = 0; allele_idx != remap_len; ++allele_idx) { |
| 7130 |
const AlleleCode ac = remap[allele_idx]; |
| 7131 |
if (ac == kMissingAlleleCode) { |
| 7132 |
continue; |
| 7133 |
} |
| 7134 |
if (IsSet(remap_seen, ac)) { |
| 7135 |
return 1; |
| 7136 |
} |
| 7137 |
SetBit(ac, remap_seen); |
| 7138 |
} |
| 7139 |
return 0; |
| 7140 |
} |
| 7141 |
|
| 7142 |
typedef struct PgenDiffGtEntryStruct { |
| 7143 |
DoubleAlleleCode dac1; |
| 7144 |
DoubleAlleleCode dac2; |
| 7145 |
} PgenDiffGtEntry; |
| 7146 |
|
| 7147 |
static_assert(sizeof(Dosage) == 2, "PgenDiff() must be updated."); |
| 7148 |
PglErr PgenDiff(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 PgenDiffInfo* pdip, uint32_t raw_sample_ct, uint32_t orig_sample_ct, uint32_t raw_variant_ct, uint32_t max_allele_ct1, uint32_t max_allele_slen, char input_missing_geno_char, uint32_t max_thread_ct, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) { |
| 7149 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 7150 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 7151 |
char* cswritep = nullptr; |
| 7152 |
uintptr_t psam_line_idx = 0; |
| 7153 |
uintptr_t pvar_line_idx = 0; |
| 7154 |
TextStream psam_txs; |
| 7155 |
PreinitTextStream(&psam_txs); |
| 7156 |
TextStream pvar_txs; |
| 7157 |
PreinitTextStream(&pvar_txs); |
| 7158 |
PgenFileInfo pgfi2; |
| 7159 |
PgenReader simple_pgr2; |
| 7160 |
PreinitPgfi(&pgfi2); |
| 7161 |
PreinitPgr(&simple_pgr2); |
| 7162 |
CompressStreamState css; |
| 7163 |
PreinitCstream(&css); |
| 7164 |
PglErr reterr = kPglRetSuccess; |
| 7165 |
{ |
| 7166 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 7167 |
uintptr_t* sample_include; |
| 7168 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &sample_include))) { |
| 7169 |
goto PgenDiff_ret_NOMEM; |
| 7170 |
} |
| 7171 |
const uint32_t sex_needed = XymtIsNonempty(variant_include, cip, kChrOffsetX) || XymtIsNonempty(variant_include, cip, kChrOffsetY); |
| 7172 |
uint32_t raw_sample_ct2 = 0; |
| 7173 |
uint32_t* sample1_idx_to_2 = nullptr; |
| 7174 |
uint32_t* sample_include_cumulative_popcounts; |
| 7175 |
uint32_t* sample_idx_to_uidx; |
| 7176 |
uintptr_t* sample_include2; |
| 7177 |
uint32_t* sample_include2_cumulative_popcounts; |
| 7178 |
uint32_t sample_ct; |
| 7179 |
{ |
| 7180 |
uint32_t max_line_blen; |
| 7181 |
if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen))) { |
| 7182 |
goto PgenDiff_ret_NOMEM; |
| 7183 |
} |
| 7184 |
reterr = InitTextStreamEx(pdip->psam_fname, 1, kMaxLongLine, max_line_blen, MAXV(max_thread_ct - 1, 1), &psam_txs); |
| 7185 |
if (unlikely(reterr)) { |
| 7186 |
goto PgenDiff_ret_PSAM_TSTREAM_FAIL; |
| 7187 |
} |
| 7188 |
char* line_start; |
| 7189 |
XidMode xid_mode; |
| 7190 |
reterr = LoadXidHeader("pgen-diff .psam", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeaderFixedWidth : kfXidHeaderFixedWidthIgnoreSid, &psam_line_idx, &psam_txs, &xid_mode, &line_start); |
| 7191 |
if (unlikely(reterr)) { |
| 7192 |
if (reterr == kPglRetEof) { |
| 7193 |
logerrputs("Error: Empty --pgen-diff .psam file.\n"); |
| 7194 |
goto PgenDiff_ret_MALFORMED_INPUT; |
| 7195 |
} |
| 7196 |
goto PgenDiff_ret_PSAM_TSTREAM_XID_FAIL; |
| 7197 |
} |
| 7198 |
char* sorted_xidbox; |
| 7199 |
uint32_t* xid_map; |
| 7200 |
uintptr_t max_xid_blen; |
| 7201 |
reterr = SortedXidboxInitAllocEnd(orig_sample_include, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen); |
| 7202 |
if (unlikely(reterr)) { |
| 7203 |
goto PgenDiff_ret_1; |
| 7204 |
} |
| 7205 |
uint32_t* sample1_uidx_to_2; |
| 7206 |
char* idbuf; |
| 7207 |
if (unlikely(bigstack_end_alloc_u32(raw_sample_ct, &sample1_uidx_to_2) || |
| 7208 |
bigstack_end_alloc_c(max_xid_blen, &idbuf))) { |
| 7209 |
goto PgenDiff_ret_NOMEM; |
| 7210 |
} |
| 7211 |
|
| 7212 |
uint32_t postid_sex_col_idx = 0; |
| 7213 |
if (*line_start == '#') { |
| 7214 |
const uint32_t id_col_ct = GetXidColCt(xid_mode); |
| 7215 |
char* token_end = CurTokenEnd(NextTokenMult0(line_start, id_col_ct - 1)); |
| 7216 |
for (uint32_t postid_col_idx = 1; ; ++postid_col_idx) { |
| 7217 |
char* token_start = FirstNonTspace(token_end); |
| 7218 |
if (IsEolnKns(*token_start)) { |
| 7219 |
break; |
| 7220 |
} |
| 7221 |
token_end = CurTokenEnd(token_start); |
| 7222 |
const uint32_t token_slen = token_end - token_start; |
| 7223 |
if (strequal_k(token_start, "SEX", token_slen)) { |
| 7224 |
if (unlikely(postid_sex_col_idx)) { |
| 7225 |
logerrputs("Error: Multiple sex columns in --pgen-diff .psam file.\n"); |
| 7226 |
goto PgenDiff_ret_MALFORMED_INPUT; |
| 7227 |
} |
| 7228 |
postid_sex_col_idx = postid_col_idx; |
| 7229 |
} |
| 7230 |
} |
| 7231 |
if (unlikely(!postid_sex_col_idx)) { |
| 7232 |
logerrputs("Error: No sex column in --pgen-diff .psam file.\n"); |
| 7233 |
goto PgenDiff_ret_MALFORMED_INPUT; |
| 7234 |
} |
| 7235 |
++psam_line_idx; |
| 7236 |
line_start = TextGet(&psam_txs); |
| 7237 |
} else { |
| 7238 |
// default: FID IID PAT MAT SEX PHENO1 |
| 7239 |
postid_sex_col_idx = 3; |
| 7240 |
} |
| 7241 |
if (!sex_needed) { |
| 7242 |
postid_sex_col_idx = 0; |
| 7243 |
} |
| 7244 |
const uintptr_t first_payload_line_idx = psam_line_idx; |
| 7245 |
for (; line_start; ++psam_line_idx, line_start = TextGet(&psam_txs)) { |
| 7246 |
const char* token_iter = line_start; |
| 7247 |
uint32_t sample_uidx; |
| 7248 |
if (SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &token_iter, &sample_uidx, idbuf)) { |
| 7249 |
if (unlikely(!token_iter)) { |
| 7250 |
goto PgenDiff_ret_PSAM_MISSING_TOKENS; |
| 7251 |
} |
| 7252 |
continue; |
| 7253 |
} |
| 7254 |
if (unlikely(IsSet(sample_include, sample_uidx))) { |
| 7255 |
TabsToSpaces(idbuf); |
| 7256 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in --pgen-diff .psam file.\n", idbuf); |
| 7257 |
goto PgenDiff_ret_MALFORMED_INPUT_WW; |
| 7258 |
} |
| 7259 |
SetBit(sample_uidx, sample_include); |
| 7260 |
sample1_uidx_to_2[sample_uidx] = psam_line_idx - first_payload_line_idx; |
| 7261 |
if (postid_sex_col_idx) { |
| 7262 |
token_iter = NextTokenMult(token_iter, postid_sex_col_idx); |
| 7263 |
if (unlikely(!token_iter)) { |
| 7264 |
goto PgenDiff_ret_PSAM_MISSING_TOKENS; |
| 7265 |
} |
| 7266 |
const uint32_t token_slen = strlen_se(token_iter); |
| 7267 |
const uint32_t cur_sex_code = CharToSex(token_iter[0]); |
| 7268 |
if ((token_slen != 1) || (!cur_sex_code)) { |
| 7269 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing sex code on line %" PRIuPTR " of --pgen-diff .psam file; this is prohibited when chrX or chrY is in the comparison.\n", psam_line_idx); |
| 7270 |
goto PgenDiff_ret_INCONSISTENT_INPUT_WW; |
| 7271 |
} |
| 7272 |
if ((!IsSet(sex_nm, sample_uidx)) || (IsSet(sex_male, sample_uidx) != 2 - cur_sex_code)) { |
| 7273 |
snprintf(g_logbuf, kLogbufSize, "Error: Mismatching sex code on line %" PRIuPTR " of --pgen-diff .psam file; this is prohibited when chrX or chrY is in the comparison.\n", psam_line_idx); |
| 7274 |
goto PgenDiff_ret_INCONSISTENT_INPUT_WW; |
| 7275 |
} |
| 7276 |
} |
| 7277 |
} |
| 7278 |
if (unlikely(TextStreamErrcode2(&psam_txs, &reterr))) { |
| 7279 |
goto PgenDiff_ret_PSAM_TSTREAM_FAIL; |
| 7280 |
} |
| 7281 |
if (unlikely(CleanupTextStream2("--pgen-diff .psam file", &psam_txs, &reterr))) { |
| 7282 |
goto PgenDiff_ret_1; |
| 7283 |
} |
| 7284 |
sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 7285 |
if (unlikely(!sample_ct)) { |
| 7286 |
logerrputs("Error: No matching samples in --pgen-diff .psam file.\n"); |
| 7287 |
goto PgenDiff_ret_INCONSISTENT_INPUT; |
| 7288 |
} |
| 7289 |
const uintptr_t raw_sample_ct2_ul = psam_line_idx - first_payload_line_idx; |
| 7290 |
#ifdef __LP64__ |
| 7291 |
if (raw_sample_ct2_ul > kPglMaxSampleCt) { |
| 7292 |
logerrputs("Error: Too many samples in --pgen-diff .psam file (max 2^31 - 2).\n"); |
| 7293 |
goto PgenDiff_ret_MALFORMED_INPUT; |
| 7294 |
} |
| 7295 |
#endif |
| 7296 |
raw_sample_ct2 = raw_sample_ct2_ul; |
| 7297 |
const uint32_t raw_sample_ct2l = BitCtToWordCt(raw_sample_ct2); |
| 7298 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) || |
| 7299 |
bigstack_alloc_u32(sample_ct, &sample_idx_to_uidx) || |
| 7300 |
bigstack_calloc_w(raw_sample_ct2l, &sample_include2) || |
| 7301 |
bigstack_alloc_u32(raw_sample_ct2l, &sample_include2_cumulative_popcounts))) { |
| 7302 |
goto PgenDiff_ret_NOMEM; |
| 7303 |
} |
| 7304 |
uintptr_t sample_uidx_base = 0; |
| 7305 |
uintptr_t cur_bits = sample_include[0]; |
| 7306 |
uint32_t prev_uidx2 = 0; // ok for this to start at 0 instead of -1 |
| 7307 |
uint32_t is_increasing = 1; |
| 7308 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7309 |
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 7310 |
sample_idx_to_uidx[sample_idx] = sample_uidx; |
| 7311 |
const uint32_t sample_uidx2 = sample1_uidx_to_2[sample_uidx]; |
| 7312 |
SetBit(sample_uidx2, sample_include2); |
| 7313 |
if (is_increasing) { |
| 7314 |
is_increasing = (sample_uidx2 >= prev_uidx2); |
| 7315 |
prev_uidx2 = sample_uidx2; |
| 7316 |
} |
| 7317 |
} |
| 7318 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 7319 |
FillCumulativePopcounts(sample_include2, raw_sample_ct2l, sample_include2_cumulative_popcounts); |
| 7320 |
if (!is_increasing) { |
| 7321 |
if (unlikely(bigstack_alloc_u32(sample_ct, &sample1_idx_to_2))) { |
| 7322 |
goto PgenDiff_ret_NOMEM; |
| 7323 |
} |
| 7324 |
sample_uidx_base = 0; |
| 7325 |
cur_bits = sample_include[0]; |
| 7326 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7327 |
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 7328 |
const uint32_t sample_uidx2 = sample1_uidx_to_2[sample_uidx]; |
| 7329 |
const uint32_t sample_idx2 = RawToSubsettedPos(sample_include2, sample_include2_cumulative_popcounts, sample_uidx2); |
| 7330 |
sample1_idx_to_2[sample_idx] = sample_idx2; |
| 7331 |
} |
| 7332 |
} |
| 7333 |
BigstackEndReset(bigstack_end_mark); |
| 7334 |
} |
| 7335 |
uintptr_t* allele_idx_offsets2 = nullptr; |
| 7336 |
uint32_t raw_variant_ct2 = 0; |
| 7337 |
uint32_t max_observed_pvar_line_blen = 0; |
| 7338 |
uint32_t max_allele_slen2 = 1; |
| 7339 |
uint32_t max_allele_ct2 = 2; |
| 7340 |
reterr = LoadAlleleIdxOffsetsFromPvar(pdip->pvar_fname, "--pgen-diff .pvar file", max_thread_ct, &raw_variant_ct2, &max_allele_slen2, &max_observed_pvar_line_blen, &allele_idx_offsets2, &max_allele_ct2); |
| 7341 |
if (unlikely(reterr)) { |
| 7342 |
goto PgenDiff_ret_1; |
| 7343 |
} |
| 7344 |
if (max_allele_slen2 > max_allele_slen) { |
| 7345 |
max_allele_slen = max_allele_slen2; |
| 7346 |
} |
| 7347 |
|
| 7348 |
PgenHeaderCtrl header_ctrl; |
| 7349 |
uintptr_t cur_alloc_cacheline_ct; |
| 7350 |
reterr = PgfiInitPhase1(pdip->pgen_fname, nullptr, raw_variant_ct2, raw_sample_ct2, &header_ctrl, &pgfi2, &cur_alloc_cacheline_ct, g_logbuf); |
| 7351 |
if (unlikely(reterr)) { |
| 7352 |
WordWrapB(0); |
| 7353 |
logerrputsb(); |
| 7354 |
goto PgenDiff_ret_1; |
| 7355 |
} |
| 7356 |
pgfi2.allele_idx_offsets = allele_idx_offsets2; |
| 7357 |
pgfi2.max_allele_ct = max_allele_ct2; |
| 7358 |
unsigned char* pgfi_alloc; |
| 7359 |
if (unlikely(bigstack_alloc_uc(cur_alloc_cacheline_ct * kCacheline, &pgfi_alloc))) { |
| 7360 |
goto PgenDiff_ret_NOMEM; |
| 7361 |
} |
| 7362 |
const uint32_t all_nonref2 = ((header_ctrl & 192) == 128); |
| 7363 |
const uint32_t raw_variant_ctl2 = BitCtToWordCt(raw_variant_ct2); |
| 7364 |
uintptr_t* nonref_flags2 = nullptr; |
| 7365 |
if ((header_ctrl & 192) == 192) { |
| 7366 |
if (unlikely(bigstack_alloc_w(raw_variant_ctl2, &nonref_flags2))) { |
| 7367 |
goto PgenDiff_ret_NOMEM; |
| 7368 |
} |
| 7369 |
pgfi2.nonref_flags = nonref_flags2; |
| 7370 |
} |
| 7371 |
uintptr_t pgr_alloc_cacheline_ct; |
| 7372 |
uint32_t max_vrec_width; |
| 7373 |
reterr = PgfiInitPhase2(header_ctrl, 1, 0, 0, 0, raw_variant_ct2, &max_vrec_width, &pgfi2, pgfi_alloc, &pgr_alloc_cacheline_ct, g_logbuf); |
| 7374 |
if (unlikely(reterr)) { |
| 7375 |
WordWrapB(0); |
| 7376 |
logerrputsb(); |
| 7377 |
goto PgenDiff_ret_1; |
| 7378 |
} |
| 7379 |
if (unlikely((!allele_idx_offsets2) && (pgfi2.gflags & kfPgenGlobalMultiallelicHardcallFound))) { |
| 7380 |
logerrputs("Error: --pgen-diff .pgen file contains multiallelic variants, while .pvar does\nnot.\n"); |
| 7381 |
goto PgenDiff_ret_INCONSISTENT_INPUT; |
| 7382 |
} |
| 7383 |
unsigned char* simple_pgr_alloc; |
| 7384 |
if (unlikely(bigstack_alloc_uc((pgr_alloc_cacheline_ct + DivUp(max_vrec_width, kCacheline)) * kCacheline, &simple_pgr_alloc))) { |
| 7385 |
goto PgenDiff_ret_NOMEM; |
| 7386 |
} |
| 7387 |
reterr = PgrInit(pdip->pgen_fname, max_vrec_width, &pgfi2, &simple_pgr2, simple_pgr_alloc); |
| 7388 |
if (unlikely(reterr)) { |
| 7389 |
if (reterr == kPglRetOpenFail) { |
| 7390 |
logerrprintfww(kErrprintfFopen, pdip->pgen_fname, strerror(errno)); |
| 7391 |
} else { |
| 7392 |
assert(reterr == kPglRetReadFail); |
| 7393 |
logerrprintfww(kErrprintfFread, pdip->pgen_fname, rstrerror(errno)); |
| 7394 |
} |
| 7395 |
goto PgenDiff_ret_1; |
| 7396 |
} |
| 7397 |
PgrSampleSubsetIndex pssi1; |
| 7398 |
PgrSampleSubsetIndex pssi2; |
| 7399 |
PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi1); |
| 7400 |
PgrSetSampleSubsetIndex(sample_include2_cumulative_popcounts, &simple_pgr2, &pssi2); |
| 7401 |
const PgenDiffFlags flags = pdip->flags; |
| 7402 |
const uint32_t dosage_hap_tol = pdip->dosage_hap_tol; |
| 7403 |
|
| 7404 |
// these values are unimportant if dosage_hap_tol == kDosageMissing |
| 7405 |
uint32_t dosage_sex_tols[2]; |
| 7406 |
dosage_sex_tols[0] = dosage_hap_tol / 2; |
| 7407 |
dosage_sex_tols[1] = dosage_hap_tol; |
| 7408 |
|
| 7409 |
const uint32_t dosage_reported = (dosage_hap_tol != kDosageMissing); |
| 7410 |
const uint32_t dosage_needed = ((PgrGetGflags(simple_pgrp) | PgrGetGflags(&simple_pgr2)) & kfPgenGlobalDosagePresent) && dosage_reported; |
| 7411 |
const uint32_t max_merged_allele_ct = MINV(max_allele_ct1 + max_allele_ct2, kPglMaxAlleleCt); |
| 7412 |
const uint32_t max_allele_htable_size = GetHtableFastSize(max_merged_allele_ct); |
| 7413 |
PgenVariant pgv1; |
| 7414 |
PgenVariant pgv2; |
| 7415 |
if (unlikely(BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, dosage_needed? kfPgenGlobalDosagePresent : kfPgenGlobal0, &pgv1) || |
| 7416 |
BigstackAllocPgv(sample_ct, allele_idx_offsets2 != nullptr, dosage_needed? kfPgenGlobalDosagePresent : kfPgenGlobal0, &pgv2))) { |
| 7417 |
goto PgenDiff_ret_NOMEM; |
| 7418 |
} |
| 7419 |
// separated to avoid spurious maybe-uninitialized warnings |
| 7420 |
const char** cur_allele2s; |
| 7421 |
const char** merged_alleles; |
| 7422 |
uint32_t* merged_alleles_htable; |
| 7423 |
uint32_t* diff_sample_idxs; |
| 7424 |
AlleleCode* remap1; |
| 7425 |
AlleleCode* remap2; |
| 7426 |
AlleleCode* wide_codes1; |
| 7427 |
AlleleCode* wide_codes2; |
| 7428 |
uintptr_t* remap_seen; |
| 7429 |
if (unlikely(bigstack_alloc_kcp(max_allele_ct2, &cur_allele2s) || |
| 7430 |
bigstack_alloc_kcp(max_merged_allele_ct, &merged_alleles) || |
| 7431 |
bigstack_alloc_u32(max_allele_htable_size, &merged_alleles_htable) || |
| 7432 |
bigstack_alloc_u32(sample_ct, &diff_sample_idxs) || |
| 7433 |
bigstack_alloc_ac(max_allele_ct1, &remap1) || |
| 7434 |
bigstack_alloc_ac(max_allele_ct2, &remap2) || |
| 7435 |
bigstack_alloc_ac(sample_ct * 2, &wide_codes1) || |
| 7436 |
bigstack_alloc_ac(sample_ct * 2, &wide_codes2) || |
| 7437 |
bigstack_alloc_w(BitCtToWordCt(max_merged_allele_ct), &remap_seen))) { |
| 7438 |
goto PgenDiff_ret_NOMEM; |
| 7439 |
} |
| 7440 |
uintptr_t* sex_male_collapsed = nullptr; |
| 7441 |
Dosage* biallelic_dosage1 = nullptr; |
| 7442 |
Dosage* biallelic_dosage2 = nullptr; |
| 7443 |
if (dosage_needed) { |
| 7444 |
// allocations are automatically rounded up to vector boundary, so |
| 7445 |
// PopulateDenseDosage() is safe |
| 7446 |
if (unlikely(bigstack_alloc_dosage(sample_ct, &biallelic_dosage1) || |
| 7447 |
bigstack_alloc_dosage(sample_ct, &biallelic_dosage2))) { |
| 7448 |
goto PgenDiff_ret_NOMEM; |
| 7449 |
} |
| 7450 |
if (sex_needed) { |
| 7451 |
const uintptr_t sample_ctl = BitCtToWordCt(sample_ct); |
| 7452 |
if (unlikely(bigstack_alloc_w(sample_ctl, &sex_male_collapsed))) { |
| 7453 |
goto PgenDiff_ret_NOMEM; |
| 7454 |
} |
| 7455 |
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed); |
| 7456 |
} |
| 7457 |
} |
| 7458 |
pgv1.patch_01_ct = 0; |
| 7459 |
pgv1.patch_10_ct = 0; |
| 7460 |
pgv1.dosage_ct = 0; |
| 7461 |
pgv2.patch_01_ct = 0; |
| 7462 |
pgv2.patch_10_ct = 0; |
| 7463 |
pgv2.dosage_ct = 0; |
| 7464 |
PgenDiffGtEntry* gt_entries = nullptr; |
| 7465 |
Dosage* ds_entries = nullptr; |
| 7466 |
if (!dosage_needed) { |
| 7467 |
if (unlikely(BIGSTACK_ALLOC_X(PgenDiffGtEntry, sample_ct, >_entries))) { |
| 7468 |
goto PgenDiff_ret_NOMEM; |
| 7469 |
} |
| 7470 |
} else { |
| 7471 |
// don't define a struct for this, since entry length depends on number |
| 7472 |
// of alleles |
| 7473 |
if (unlikely(bigstack_alloc_dosage(sample_ct * (2 * k1LU) * (max_merged_allele_ct - 1), &ds_entries))) { |
| 7474 |
goto PgenDiff_ret_NOMEM; |
| 7475 |
} |
| 7476 |
} |
| 7477 |
|
| 7478 |
const uint32_t output_zst = (flags / kfPgenDiffZs) & 1; |
| 7479 |
OutnameZstSet(".pdiff", output_zst, outname_end); |
| 7480 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 7481 |
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + 4 * kMaxIdSlen + 128 + max_allele_slen + max_merged_allele_ct * 16; |
| 7482 |
const uint32_t compress_thread_ct = MINV((max_thread_ct + 1) / 2, 6); |
| 7483 |
reterr = InitCstreamAlloc(outname, 0, output_zst, compress_thread_ct, overflow_buf_size, &css, &cswritep); |
| 7484 |
if (unlikely(reterr)) { |
| 7485 |
goto PgenDiff_ret_1; |
| 7486 |
} |
| 7487 |
*cswritep++ = '#'; |
| 7488 |
const uint32_t chr_col = flags & kfPgenDiffColChrom; |
| 7489 |
|
| 7490 |
// null-terminated |
| 7491 |
char* chr_buf; |
| 7492 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) { |
| 7493 |
goto PgenDiff_ret_NOMEM; |
| 7494 |
} |
| 7495 |
if (chr_col) { |
| 7496 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 7497 |
} |
| 7498 |
const uint32_t pos_col = flags & kfPgenDiffColPos; |
| 7499 |
if (pos_col) { |
| 7500 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 7501 |
} |
| 7502 |
const uint32_t varid_col = flags & kfPgenDiffColId; |
| 7503 |
if (varid_col) { |
| 7504 |
cswritep = strcpya_k(cswritep, "ID\t"); |
| 7505 |
} |
| 7506 |
const uint32_t ref_col = flags & kfPgenDiffColRef; |
| 7507 |
if (ref_col) { |
| 7508 |
cswritep = strcpya_k(cswritep, "REF\t"); |
| 7509 |
} |
| 7510 |
const uint32_t alt_col = flags & kfPgenDiffColAlt; |
| 7511 |
if (alt_col) { |
| 7512 |
cswritep = strcpya_k(cswritep, "ALT\t"); |
| 7513 |
} |
| 7514 |
const uintptr_t* nonref_flags1 = pgfip->nonref_flags; |
| 7515 |
const uint32_t all_nonref1 = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags1); |
| 7516 |
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags1, flags / kfPgenDiffColMaybeprovref, raw_variant_ct, all_nonref1); |
| 7517 |
if (provref_col) { |
| 7518 |
cswritep = strcpya_k(cswritep, "PROVISIONAL_REF?\t"); |
| 7519 |
} |
| 7520 |
const uint32_t fid_col = FidColIsRequired(siip, flags / kfPgenDiffColMaybefid); |
| 7521 |
if (fid_col) { |
| 7522 |
cswritep = strcpya_k(cswritep, "FID\t"); |
| 7523 |
} |
| 7524 |
cswritep = strcpya_k(cswritep, "IID"); |
| 7525 |
const uint32_t sid_col = SidColIsRequired(siip->sids, flags / kfPgenDiffColMaybesid); |
| 7526 |
if (sid_col) { |
| 7527 |
cswritep = strcpya_k(cswritep, "\tSID"); |
| 7528 |
} |
| 7529 |
const uint32_t geno_col = flags & kfPgenDiffColGeno; |
| 7530 |
if (geno_col) { |
| 7531 |
if (!dosage_reported) { |
| 7532 |
cswritep = strcpya_k(cswritep, "\tGT1\tGT2"); |
| 7533 |
} else { |
| 7534 |
cswritep = strcpya_k(cswritep, "\tDS1\tDS2"); |
| 7535 |
} |
| 7536 |
} |
| 7537 |
AppendBinaryEoln(&cswritep); |
| 7538 |
|
| 7539 |
reterr = InitTextStream(pdip->pvar_fname, MAXV(max_observed_pvar_line_blen, kTextStreamBlenFast), ClipU32(max_thread_ct - 1, 1, 3), &pvar_txs); |
| 7540 |
if (unlikely(reterr)) { |
| 7541 |
goto PgenDiff_ret_PVAR_REWIND_FAIL; |
| 7542 |
} |
| 7543 |
// Skip to header. |
| 7544 |
char* line_start; |
| 7545 |
do { |
| 7546 |
line_start = TextGet(&pvar_txs); |
| 7547 |
if (unlikely(!line_start)) { |
| 7548 |
goto PgenDiff_ret_PVAR_REWIND_FAIL; |
| 7549 |
} |
| 7550 |
++pvar_line_idx; |
| 7551 |
} while ((*line_start == '#') && (!tokequal_k(line_start, "#CHROM"))); |
| 7552 |
uint32_t col_skips[4]; |
| 7553 |
uint32_t col_types[4]; |
| 7554 |
if (*line_start == '#') { |
| 7555 |
// [-1] = #CHROM (must be first column) |
| 7556 |
// [0] = POS |
| 7557 |
// [1] = ID |
| 7558 |
// [2] = REF |
| 7559 |
// [3] = ALT |
| 7560 |
// Can ignore other columns here. |
| 7561 |
char* token_end = &(line_start[6]); |
| 7562 |
uint32_t found_header_bitset = 0; |
| 7563 |
uint32_t relevant_postchr_col_uidx = 0; |
| 7564 |
for (uint32_t col_idx = 1; ; ++col_idx) { |
| 7565 |
char* token_start = FirstNonTspace(token_end); |
| 7566 |
if (IsEolnKns(*token_start)) { |
| 7567 |
break; |
| 7568 |
} |
| 7569 |
token_end = CurTokenEnd(token_start); |
| 7570 |
const uint32_t token_slen = token_end - token_start; |
| 7571 |
uint32_t cur_col_type; |
| 7572 |
if (strequal_k(token_start, "POS", token_slen)) { |
| 7573 |
cur_col_type = 0; |
| 7574 |
} else if (strequal_k(token_start, "ID", token_slen)) { |
| 7575 |
cur_col_type = 1; |
| 7576 |
} else if (strequal_k(token_start, "REF", token_slen)) { |
| 7577 |
cur_col_type = 2; |
| 7578 |
} else if (strequal_k(token_start, "ALT", token_slen)) { |
| 7579 |
cur_col_type = 3; |
| 7580 |
} else { |
| 7581 |
continue; |
| 7582 |
} |
| 7583 |
const uint32_t cur_col_type_shifted = 1 << cur_col_type; |
| 7584 |
if (unlikely(found_header_bitset & cur_col_type_shifted)) { |
| 7585 |
// known token, so no overflow danger |
| 7586 |
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '"); |
| 7587 |
write_iter = memcpya(write_iter, token_start, token_slen); |
| 7588 |
write_iter = strcpya_k(write_iter, "' on line "); |
| 7589 |
write_iter = wtoa(pvar_line_idx, write_iter); |
| 7590 |
write_iter = strcpya_k(write_iter, " of --pgen-diff file.\n"); |
| 7591 |
*write_iter = '\0'; |
| 7592 |
goto PgenDiff_ret_MALFORMED_INPUT_WW; |
| 7593 |
} |
| 7594 |
found_header_bitset |= cur_col_type_shifted; |
| 7595 |
col_skips[relevant_postchr_col_uidx] = col_idx; |
| 7596 |
col_types[relevant_postchr_col_uidx++] = cur_col_type; |
| 7597 |
} |
| 7598 |
if (unlikely(found_header_bitset != 0xf)) { |
| 7599 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of --pgen-diff file. (POS, ID, REF, and ALT are required.)\n", pvar_line_idx); |
| 7600 |
goto PgenDiff_ret_MALFORMED_INPUT_WW; |
| 7601 |
} |
| 7602 |
for (uint32_t rpc_col_idx = 3; rpc_col_idx; --rpc_col_idx) { |
| 7603 |
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1]; |
| 7604 |
} |
| 7605 |
line_start = AdvPastDelim(token_end, '\n'); |
| 7606 |
++pvar_line_idx; |
| 7607 |
} else { |
| 7608 |
char* fifth_token_start = NextTokenMult(line_start, 4); |
| 7609 |
if (unlikely(!fifth_token_start)) { |
| 7610 |
goto PgenDiff_ret_PVAR_MISSING_TOKENS; |
| 7611 |
} |
| 7612 |
col_skips[0] = 1; |
| 7613 |
col_skips[2] = 1; |
| 7614 |
col_skips[3] = 1; |
| 7615 |
col_types[0] = 1; |
| 7616 |
col_types[1] = 0; |
| 7617 |
col_types[2] = 3; |
| 7618 |
col_types[3] = 2; |
| 7619 |
if (!NextToken(fifth_token_start)) { |
| 7620 |
// #CHROM ID POS ALT REF |
| 7621 |
col_skips[1] = 1; |
| 7622 |
} else { |
| 7623 |
// #CHROM ID CM POS ALT REF |
| 7624 |
col_skips[1] = 2; |
| 7625 |
} |
| 7626 |
} |
| 7627 |
|
| 7628 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 7629 |
uintptr_t* already_seen; |
| 7630 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &already_seen))) { |
| 7631 |
goto PgenDiff_ret_NOMEM; |
| 7632 |
} |
| 7633 |
const DoubleAlleleCode biallelic_dac[4] = {0, 1 << (8 * sizeof(AlleleCode)), 1 + (1 << (8 * sizeof(AlleleCode))), kMissingDoubleAlleleCode}; |
| 7634 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 7635 |
const char* sample_ids = siip->sample_ids; |
| 7636 |
const char* sids = siip->sids; |
| 7637 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 7638 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 7639 |
const uint32_t include_missing = (flags / kfPgenDiffIncludeMissing) & 1; |
| 7640 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 7641 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 7642 |
uint32_t chr_idx = UINT32_MAX; |
| 7643 |
uint32_t chr_slen = 0; |
| 7644 |
uint32_t cur_bp = 0; // just for .pvar-sorted sanity check |
| 7645 |
uint32_t cur_included_bp = 0; |
| 7646 |
uint32_t variant_uidx_start = 0; |
| 7647 |
uint32_t variant_uidx_end = 0; |
| 7648 |
uint32_t same_bp_variant_ct = 0; |
| 7649 |
uint32_t chrom_end_variant_uidx = 0; |
| 7650 |
uint32_t is_autosomal_diploid = 0; |
| 7651 |
uint32_t is_x = 0; |
| 7652 |
uint32_t is_y = 0; |
| 7653 |
uint32_t dosage_cur_tol = 0; |
| 7654 |
uint32_t pct = 0; |
| 7655 |
uint32_t next_print_variant_uidx2 = raw_variant_ct2 / 100; |
| 7656 |
uint64_t grand_diff_ct = 0; |
| 7657 |
uint32_t cur_allele_ct1 = 2; |
| 7658 |
uint32_t cur_allele_ct2 = 2; |
| 7659 |
fputs("--pgen-diff: 0%", stdout); |
| 7660 |
fflush(stdout); |
| 7661 |
for (uint32_t variant_uidx2 = 0; variant_uidx2 != raw_variant_ct2; ++variant_uidx2, ++pvar_line_idx) { |
| 7662 |
if (unlikely(!TextGetUnsafe2(&pvar_txs, &line_start))) { |
| 7663 |
goto PgenDiff_ret_PVAR_REWIND_FAIL_N; |
| 7664 |
} |
| 7665 |
char* token_ptrs[4]; |
| 7666 |
uint32_t token_slens[4]; |
| 7667 |
char* last_token_end = TokenLex(line_start, col_types, col_skips, 4, token_ptrs, token_slens); |
| 7668 |
if (unlikely(!last_token_end)) { |
| 7669 |
goto PgenDiff_ret_PVAR_MISSING_TOKENS_N; |
| 7670 |
} |
| 7671 |
if (variant_uidx2 >= next_print_variant_uidx2) { |
| 7672 |
if (pct > 10) { |
| 7673 |
putc_unlocked('\b', stdout); |
| 7674 |
} |
| 7675 |
pct = (variant_uidx2 * 100LLU) / raw_variant_ct2; |
| 7676 |
printf("\b\b%u%%", pct++); |
| 7677 |
fflush(stdout); |
| 7678 |
next_print_variant_uidx2 = (pct * S_CAST(uint64_t, raw_variant_ct2)) / 100; |
| 7679 |
} |
| 7680 |
{ |
| 7681 |
char* chrom_start = line_start; |
| 7682 |
line_start = AdvPastDelim(line_start, '\n'); |
| 7683 |
|
| 7684 |
char* chrom_end = CurTokenEnd(chrom_start); |
| 7685 |
*chrom_end = '\0'; |
| 7686 |
const uint32_t new_chr_idx = GetChrCode(chrom_start, cip, chrom_end - chrom_start); |
| 7687 |
if (IsI32Neg(new_chr_idx)) { |
| 7688 |
continue; |
| 7689 |
} |
| 7690 |
if (new_chr_idx != chr_idx) { |
| 7691 |
chr_idx = new_chr_idx; |
| 7692 |
if (IsI32Neg(chr_idx) || !IsSet(cip->chr_mask, chr_idx)) { |
| 7693 |
// Chromosome isn't loaded at all; skip it. |
| 7694 |
chrom_end_variant_uidx = 0; |
| 7695 |
continue; |
| 7696 |
} |
| 7697 |
const uint32_t is_haploid = IsSet(cip->haploid_mask, chr_idx); |
| 7698 |
is_autosomal_diploid = 1 - is_haploid; |
| 7699 |
is_x = (chr_idx == x_code); |
| 7700 |
is_y = (chr_idx == y_code); |
| 7701 |
dosage_cur_tol = dosage_sex_tols[is_haploid]; |
| 7702 |
cur_bp = 0; |
| 7703 |
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_idx]; |
| 7704 |
const uint32_t chrom_start_variant_uidx = cip->chr_fo_vidx_start[chr_fo_idx]; |
| 7705 |
chrom_end_variant_uidx = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 7706 |
variant_uidx_start = AdvBoundedTo1Bit(variant_include, chrom_start_variant_uidx, chrom_end_variant_uidx); |
| 7707 |
if (variant_uidx_start == chrom_end_variant_uidx) { |
| 7708 |
// All variants on this chromosome have been filtered out; skip it. |
| 7709 |
chrom_end_variant_uidx = 0; |
| 7710 |
continue; |
| 7711 |
} |
| 7712 |
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf); |
| 7713 |
*chr_name_end = '\0'; |
| 7714 |
chr_slen = chr_name_end - chr_buf; |
| 7715 |
cur_included_bp = variant_bps[variant_uidx_start]; |
| 7716 |
const uint32_t search_start = variant_uidx_start + 1; |
| 7717 |
variant_uidx_end = ExpsearchU32(variant_bps, search_start, chrom_end_variant_uidx, cur_included_bp + 1); |
| 7718 |
variant_uidx_end = 1 + FindLast1BitBefore(variant_include, variant_uidx_end); |
| 7719 |
same_bp_variant_ct = PopcountBitRange(variant_include, variant_uidx_start, variant_uidx_end); |
| 7720 |
} else if (!chrom_end_variant_uidx) { |
| 7721 |
continue; |
| 7722 |
} |
| 7723 |
} |
| 7724 |
|
| 7725 |
{ |
| 7726 |
int32_t new_bp; |
| 7727 |
if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &new_bp))) { |
| 7728 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of --pgen-diff .pvar file.\n", pvar_line_idx); |
| 7729 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7730 |
} |
| 7731 |
if (new_bp < 0) { |
| 7732 |
continue; |
| 7733 |
} |
| 7734 |
const uint32_t new_bp_u32 = new_bp; |
| 7735 |
if (new_bp_u32 < cur_bp) { |
| 7736 |
// Could also verify that .pvar has no split chromosomes. |
| 7737 |
logputs("\n"); |
| 7738 |
logerrputs("Error: --pgen-diff .pvar file is unsorted.\n"); |
| 7739 |
goto PgenDiff_ret_MALFORMED_INPUT; |
| 7740 |
} |
| 7741 |
cur_bp = new_bp_u32; |
| 7742 |
if (new_bp_u32 < cur_included_bp) { |
| 7743 |
continue; |
| 7744 |
} |
| 7745 |
if (new_bp_u32 > cur_included_bp) { |
| 7746 |
variant_uidx_start = ExpsearchU32(variant_bps, variant_uidx_end, chrom_end_variant_uidx, new_bp_u32); |
| 7747 |
variant_uidx_start = AdvBoundedTo1Bit(variant_include, variant_uidx_start, chrom_end_variant_uidx); |
| 7748 |
if (variant_uidx_start == chrom_end_variant_uidx) { |
| 7749 |
variant_uidx_end = variant_uidx_start; |
| 7750 |
cur_included_bp = UINT32_MAX; |
| 7751 |
continue; |
| 7752 |
} |
| 7753 |
cur_included_bp = variant_bps[variant_uidx_start]; |
| 7754 |
const uint32_t search_start = variant_uidx_start + 1; |
| 7755 |
variant_uidx_end = ExpsearchU32(variant_bps, search_start, chrom_end_variant_uidx, cur_included_bp + 1); |
| 7756 |
variant_uidx_end = 1 + FindLast1BitBefore(variant_include, variant_uidx_end); |
| 7757 |
same_bp_variant_ct = PopcountBitRange(variant_include, variant_uidx_start, variant_uidx_end); |
| 7758 |
if (new_bp_u32 < cur_included_bp) { |
| 7759 |
continue; |
| 7760 |
} |
| 7761 |
} |
| 7762 |
} |
| 7763 |
|
| 7764 |
uint32_t variant_uidx = UINT32_MAX; |
| 7765 |
{ |
| 7766 |
// Note that this is inefficient if we're dealing with a large pile of |
| 7767 |
// unmapped variants with CHROM and POS set to 0. We can construct a |
| 7768 |
// variant ID hash table when same_bp_variant_ct is large if it's |
| 7769 |
// important to speed up that use case. |
| 7770 |
char* cur_variant_id = token_ptrs[1]; |
| 7771 |
const uint32_t cur_variant_id_slen = token_slens[1]; |
| 7772 |
if (cur_variant_id_slen > kMaxIdSlen) { |
| 7773 |
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID too long on line %" PRIuPTR " of --pgen-diff .pvar file (max " MAX_ID_SLEN_STR " characters).\n", pvar_line_idx); |
| 7774 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7775 |
} |
| 7776 |
cur_variant_id[cur_variant_id_slen] = '\0'; |
| 7777 |
const uint32_t cur_variant_id_blen = cur_variant_id_slen + 1; |
| 7778 |
uintptr_t variant_uidx_base; |
| 7779 |
uintptr_t cur_bits; |
| 7780 |
BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits); |
| 7781 |
for (uint32_t same_bp_variant_idx = 0; same_bp_variant_idx != same_bp_variant_ct; ++same_bp_variant_idx) { |
| 7782 |
const uint32_t scan_variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 7783 |
if (!memequal(cur_variant_id, variant_ids[scan_variant_uidx], cur_variant_id_blen)) { |
| 7784 |
continue; |
| 7785 |
} |
| 7786 |
if (unlikely(variant_uidx != UINT32_MAX)) { |
| 7787 |
snprintf(g_logbuf, kLogbufSize, "Error: --pgen-diff: Multiple instances of variant ID '%s' at position %s:%u in main fileset.\n", cur_variant_id, chr_buf, cur_included_bp); |
| 7788 |
goto PgenDiff_ret_INCONSISTENT_INPUT_WW_N; |
| 7789 |
} |
| 7790 |
variant_uidx = scan_variant_uidx; |
| 7791 |
} |
| 7792 |
if (variant_uidx == UINT32_MAX) { |
| 7793 |
continue; |
| 7794 |
} |
| 7795 |
if (unlikely(IsSet(already_seen, variant_uidx))) { |
| 7796 |
snprintf(g_logbuf, kLogbufSize, "Error: --pgen-diff: Multiple instances of variant ID '%s' at position %s:%u in .pvar file.\n", cur_variant_id, chr_buf, cur_included_bp); |
| 7797 |
goto PgenDiff_ret_INCONSISTENT_INPUT_WW_N; |
| 7798 |
} |
| 7799 |
SetBit(variant_uidx, already_seen); |
| 7800 |
} |
| 7801 |
|
| 7802 |
uintptr_t allele_idx_offset_base1 = variant_uidx * 2; |
| 7803 |
if (allele_idx_offsets) { |
| 7804 |
allele_idx_offset_base1 = allele_idx_offsets[variant_uidx]; |
| 7805 |
cur_allele_ct1 = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base1; |
| 7806 |
} |
| 7807 |
const char* const* cur_allele1s = &(allele_storage[allele_idx_offset_base1]); |
| 7808 |
uintptr_t allele_idx_offset_base2 = variant_uidx2 * 2; |
| 7809 |
if (allele_idx_offsets2) { |
| 7810 |
allele_idx_offset_base2 = allele_idx_offsets2[variant_uidx2]; |
| 7811 |
cur_allele_ct2 = allele_idx_offsets2[variant_uidx2 + 1] - allele_idx_offset_base2; |
| 7812 |
} |
| 7813 |
|
| 7814 |
if (!dosage_needed) { |
| 7815 |
if (cur_allele_ct1 == 2) { |
| 7816 |
reterr = PgrGet(sample_include, pssi1, sample_ct, variant_uidx, simple_pgrp, pgv1.genovec); |
| 7817 |
} else { |
| 7818 |
reterr = PgrGetM(sample_include, pssi1, sample_ct, variant_uidx, simple_pgrp, &pgv1); |
| 7819 |
} |
| 7820 |
if (unlikely(reterr)) { |
| 7821 |
PgenErrPrintNV(reterr, variant_uidx); |
| 7822 |
goto PgenDiff_ret_1; |
| 7823 |
} |
| 7824 |
if (cur_allele_ct2 == 2) { |
| 7825 |
reterr = PgrGet(sample_include2, pssi2, sample_ct, variant_uidx2, &simple_pgr2, pgv2.genovec); |
| 7826 |
} else { |
| 7827 |
reterr = PgrGetM(sample_include2, pssi2, sample_ct, variant_uidx2, &simple_pgr2, &pgv2); |
| 7828 |
} |
| 7829 |
} else { |
| 7830 |
if (cur_allele_ct1 == 2) { |
| 7831 |
reterr = PgrGetD(sample_include, pssi1, sample_ct, variant_uidx, simple_pgrp, pgv1.genovec, pgv1.dosage_present, pgv1.dosage_main, &pgv1.dosage_ct); |
| 7832 |
} else { |
| 7833 |
reterr = PgrGetMD(sample_include, pssi1, sample_ct, variant_uidx, simple_pgrp, &pgv1); |
| 7834 |
} |
| 7835 |
if (unlikely(reterr)) { |
| 7836 |
PgenErrPrintNV(reterr, variant_uidx); |
| 7837 |
goto PgenDiff_ret_1; |
| 7838 |
} |
| 7839 |
if (cur_allele_ct2 == 2) { |
| 7840 |
reterr = PgrGetD(sample_include2, pssi2, sample_ct, variant_uidx2, &simple_pgr2, pgv2.genovec, pgv2.dosage_present, pgv2.dosage_main, &pgv2.dosage_ct); |
| 7841 |
} else { |
| 7842 |
reterr = PgrGetMD(sample_include2, pssi2, sample_ct, variant_uidx2, &simple_pgr2, &pgv2); |
| 7843 |
} |
| 7844 |
} |
| 7845 |
if (unlikely(reterr)) { |
| 7846 |
PgenErrPrintNV(reterr, variant_uidx2); |
| 7847 |
goto PgenDiff_ret_1; |
| 7848 |
} |
| 7849 |
|
| 7850 |
uintptr_t* genovec1 = pgv1.genovec; |
| 7851 |
uintptr_t* genovec2 = pgv2.genovec; |
| 7852 |
uint32_t merged_allele_ct = 0; |
| 7853 |
uint32_t merged_provref = 0; |
| 7854 |
{ |
| 7855 |
char* ref_allele2 = token_ptrs[2]; |
| 7856 |
const uint32_t ref_allele2_slen = token_slens[2]; |
| 7857 |
ref_allele2[ref_allele2_slen] = '\0'; |
| 7858 |
cur_allele2s[0] = ref_allele2; |
| 7859 |
|
| 7860 |
const uint32_t last_allele2_idx = cur_allele_ct2 - 1; |
| 7861 |
char* alt_iter = token_ptrs[3]; |
| 7862 |
alt_iter[token_slens[3]] = '\0'; |
| 7863 |
for (uint32_t allele2_idx = 1; allele2_idx != last_allele2_idx; ++allele2_idx) { |
| 7864 |
char* alt_end = AdvToDelim(alt_iter, ','); |
| 7865 |
*alt_end = '\0'; |
| 7866 |
cur_allele2s[allele2_idx] = alt_iter; |
| 7867 |
alt_iter = &(alt_end[1]); |
| 7868 |
} |
| 7869 |
cur_allele2s[last_allele2_idx] = alt_iter; |
| 7870 |
|
| 7871 |
// We verify during .pvar load that, if a missing allele code is |
| 7872 |
// present, it's in a biallelic variant. bugfix (3 Feb 2021): forgot |
| 7873 |
// that biallelic variants can have *both* allele codes missing |
| 7874 |
// (consider a .ped-derived variant with only missing calls). |
| 7875 |
// We verify below that the missing allele code does not appear in the |
| 7876 |
// actual genotype calls. |
| 7877 |
uint32_t missing1_state = 0; |
| 7878 |
for (uint32_t allele1_idx = 0; allele1_idx != cur_allele_ct1; ++allele1_idx) { |
| 7879 |
const char* cur_allele1 = cur_allele1s[allele1_idx]; |
| 7880 |
if (strequal_k_unsafe(cur_allele1, ".")) { |
| 7881 |
missing1_state |= allele1_idx + 1; |
| 7882 |
} |
| 7883 |
} |
| 7884 |
ZeroTrailingNyps(sample_ct, genovec1); |
| 7885 |
ZeroTrailingNyps(sample_ct, genovec2); |
| 7886 |
if (missing1_state) { |
| 7887 |
assert(cur_allele_ct1 == 2); |
| 7888 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 7889 |
GenoarrCountFreqsUnsafe(genovec1, sample_ct, genocounts); |
| 7890 |
if (unlikely(genocounts[1] || ((missing1_state & 1) && genocounts[0]) || ((missing1_state & 2) && genocounts[2]) || pgv1.dosage_ct)) { |
| 7891 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing allele for variant '%s' at position %s:%u is present in the .pgen.\n", variant_ids[variant_uidx], chr_buf, cur_included_bp); |
| 7892 |
goto PgenDiff_ret_INCONSISTENT_INPUT_WW_N; |
| 7893 |
} |
| 7894 |
if (missing1_state & 1) { |
| 7895 |
remap1[0] = kMissingAlleleCode; |
| 7896 |
} |
| 7897 |
if (missing1_state & 2) { |
| 7898 |
remap1[1] = kMissingAlleleCode; |
| 7899 |
} |
| 7900 |
} |
| 7901 |
uint32_t missing2_state = 0; |
| 7902 |
for (uint32_t allele2_idx = 0; allele2_idx != cur_allele_ct2; ++allele2_idx) { |
| 7903 |
const char* cur_allele2 = cur_allele2s[allele2_idx]; |
| 7904 |
if (((cur_allele2[0] == '.') || (cur_allele2[0] == input_missing_geno_char)) && (cur_allele2[1] == '\0')) { |
| 7905 |
if (unlikely(cur_allele_ct2 > 2)) { |
| 7906 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing allele in multiallelic variant on line %" PRIuPTR " of --pgen-diff .pvar file.\n", pvar_line_idx); |
| 7907 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7908 |
} |
| 7909 |
missing2_state |= allele2_idx + 1; |
| 7910 |
} |
| 7911 |
} |
| 7912 |
if (missing2_state) { |
| 7913 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 7914 |
GenoarrCountFreqsUnsafe(genovec2, sample_ct, genocounts); |
| 7915 |
if (unlikely(genocounts[1] || ((missing2_state & 1) && genocounts[0]) || ((missing2_state & 2) && genocounts[2]) || ((cur_allele_ct2 > 2) && (pgv2.patch_01_ct || pgv2.patch_10_ct)) || pgv2.dosage_ct)) { |
| 7916 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing allele on line %" PRIuPTR " of --pgen-diff .pvar file is present in the .pgen.\n", pvar_line_idx); |
| 7917 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7918 |
} |
| 7919 |
if (missing2_state & 1) { |
| 7920 |
remap2[0] = kMissingAlleleCode; |
| 7921 |
} |
| 7922 |
if (missing2_state & 2) { |
| 7923 |
remap2[1] = kMissingAlleleCode; |
| 7924 |
} |
| 7925 |
} |
| 7926 |
const uint32_t provisional_ref1 = all_nonref1 || (nonref_flags1 && IsSet(nonref_flags1, variant_uidx)); |
| 7927 |
if ((!provisional_ref1) && (missing1_state & 1)) { |
| 7928 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing REF allele for variant '%s' at position %s:%u is not flagged as provisional.\n", variant_ids[variant_uidx], chr_buf, cur_included_bp); |
| 7929 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7930 |
} |
| 7931 |
const uint32_t provisional_ref2 = all_nonref2 || (nonref_flags2 && IsSet(nonref_flags2, variant_uidx2)); |
| 7932 |
if ((!provisional_ref2) && (missing2_state & 1)) { |
| 7933 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing REF allele on line %" PRIuPTR " of --pgen-diff .pvar file is not flagged as provisional.\n", pvar_line_idx); |
| 7934 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7935 |
} |
| 7936 |
if ((missing1_state == 3) && (missing2_state == 3)) { |
| 7937 |
// Both variants are all-missing, no differences possible. |
| 7938 |
continue; |
| 7939 |
} |
| 7940 |
// Initialize these to the index of the first nonmissing allele. |
| 7941 |
uint32_t allele1_alt_start = (missing1_state & 1) + (missing1_state == 3); |
| 7942 |
uint32_t allele2_alt_start = (missing2_state & 1) + (missing2_state == 3); |
| 7943 |
merged_provref = provisional_ref1; |
| 7944 |
if ((!provisional_ref1) || ((!(missing1_state & 1)) && provisional_ref2)) { |
| 7945 |
// - If REF1 is not provisional, it's always the merged REF allele. |
| 7946 |
// - If REF1 is provisional, it's still the merged REF allele if REF2 |
| 7947 |
// is also provisional and REF1 is nonmissing. |
| 7948 |
if (unlikely((!provisional_ref2) && (!strequal_overread(cur_allele1s[0], cur_allele2s[0])))) { |
| 7949 |
snprintf(g_logbuf, kLogbufSize, "Error: REF allele on line %" PRIuPTR " of --pgen-diff .pvar file conflicts with loaded REF allele, and neither are flagged as provisional.\n", pvar_line_idx); |
| 7950 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 7951 |
} |
| 7952 |
merged_alleles[0] = cur_allele1s[0]; |
| 7953 |
remap1[0] = 0; |
| 7954 |
allele1_alt_start = 1 + ((missing1_state >> 1) & 1); |
| 7955 |
} else { |
| 7956 |
// REF1 is not the merged REF allele. |
| 7957 |
if (!(missing2_state & 1)) { |
| 7958 |
// If REF2 can be the merged REF allele (i.e. it isn't missing), |
| 7959 |
// make it so. |
| 7960 |
merged_alleles[0] = cur_allele2s[0]; |
| 7961 |
remap2[0] = 0; |
| 7962 |
allele2_alt_start = 1 + ((missing2_state >> 1) & 1); |
| 7963 |
merged_provref = provisional_ref2; |
| 7964 |
} else { |
| 7965 |
// Both REFs missing. Treat main dataset ALT1 as REF if it isn't |
| 7966 |
// missing. |
| 7967 |
if (!(missing1_state & 2)) { |
| 7968 |
merged_alleles[0] = cur_allele1s[1]; |
| 7969 |
remap1[1] = 0; |
| 7970 |
allele1_alt_start = 2; |
| 7971 |
} else { |
| 7972 |
// Other dataset's ALT1 guaranteed to be nonmissing if we get |
| 7973 |
// here. |
| 7974 |
merged_alleles[0] = cur_allele2s[1]; |
| 7975 |
remap2[1] = 0; |
| 7976 |
allele2_alt_start = 2; |
| 7977 |
} |
| 7978 |
} |
| 7979 |
} |
| 7980 |
const uint32_t cur_max_merged_alleles = 1 + cur_allele_ct1 + cur_allele_ct2 - allele1_alt_start - allele2_alt_start; |
| 7981 |
const uint32_t cur_htable_size = (cur_max_merged_alleles * 9) / 2; |
| 7982 |
SetAllU32Arr(cur_htable_size, merged_alleles_htable); |
| 7983 |
// See e.g. PopulateStrboxHtable(). |
| 7984 |
uint32_t hashval = Hashceil(merged_alleles[0], strlen(merged_alleles[0]), cur_htable_size); |
| 7985 |
merged_alleles_htable[hashval] = 0; |
| 7986 |
++merged_allele_ct; |
| 7987 |
|
| 7988 |
for (uint32_t allele1_idx = allele1_alt_start; allele1_idx != cur_allele_ct1; ++allele1_idx) { |
| 7989 |
if ((allele1_idx < 2) && ((missing1_state >> allele1_idx) & 1)) { |
| 7990 |
continue; |
| 7991 |
} |
| 7992 |
const char* cur_allele1 = cur_allele1s[allele1_idx]; |
| 7993 |
const uint32_t cur_allele1_slen = strlen(cur_allele1); |
| 7994 |
const uint32_t cur_idx = IdHtableAdd(cur_allele1, merged_alleles, cur_allele1_slen, cur_htable_size, merged_allele_ct, merged_alleles_htable); |
| 7995 |
if (cur_idx == UINT32_MAX) { |
| 7996 |
if (unlikely(merged_allele_ct == kPglMaxAlleleCt)) { |
| 7997 |
logerrprintfww("Error: Too many alleles across --pgen-diff and main filesets for variant '%s' at position %s:%u. (This " PROG_NAME_STR " build is limited to " PGL_MAX_ALLELE_CT_STR ".)\n", variant_ids[variant_uidx], chr_buf, cur_included_bp); |
| 7998 |
reterr = kPglRetNotYetSupported; |
| 7999 |
goto PgenDiff_ret_1; |
| 8000 |
} |
| 8001 |
remap1[allele1_idx] = merged_allele_ct; |
| 8002 |
merged_alleles[merged_allele_ct] = cur_allele1; |
| 8003 |
++merged_allele_ct; |
| 8004 |
} else { |
| 8005 |
remap1[allele1_idx] = cur_idx; |
| 8006 |
} |
| 8007 |
} |
| 8008 |
for (uint32_t allele2_idx = allele2_alt_start; allele2_idx != cur_allele_ct2; ++allele2_idx) { |
| 8009 |
if ((allele2_idx < 2) && ((missing2_state >> allele2_idx) & 1)) { |
| 8010 |
continue; |
| 8011 |
} |
| 8012 |
const char* cur_allele2 = cur_allele2s[allele2_idx]; |
| 8013 |
const uint32_t cur_allele2_slen = strlen(cur_allele2); |
| 8014 |
const uint32_t cur_idx = IdHtableAdd(cur_allele2, merged_alleles, cur_allele2_slen, cur_htable_size, merged_allele_ct, merged_alleles_htable); |
| 8015 |
if (cur_idx == UINT32_MAX) { |
| 8016 |
if (unlikely(merged_allele_ct == kPglMaxAlleleCt)) { |
| 8017 |
logerrprintfww("Error: Too many alleles across --pgen-diff and main filesets for variant '%s' at position %s:%u. (This " PROG_NAME_STR " build is limited to " PGL_MAX_ALLELE_CT_STR ".)\n", variant_ids[variant_uidx], chr_buf, cur_included_bp); |
| 8018 |
reterr = kPglRetNotYetSupported; |
| 8019 |
goto PgenDiff_ret_1; |
| 8020 |
} |
| 8021 |
remap2[allele2_idx] = merged_allele_ct; |
| 8022 |
merged_alleles[merged_allele_ct] = cur_allele2; |
| 8023 |
++merged_allele_ct; |
| 8024 |
} else { |
| 8025 |
remap2[allele2_idx] = cur_idx; |
| 8026 |
} |
| 8027 |
} |
| 8028 |
const uint32_t merged_allele_ctl = BitCtToWordCt(merged_allele_ct); |
| 8029 |
if (unlikely(DuplicateAllelePresent(remap2, cur_allele_ct2, merged_allele_ctl, remap_seen))) { |
| 8030 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate allele code on line %" PRIuPTR " of --pgen-diff .pvar file.\n", pvar_line_idx); |
| 8031 |
goto PgenDiff_ret_MALFORMED_INPUT_WW_N; |
| 8032 |
} |
| 8033 |
if (merged_allele_ct == 1) { |
| 8034 |
if (!include_missing) { |
| 8035 |
// Only possible difference is missing vs. not-missing. |
| 8036 |
continue; |
| 8037 |
} |
| 8038 |
assert(missing1_state); |
| 8039 |
merged_alleles[1] = cur_allele1s[ctzu32(missing1_state)]; |
| 8040 |
merged_allele_ct = 2; |
| 8041 |
} |
| 8042 |
} |
| 8043 |
uint32_t diff_ct = 0; |
| 8044 |
if (merged_allele_ct == 2) { |
| 8045 |
// Note that these two conditions aren't necessarily synonymous, due to |
| 8046 |
// missing alleles. |
| 8047 |
if ((remap1[0] == 1) || (remap1[1] == 0)) { |
| 8048 |
GenovecInvertUnsafe(sample_ct, genovec1); |
| 8049 |
ZeroTrailingNyps(sample_ct, genovec1); |
| 8050 |
if (dosage_needed) { |
| 8051 |
BiallelicDosage16Invert(pgv1.dosage_ct, pgv1.dosage_main); |
| 8052 |
} |
| 8053 |
} |
| 8054 |
if ((remap2[0] == 1) || (remap2[1] == 0)) { |
| 8055 |
GenovecInvertUnsafe(sample_ct, genovec2); |
| 8056 |
ZeroTrailingNyps(sample_ct, genovec2); |
| 8057 |
if (dosage_needed) { |
| 8058 |
BiallelicDosage16Invert(pgv2.dosage_ct, pgv2.dosage_main); |
| 8059 |
} |
| 8060 |
} |
| 8061 |
if (!dosage_needed) { |
| 8062 |
if (!sample1_idx_to_2) { |
| 8063 |
// Optimize common case where no reshuffling is needed. |
| 8064 |
for (uint32_t widx = 0; widx != sample_ctl2; ++widx) { |
| 8065 |
uintptr_t geno_word1 = genovec1[widx]; |
| 8066 |
uintptr_t geno_word2 = genovec2[widx]; |
| 8067 |
uintptr_t diff_word = geno_word1 ^ geno_word2; |
| 8068 |
if (!diff_word) { |
| 8069 |
continue; |
| 8070 |
} |
| 8071 |
if (!include_missing) { |
| 8072 |
const uintptr_t missing_word1 = geno_word1 & (geno_word1 >> 1) & kMask5555; |
| 8073 |
const uintptr_t missing_word2 = geno_word2 & (geno_word2 >> 1) & kMask5555; |
| 8074 |
diff_word &= ~((missing_word1 | missing_word2) * 3); |
| 8075 |
if (!diff_word) { |
| 8076 |
continue; |
| 8077 |
} |
| 8078 |
} |
| 8079 |
const uint32_t sample_idx_base = widx * kBitsPerWordD2; |
| 8080 |
do { |
| 8081 |
const uint32_t rshift = ctzw(diff_word) & (~1); |
| 8082 |
const uintptr_t geno1 = (geno_word1 >> rshift) & 3; |
| 8083 |
const uintptr_t geno2 = (geno_word2 >> rshift) & 3; |
| 8084 |
diff_sample_idxs[diff_ct] = sample_idx_base + (rshift / 2); |
| 8085 |
PgenDiffGtEntry* gt_entryp = &(gt_entries[diff_ct]); |
| 8086 |
gt_entryp->dac1 = biallelic_dac[geno1]; |
| 8087 |
gt_entryp->dac2 = biallelic_dac[geno2]; |
| 8088 |
++diff_ct; |
| 8089 |
diff_word &= ~((3 * k1LU) << rshift); |
| 8090 |
} while (diff_word); |
| 8091 |
} |
| 8092 |
} else { |
| 8093 |
// biallelic, !dosage_needed, must reshuffle |
| 8094 |
// possible todo: parallelize this |
| 8095 |
const uint32_t sample_ctl2_m1 = sample_ctl2 - 1; |
| 8096 |
uint32_t loop_len = kBitsPerWordD2; |
| 8097 |
for (uint32_t widx = 0; ; ++widx) { |
| 8098 |
if (widx >= sample_ctl2_m1) { |
| 8099 |
if (widx > sample_ctl2_m1) { |
| 8100 |
break; |
| 8101 |
} |
| 8102 |
loop_len = ModNz(sample_ct, kBitsPerWordD2); |
| 8103 |
} |
| 8104 |
const uint32_t sample_idx_base = widx * kBitsPerWordD2; |
| 8105 |
const uint32_t* cur_sample1_idx_to_2 = &(sample1_idx_to_2[sample_idx_base]); |
| 8106 |
uintptr_t geno_word1 = genovec1[widx]; |
| 8107 |
if (include_missing) { |
| 8108 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 8109 |
const uint32_t sample_idx2 = cur_sample1_idx_to_2[uii]; |
| 8110 |
const uintptr_t geno1 = geno_word1 & 3; |
| 8111 |
const uintptr_t geno2 = GetNyparrEntry(genovec2, sample_idx2); |
| 8112 |
geno_word1 >>= 2; |
| 8113 |
if (geno1 == geno2) { |
| 8114 |
continue; |
| 8115 |
} |
| 8116 |
diff_sample_idxs[diff_ct] = sample_idx_base + uii; |
| 8117 |
PgenDiffGtEntry* gt_entryp = &(gt_entries[diff_ct]); |
| 8118 |
gt_entryp->dac1 = biallelic_dac[geno1]; |
| 8119 |
gt_entryp->dac2 = biallelic_dac[geno2]; |
| 8120 |
++diff_ct; |
| 8121 |
} |
| 8122 |
} else { |
| 8123 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 8124 |
const uint32_t sample_idx2 = cur_sample1_idx_to_2[uii]; |
| 8125 |
const uintptr_t geno1 = geno_word1 & 3; |
| 8126 |
const uintptr_t geno2 = GetNyparrEntry(genovec2, sample_idx2); |
| 8127 |
geno_word1 >>= 2; |
| 8128 |
if ((geno1 == geno2) || (geno1 == 3) || (geno2 == 3)) { |
| 8129 |
continue; |
| 8130 |
} |
| 8131 |
diff_sample_idxs[diff_ct] = sample_idx_base + uii; |
| 8132 |
PgenDiffGtEntry* gt_entryp = &(gt_entries[diff_ct]); |
| 8133 |
gt_entryp->dac1 = biallelic_dac[geno1]; |
| 8134 |
gt_entryp->dac2 = biallelic_dac[geno2]; |
| 8135 |
++diff_ct; |
| 8136 |
} |
| 8137 |
} |
| 8138 |
} |
| 8139 |
} |
| 8140 |
} else { |
| 8141 |
// biallelic, dosage_needed |
| 8142 |
PopulateDenseDosage(genovec1, pgv1.dosage_present, pgv1.dosage_main, sample_ct, pgv1.dosage_ct, biallelic_dosage1); |
| 8143 |
PopulateDenseDosage(genovec2, pgv2.dosage_present, pgv2.dosage_main, sample_ct, pgv2.dosage_ct, biallelic_dosage2); |
| 8144 |
if (!sample1_idx_to_2) { |
| 8145 |
const uintptr_t dosage_blen = sample_ct * sizeof(Dosage); |
| 8146 |
uintptr_t sample_idx = 0; |
| 8147 |
if (!is_x) { |
| 8148 |
// don't need to special-case chrY here since we just skip |
| 8149 |
// nonmales in the reporting step |
| 8150 |
while (1) { |
| 8151 |
const uintptr_t diff_byte_offset = FirstUnequalFrom(biallelic_dosage1, biallelic_dosage2, sample_idx * sizeof(Dosage), dosage_blen); |
| 8152 |
if (diff_byte_offset == dosage_blen) { |
| 8153 |
break; |
| 8154 |
} |
| 8155 |
sample_idx = diff_byte_offset / sizeof(Dosage); |
| 8156 |
const uint32_t d1 = biallelic_dosage1[sample_idx]; |
| 8157 |
const uint32_t d2 = biallelic_dosage2[sample_idx]; |
| 8158 |
if (((d1 != kDosageMissing) && (d2 != kDosageMissing)) || include_missing) { |
| 8159 |
// Since this doesn't separate out the kDosageMissing cases, |
| 8160 |
// it needs to be updated if Dosage is widened (since |
| 8161 |
// kDosageMissing would then be adjacent to 0 in uint32_t |
| 8162 |
// space). |
| 8163 |
if (abs_i32(d1 - d2) > dosage_cur_tol) { |
| 8164 |
diff_sample_idxs[diff_ct] = sample_idx; |
| 8165 |
ds_entries[diff_ct * 2] = d1; |
| 8166 |
ds_entries[diff_ct * 2 + 1] = d2; |
| 8167 |
++diff_ct; |
| 8168 |
} |
| 8169 |
} |
| 8170 |
++sample_idx; |
| 8171 |
} |
| 8172 |
} else { |
| 8173 |
// is_x |
| 8174 |
while (1) { |
| 8175 |
const uintptr_t diff_byte_offset = FirstUnequalFrom(biallelic_dosage1, biallelic_dosage2, sample_idx * sizeof(Dosage), dosage_blen); |
| 8176 |
if (diff_byte_offset == dosage_blen) { |
| 8177 |
break; |
| 8178 |
} |
| 8179 |
sample_idx = diff_byte_offset / sizeof(Dosage); |
| 8180 |
const uint32_t d1 = biallelic_dosage1[sample_idx]; |
| 8181 |
const uint32_t d2 = biallelic_dosage2[sample_idx]; |
| 8182 |
if (((d1 != kDosageMissing) && (d2 != kDosageMissing)) || include_missing) { |
| 8183 |
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx); |
| 8184 |
if (abs_i32(d1 - d2) > dosage_sex_tols[is_male]) { |
| 8185 |
diff_sample_idxs[diff_ct] = sample_idx; |
| 8186 |
ds_entries[diff_ct * 2] = d1; |
| 8187 |
ds_entries[diff_ct * 2 + 1] = d2; |
| 8188 |
++diff_ct; |
| 8189 |
} |
| 8190 |
} |
| 8191 |
++sample_idx; |
| 8192 |
} |
| 8193 |
} |
| 8194 |
} else { |
| 8195 |
if (!is_x) { |
| 8196 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 8197 |
const uint32_t d1 = biallelic_dosage1[sample_idx]; |
| 8198 |
const uint32_t sample_idx2 = sample1_idx_to_2[sample_idx]; |
| 8199 |
const uint32_t d2 = biallelic_dosage2[sample_idx2]; |
| 8200 |
if (((d1 != kDosageMissing) && (d2 != kDosageMissing)) || include_missing) { |
| 8201 |
if (abs_i32(d1 - d2) > dosage_cur_tol) { |
| 8202 |
diff_sample_idxs[diff_ct] = sample_idx; |
| 8203 |
ds_entries[diff_ct * 2] = d1; |
| 8204 |
ds_entries[diff_ct * 2 + 1] = d2; |
| 8205 |
++diff_ct; |
| 8206 |
} |
| 8207 |
} |
| 8208 |
} |
| 8209 |
} else { |
| 8210 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 8211 |
const uint32_t d1 = biallelic_dosage1[sample_idx]; |
| 8212 |
const uint32_t sample_idx2 = sample1_idx_to_2[sample_idx]; |
| 8213 |
const uint32_t d2 = biallelic_dosage2[sample_idx2]; |
| 8214 |
if (((d1 != kDosageMissing) && (d2 != kDosageMissing)) || include_missing) { |
| 8215 |
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx); |
| 8216 |
if (abs_i32(d1 - d2) > dosage_sex_tols[is_male]) { |
| 8217 |
diff_sample_idxs[diff_ct] = sample_idx; |
| 8218 |
ds_entries[diff_ct * 2] = d1; |
| 8219 |
ds_entries[diff_ct * 2 + 1] = d2; |
| 8220 |
++diff_ct; |
| 8221 |
} |
| 8222 |
} |
| 8223 |
} |
| 8224 |
} |
| 8225 |
} |
| 8226 |
} |
| 8227 |
} else { |
| 8228 |
if (!dosage_needed) { |
| 8229 |
PglMultiallelicSparseToDense(genovec1, pgv1.patch_01_set, pgv1.patch_01_vals, pgv1.patch_10_set, pgv1.patch_10_vals, remap1, sample_ct, pgv1.patch_01_ct, pgv1.patch_10_ct, nullptr, wide_codes1); |
| 8230 |
PglMultiallelicSparseToDense(genovec2, pgv2.patch_01_set, pgv2.patch_01_vals, pgv2.patch_10_set, pgv2.patch_10_vals, remap2, sample_ct, pgv2.patch_01_ct, pgv2.patch_10_ct, nullptr, wide_codes2); |
| 8231 |
const DoubleAlleleCode* wc1_alias = R_CAST(DoubleAlleleCode*, wide_codes1); |
| 8232 |
const DoubleAlleleCode* wc2_alias = R_CAST(DoubleAlleleCode*, wide_codes2); |
| 8233 |
if (!sample1_idx_to_2) { |
| 8234 |
const uintptr_t wide_codes_blen = sample_ct * 2 * sizeof(AlleleCode); |
| 8235 |
uintptr_t sample_idx = 0; |
| 8236 |
while (1) { |
| 8237 |
const uintptr_t diff_byte_offset = FirstUnequalFrom(wc1_alias, wc2_alias, sample_idx * sizeof(DoubleAlleleCode), wide_codes_blen); |
| 8238 |
if (diff_byte_offset == wide_codes_blen) { |
| 8239 |
break; |
| 8240 |
} |
| 8241 |
sample_idx = diff_byte_offset / (2 * sizeof(AlleleCode)); |
| 8242 |
const DoubleAlleleCode dac1 = wc1_alias[sample_idx]; |
| 8243 |
const DoubleAlleleCode dac2 = wc2_alias[sample_idx]; |
| 8244 |
if (((dac1 != kMissingDoubleAlleleCode) && (dac2 != kMissingDoubleAlleleCode)) || include_missing) { |
| 8245 |
diff_sample_idxs[diff_ct] = sample_idx; |
| 8246 |
PgenDiffGtEntry* gt_entryp = &(gt_entries[diff_ct]); |
| 8247 |
gt_entryp->dac1 = dac1; |
| 8248 |
gt_entryp->dac2 = dac2; |
| 8249 |
++diff_ct; |
| 8250 |
} |
| 8251 |
++sample_idx; |
| 8252 |
} |
| 8253 |
} else { |
| 8254 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 8255 |
const DoubleAlleleCode dac1 = wc1_alias[sample_idx]; |
| 8256 |
const uint32_t sample_idx2 = sample1_idx_to_2[sample_idx]; |
| 8257 |
const DoubleAlleleCode dac2 = wc2_alias[sample_idx2]; |
| 8258 |
if ((dac1 == dac2) || (((dac1 == kMissingAlleleCode) || (dac2 == kMissingAlleleCode)) && (!include_missing))) { |
| 8259 |
continue; |
| 8260 |
} |
| 8261 |
diff_sample_idxs[diff_ct] = sample_idx; |
| 8262 |
PgenDiffGtEntry* gt_entryp = &(gt_entries[diff_ct]); |
| 8263 |
gt_entryp->dac1 = dac1; |
| 8264 |
gt_entryp->dac2 = dac2; |
| 8265 |
++diff_ct; |
| 8266 |
} |
| 8267 |
} |
| 8268 |
} else { |
| 8269 |
// multiallelic, dosage_needed |
| 8270 |
logerrputs("Error: --pgen-diff multiallelic-variant dosage support is under development.\n"); |
| 8271 |
reterr = kPglRetNotYetSupported; |
| 8272 |
goto PgenDiff_ret_1; |
| 8273 |
} |
| 8274 |
} |
| 8275 |
if (!diff_ct) { |
| 8276 |
continue; |
| 8277 |
} |
| 8278 |
grand_diff_ct += diff_ct; |
| 8279 |
const uint32_t merged_allele_ct_m1 = merged_allele_ct - 1; |
| 8280 |
uint32_t cur_autosomal_diploid = is_autosomal_diploid; |
| 8281 |
for (uint32_t diff_idx = 0; diff_idx != diff_ct; ++diff_idx) { |
| 8282 |
const uint32_t sample_uidx = sample_idx_to_uidx[diff_sample_idxs[diff_idx]]; |
| 8283 |
if (is_x) { |
| 8284 |
cur_autosomal_diploid = !IsSet(sex_male, sample_uidx); |
| 8285 |
} else if (is_y) { |
| 8286 |
// unknown-sex prohibited, so sex_male is fine |
| 8287 |
if (!IsSet(sex_male, sample_uidx)) { |
| 8288 |
--grand_diff_ct; |
| 8289 |
continue; |
| 8290 |
} |
| 8291 |
} |
| 8292 |
if (chr_col) { |
| 8293 |
cswritep = memcpyax(cswritep, chr_buf, chr_slen, '\t'); |
| 8294 |
} |
| 8295 |
if (pos_col) { |
| 8296 |
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep); |
| 8297 |
} |
| 8298 |
if (varid_col) { |
| 8299 |
cswritep = strcpyax(cswritep, variant_ids[variant_uidx], '\t'); |
| 8300 |
} |
| 8301 |
if (ref_col) { |
| 8302 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 8303 |
goto PgenDiff_ret_WRITE_FAIL; |
| 8304 |
} |
| 8305 |
cswritep = strcpyax(cswritep, merged_alleles[0], '\t'); |
| 8306 |
} |
| 8307 |
if (alt_col) { |
| 8308 |
for (uint32_t allele_idx = 1; allele_idx != merged_allele_ct; ++allele_idx) { |
| 8309 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 8310 |
goto PgenDiff_ret_WRITE_FAIL; |
| 8311 |
} |
| 8312 |
cswritep = strcpyax(cswritep, merged_alleles[allele_idx], ','); |
| 8313 |
} |
| 8314 |
cswritep[-1] = '\t'; |
| 8315 |
} |
| 8316 |
if (provref_col) { |
| 8317 |
*cswritep++ = merged_provref? 'Y' : 'N'; |
| 8318 |
*cswritep++ = '\t'; |
| 8319 |
} |
| 8320 |
const char* cur_sample_id = &(sample_ids[sample_uidx * max_sample_id_blen]); |
| 8321 |
if (!fid_col) { |
| 8322 |
cur_sample_id = AdvPastDelim(cur_sample_id, '\t'); |
| 8323 |
} |
| 8324 |
cswritep = strcpya(cswritep, cur_sample_id); |
| 8325 |
if (sid_col) { |
| 8326 |
*cswritep++ = '\t'; |
| 8327 |
if (sids) { |
| 8328 |
cswritep = strcpya(cswritep, &(sids[sample_uidx * max_sid_blen])); |
| 8329 |
} else { |
| 8330 |
*cswritep++ = '0'; |
| 8331 |
} |
| 8332 |
} |
| 8333 |
if (geno_col) { |
| 8334 |
if (!dosage_needed) { |
| 8335 |
const PgenDiffGtEntry entry = gt_entries[diff_idx]; |
| 8336 |
if (!dosage_reported) { |
| 8337 |
*cswritep++ = '\t'; |
| 8338 |
if (entry.dac1 == kMissingDoubleAlleleCode) { |
| 8339 |
if (cur_autosomal_diploid) { |
| 8340 |
cswritep = strcpya_k(cswritep, "./."); |
| 8341 |
} else { |
| 8342 |
*cswritep++ = '.'; |
| 8343 |
} |
| 8344 |
} else { |
| 8345 |
const AlleleCode gt1_low = entry.dac1; // truncate |
| 8346 |
const AlleleCode gt1_high = entry.dac1 >> (8 * sizeof(AlleleCode)); |
| 8347 |
cswritep = u32toa(gt1_low, cswritep); |
| 8348 |
if (cur_autosomal_diploid || (gt1_low != gt1_high)) { |
| 8349 |
*cswritep++ = '/'; |
| 8350 |
cswritep = u32toa(gt1_high, cswritep); |
| 8351 |
} |
| 8352 |
} |
| 8353 |
*cswritep++ = '\t'; |
| 8354 |
if (entry.dac2 == kMissingDoubleAlleleCode) { |
| 8355 |
if (cur_autosomal_diploid) { |
| 8356 |
cswritep = strcpya_k(cswritep, "./."); |
| 8357 |
} else { |
| 8358 |
*cswritep++ = '.'; |
| 8359 |
} |
| 8360 |
} else { |
| 8361 |
const AlleleCode gt2_low = entry.dac2; // truncate |
| 8362 |
const AlleleCode gt2_high = entry.dac2 >> (8 * sizeof(AlleleCode)); |
| 8363 |
cswritep = u32toa(gt2_low, cswritep); |
| 8364 |
if (cur_autosomal_diploid || (gt2_low != gt2_high)) { |
| 8365 |
*cswritep++ = '/'; |
| 8366 |
cswritep = u32toa(gt2_high, cswritep); |
| 8367 |
} |
| 8368 |
} |
| 8369 |
} else { |
| 8370 |
// dosage_reported |
| 8371 |
*cswritep++ = '\t'; |
| 8372 |
const AlleleCode gt1_low = entry.dac1; // truncate |
| 8373 |
const AlleleCode gt1_high = entry.dac1 >> (8 * sizeof(AlleleCode)); |
| 8374 |
if (cur_autosomal_diploid) { |
| 8375 |
cswritep = PrintMultiallelicHcAsDs(gt1_low, gt1_high, merged_allele_ct, cswritep); |
| 8376 |
} else { |
| 8377 |
cswritep = PrintMultiallelicHcAsHaploidDs(gt1_low, gt1_high, merged_allele_ct, cswritep); |
| 8378 |
} |
| 8379 |
*cswritep++ = '\t'; |
| 8380 |
const AlleleCode gt2_low = entry.dac2; // truncate |
| 8381 |
const AlleleCode gt2_high = entry.dac2 >> (8 * sizeof(AlleleCode)); |
| 8382 |
if (cur_autosomal_diploid) { |
| 8383 |
cswritep = PrintMultiallelicHcAsDs(gt2_low, gt2_high, merged_allele_ct, cswritep); |
| 8384 |
} else { |
| 8385 |
cswritep = PrintMultiallelicHcAsHaploidDs(gt2_low, gt2_high, merged_allele_ct, cswritep); |
| 8386 |
} |
| 8387 |
} |
| 8388 |
} else { |
| 8389 |
// dosage_needed |
| 8390 |
const Dosage* cur_ds_entry = &(ds_entries[diff_idx * (2 * k1LU) * merged_allele_ct_m1]); |
| 8391 |
*cswritep++ = '\t'; |
| 8392 |
for (uint32_t uii = 0; uii != 2; ++uii) { |
| 8393 |
if (cur_ds_entry[0] == kDosageMissing) { |
| 8394 |
cswritep = strcpya_k(cswritep, ".\t"); |
| 8395 |
} else { |
| 8396 |
if (cur_autosomal_diploid) { |
| 8397 |
for (uint32_t alt_idx = 0; alt_idx != merged_allele_ct_m1; ++alt_idx) { |
| 8398 |
cswritep = PrintSmallDosage(cur_ds_entry[alt_idx], cswritep); |
| 8399 |
*cswritep++ = ','; |
| 8400 |
} |
| 8401 |
} else { |
| 8402 |
for (uint32_t alt_idx = 0; alt_idx != merged_allele_ct_m1; ++alt_idx) { |
| 8403 |
cswritep = PrintHaploidDosage(cur_ds_entry[alt_idx], cswritep); |
| 8404 |
*cswritep++ = ','; |
| 8405 |
} |
| 8406 |
} |
| 8407 |
cswritep[-1] = '\t'; |
| 8408 |
} |
| 8409 |
cur_ds_entry = &(cur_ds_entry[merged_allele_ct_m1]); |
| 8410 |
} |
| 8411 |
--cswritep; |
| 8412 |
} |
| 8413 |
} |
| 8414 |
AppendBinaryEoln(&cswritep); |
| 8415 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 8416 |
goto PgenDiff_ret_WRITE_FAIL; |
| 8417 |
} |
| 8418 |
} |
| 8419 |
} |
| 8420 |
// could verify we're at .pvar EOF |
| 8421 |
|
| 8422 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 8423 |
goto PgenDiff_ret_WRITE_FAIL; |
| 8424 |
} |
| 8425 |
if (pct > 10) { |
| 8426 |
putc_unlocked('\b', stdout); |
| 8427 |
} |
| 8428 |
fputs("\b\b", stdout); |
| 8429 |
logputs("done.\n"); |
| 8430 |
const uint32_t matched_variant_ct = PopcountWords(already_seen, raw_variant_ctl); |
| 8431 |
logprintfww("--pgen-diff: %u sample%s and %u variant%s compared, %" PRIu64 " difference%s reported to %s .\n", sample_ct, (sample_ct == 1)? "" : "s", matched_variant_ct, (matched_variant_ct == 1)? "" : "s", grand_diff_ct, (grand_diff_ct == 1)? "" : "s", outname); |
| 8432 |
|
| 8433 |
} |
| 8434 |
while (0) { |
| 8435 |
PgenDiff_ret_NOMEM: |
| 8436 |
reterr = kPglRetNomem; |
| 8437 |
break; |
| 8438 |
PgenDiff_ret_PVAR_REWIND_FAIL_N: |
| 8439 |
logputs("\n"); |
| 8440 |
PgenDiff_ret_PVAR_REWIND_FAIL: |
| 8441 |
logerrprintfww(kErrprintfRewind, "--pgen-diff .pvar file"); |
| 8442 |
reterr = kPglRetRewindFail; |
| 8443 |
break; |
| 8444 |
PgenDiff_ret_PVAR_MISSING_TOKENS_N: |
| 8445 |
logputs("\n"); |
| 8446 |
PgenDiff_ret_PVAR_MISSING_TOKENS: |
| 8447 |
logerrprintfww("Error: Line %" PRIuPTR " of --pgen-diff .pvar file has fewer tokens than expected.\n", pvar_line_idx); |
| 8448 |
reterr = kPglRetMalformedInput; |
| 8449 |
break; |
| 8450 |
PgenDiff_ret_PSAM_TSTREAM_XID_FAIL: |
| 8451 |
if (!TextStreamErrcode(&psam_txs)) { |
| 8452 |
break; |
| 8453 |
} |
| 8454 |
PgenDiff_ret_PSAM_TSTREAM_FAIL: |
| 8455 |
TextStreamErrPrint("--pgen-diff .psam file", &psam_txs); |
| 8456 |
break; |
| 8457 |
PgenDiff_ret_PSAM_MISSING_TOKENS: |
| 8458 |
logerrprintfww("Error: Line %" PRIuPTR " of --pgen-diff .psam file has fewer tokens than expected.\n", psam_line_idx); |
| 8459 |
reterr = kPglRetMalformedInput; |
| 8460 |
break; |
| 8461 |
PgenDiff_ret_MALFORMED_INPUT_WW_N: |
| 8462 |
logputs("\n"); |
| 8463 |
PgenDiff_ret_MALFORMED_INPUT_WW: |
| 8464 |
WordWrapB(0); |
| 8465 |
logerrputsb(); |
| 8466 |
PgenDiff_ret_MALFORMED_INPUT: |
| 8467 |
reterr = kPglRetMalformedInput; |
| 8468 |
break; |
| 8469 |
PgenDiff_ret_INCONSISTENT_INPUT_WW_N: |
| 8470 |
logputs("\n"); |
| 8471 |
PgenDiff_ret_INCONSISTENT_INPUT_WW: |
| 8472 |
WordWrapB(0); |
| 8473 |
logerrputsb(); |
| 8474 |
PgenDiff_ret_INCONSISTENT_INPUT: |
| 8475 |
reterr = kPglRetInconsistentInput; |
| 8476 |
break; |
| 8477 |
PgenDiff_ret_WRITE_FAIL: |
| 8478 |
reterr = kPglRetWriteFail; |
| 8479 |
break; |
| 8480 |
} |
| 8481 |
PgenDiff_ret_1: |
| 8482 |
CswriteCloseCond(&css, cswritep); |
| 8483 |
CleanupPgr2("--pgen-diff .pgen file", &simple_pgr2, &reterr); |
| 8484 |
CleanupPgfi2("--pgen-diff .pgen file", &pgfi2, &reterr); |
| 8485 |
CleanupTextStream2("--pgen-diff .pvar file", &pvar_txs, &reterr); |
| 8486 |
CleanupTextStream2("--pgen-diff .psam file", &psam_txs, &reterr); |
| 8487 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 8488 |
return reterr; |
| 8489 |
} |
| 8490 |
|
| 8491 |
#ifdef __cplusplus |
| 8492 |
} // namespace plink2 |
| 8493 |
#endif |