| 1 |
// This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell, |
| 2 |
// Christopher Chang. |
| 3 |
// |
| 4 |
// This library is free software: you can redistribute it and/or modify it |
| 5 |
// under the terms of the GNU Lesser General Public License as published by the |
| 6 |
// Free Software Foundation; either version 3 of the License, or (at your |
| 7 |
// option) any later version. |
| 8 |
// |
| 9 |
// This library 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 Lesser General Public License |
| 12 |
// for more details. |
| 13 |
// |
| 14 |
// You should have received a copy of the GNU Lesser General Public License |
| 15 |
// along with this library. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
|
| 18 |
#include "pgenlib_write.h" |
| 19 |
|
| 20 |
#include <unistd.h> // unlink() |
| 21 |
|
| 22 |
#ifdef __cplusplus |
| 23 |
namespace plink2 { |
| 24 |
#endif |
| 25 |
|
| 26 |
static inline PgenWriterCommon* GetPwcp(STPgenWriter* spgwp) { |
| 27 |
return &GET_PRIVATE(*spgwp, pwc); |
| 28 |
} |
| 29 |
|
| 30 |
static inline FILE** GetPgenOutfilep(STPgenWriter* spgwp) { |
| 31 |
return &GET_PRIVATE(*spgwp, pgen_outfile); |
| 32 |
} |
| 33 |
|
| 34 |
static inline FILE** GetPgiOrFinalPgenOutfilep(STPgenWriter* spgwp) { |
| 35 |
return &GET_PRIVATE(*spgwp, pgi_or_final_pgen_outfile); |
| 36 |
} |
| 37 |
|
| 38 |
static inline char** GetFnameBufp(STPgenWriter* spgwp) { |
| 39 |
return &GET_PRIVATE(*spgwp, fname_buf); |
| 40 |
} |
| 41 |
|
| 42 |
void GenovecInvertCopyUnsafe(const uintptr_t* __restrict genovec, uint32_t sample_ct, uintptr_t* __restrict genovec_inverted_copy) { |
| 43 |
// flips 0 to 2 and vice versa. |
| 44 |
// "unsafe" because trailing bits are not zeroed out. |
| 45 |
const uint32_t vec_ct = NypCtToVecCt(sample_ct); |
| 46 |
assert(IsVecAligned(genovec)); |
| 47 |
const VecW not_m1 = VCONST_W(kMaskAAAA); |
| 48 |
const VecW* vin_ptr = R_CAST(const VecW*, genovec); |
| 49 |
VecW* vout_ptr = R_CAST(VecW*, genovec_inverted_copy); |
| 50 |
for (uint32_t vidx = 0; vidx != vec_ct; ++vidx) { |
| 51 |
const VecW cur_vec = vin_ptr[vidx]; |
| 52 |
// flip high bit iff low bit is unset |
| 53 |
vout_ptr[vidx] = cur_vec ^ vecw_and_notfirst(vecw_slli(cur_vec, 1), not_m1); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
void PreinitSpgw(STPgenWriter* spgwp) { |
| 58 |
*GetPgenOutfilep(spgwp) = nullptr; |
| 59 |
*GetPgiOrFinalPgenOutfilep(spgwp) = nullptr; |
| 60 |
*GetFnameBufp(spgwp) = nullptr; |
| 61 |
} |
| 62 |
|
| 63 |
void PreinitMpgw(MTPgenWriter* mpgwp) { |
| 64 |
mpgwp->pgen_outfile = nullptr; |
| 65 |
mpgwp->pgi_or_final_pgen_outfile = nullptr; |
| 66 |
mpgwp->fname_buf = nullptr; |
| 67 |
} |
| 68 |
|
| 69 |
// OpenFail and WriteFail errors can now refer to either the .pgen, .pgen.tmp, |
| 70 |
// or .pgen.pgi file. |
| 71 |
PglErr PwcInitPhase1(const char* __restrict fname, uintptr_t* explicit_nonref_flags, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, uint32_t variant_ct_limit, uint32_t sample_ct, PgenWriteMode write_mode, PgenGlobalFlags phase_dosage_gflags, uint32_t nonref_flags_storage, uintptr_t vrec_len_byte_ct, PgenWriterCommon* pwcp, FILE** pgen_outfile_ptr, FILE** pgi_or_final_pgen_outfile_ptr, char** fname_buf_ptr) { |
| 72 |
pwcp->explicit_nonref_flags = nullptr; |
| 73 |
if (nonref_flags_storage == 3) { |
| 74 |
if (unlikely(!explicit_nonref_flags)) { |
| 75 |
return kPglRetImproperFunctionCall; |
| 76 |
} |
| 77 |
pwcp->explicit_nonref_flags = explicit_nonref_flags; |
| 78 |
} |
| 79 |
pwcp->header_exts = header_exts; |
| 80 |
pwcp->footer_exts = footer_exts; |
| 81 |
pwcp->variant_ct_limit = variant_ct_limit; |
| 82 |
pwcp->sample_ct = sample_ct; |
| 83 |
pwcp->phase_dosage_gflags = phase_dosage_gflags; |
| 84 |
pwcp->nonref_flags_storage = nonref_flags_storage; |
| 85 |
pwcp->vrec_len_byte_ct = vrec_len_byte_ct; |
| 86 |
#ifndef NDEBUG |
| 87 |
pwcp->vblock_fpos = nullptr; |
| 88 |
pwcp->vrec_len_buf = nullptr; |
| 89 |
pwcp->vrtype_buf = nullptr; |
| 90 |
pwcp->fwrite_buf = nullptr; |
| 91 |
pwcp->fwrite_bufp = nullptr; |
| 92 |
pwcp->genovec_hets_buf = nullptr; |
| 93 |
pwcp->genovec_invert_buf = nullptr; |
| 94 |
pwcp->ldbase_genovec = nullptr; |
| 95 |
pwcp->ldbase_raregeno = nullptr; |
| 96 |
pwcp->ldbase_difflist_sample_ids = nullptr; |
| 97 |
#endif |
| 98 |
pwcp->vidx = 0; |
| 99 |
|
| 100 |
*pgen_outfile_ptr = nullptr; |
| 101 |
*pgi_or_final_pgen_outfile_ptr = nullptr; |
| 102 |
*fname_buf_ptr = nullptr; |
| 103 |
const int32_t ext_present = (header_exts != nullptr) || (footer_exts != nullptr); |
| 104 |
const int32_t third_byte = ((write_mode == kPgenWriteSeparateIndex)? 0x20 : 0x10) + ext_present; |
| 105 |
if (write_mode != kPgenWriteBackwardSeek) { |
| 106 |
const uint32_t fname_slen = strlen(fname); |
| 107 |
if (fname_slen > kPglFnamesize - 5) { |
| 108 |
return kPglRetMalformedInput; |
| 109 |
} |
| 110 |
pwcp->vblock_fpos_offset = 3; |
| 111 |
if (write_mode == kPgenWriteAndCopy) { |
| 112 |
if (unlikely(pgl_malloc(fname_slen + 5, fname_buf_ptr))) { |
| 113 |
return kPglRetNomem; |
| 114 |
} |
| 115 |
char* fname_iter = memcpya(*fname_buf_ptr, fname, fname_slen); |
| 116 |
// In the kPgenWriteAndCopy case, pgen_outfile is the *temporary* .pgen |
| 117 |
// output. |
| 118 |
strcpy_k(fname_iter, ".tmp"); |
| 119 |
*pgen_outfile_ptr = fopen(*fname_buf_ptr, FOPEN_WB); |
| 120 |
if (unlikely(!(*pgen_outfile_ptr))) { |
| 121 |
return kPglRetOpenFail; |
| 122 |
} |
| 123 |
fwrite_unlocked("l\x1b", 2, 1, *pgen_outfile_ptr); |
| 124 |
if (unlikely(putc_checked(third_byte + 0x10, *pgen_outfile_ptr))) { |
| 125 |
return kPglRetWriteFail; |
| 126 |
} |
| 127 |
} else { |
| 128 |
// kPgenWriteSeparateIndex |
| 129 |
char fname_buf[kPglFnamesize]; |
| 130 |
char* fname_iter = memcpya(fname_buf, fname, fname_slen); |
| 131 |
strcpy_k(fname_iter, ".pgi"); |
| 132 |
*pgi_or_final_pgen_outfile_ptr = fopen(fname_buf, FOPEN_WB); |
| 133 |
if (unlikely(!(*pgi_or_final_pgen_outfile_ptr))) { |
| 134 |
return kPglRetOpenFail; |
| 135 |
} |
| 136 |
fwrite_unlocked("l\x1b", 2, 1, *pgi_or_final_pgen_outfile_ptr); |
| 137 |
if (unlikely(putc_checked(third_byte + 0x10, *pgi_or_final_pgen_outfile_ptr))) { |
| 138 |
return kPglRetWriteFail; |
| 139 |
} |
| 140 |
} |
| 141 |
} |
| 142 |
FILE* header_ff = fopen(fname, FOPEN_WB); |
| 143 |
if (unlikely(!header_ff)) { |
| 144 |
return kPglRetOpenFail; |
| 145 |
} |
| 146 |
if (write_mode != kPgenWriteAndCopy) { |
| 147 |
*pgen_outfile_ptr = header_ff; |
| 148 |
} else { |
| 149 |
*pgi_or_final_pgen_outfile_ptr = header_ff; |
| 150 |
} |
| 151 |
fwrite_unlocked("l\x1b", 2, 1, header_ff); |
| 152 |
if (unlikely(putc_checked(third_byte, header_ff))) { |
| 153 |
return kPglRetWriteFail; |
| 154 |
} |
| 155 |
if (write_mode != kPgenWriteBackwardSeek) { |
| 156 |
return kPglRetSuccess; |
| 157 |
} |
| 158 |
|
| 159 |
uint64_t header_bytes_left = PglHeaderBaseEndOffset(variant_ct_limit, vrec_len_byte_ct, phase_dosage_gflags != kfPgenGlobal0, nonref_flags_storage == 3) - 3; |
| 160 |
if (ext_present) { |
| 161 |
// Additional header contents: |
| 162 |
// 1. Flag varint describing which header extensions are present. |
| 163 |
// 2. Flag varint describing which footer extensions are present. |
| 164 |
// 3. If at least one footer extension present, uint64 byte offset of |
| 165 |
// footer start. |
| 166 |
// 4. For each present header extension, a varint indicating its byte |
| 167 |
// length. |
| 168 |
// 5. Bodies of header extensions, in order. |
| 169 |
|
| 170 |
// Fixed minimum size of (1) + (2). |
| 171 |
header_bytes_left += 2; |
| 172 |
if (header_exts) { |
| 173 |
PgenExtensionLl* header_exts_iter = header_exts; |
| 174 |
int32_t prev_type_idx = -1; |
| 175 |
do { |
| 176 |
const int32_t cur_type_idx = header_exts_iter->type_idx; |
| 177 |
if (cur_type_idx <= prev_type_idx) { |
| 178 |
return kPglRetImproperFunctionCall; |
| 179 |
} |
| 180 |
const uint64_t cur_size = header_exts_iter->size; |
| 181 |
if (unlikely(cur_size >= (1LLU << (kBitsPerWord - 1)))) { |
| 182 |
return kPglRetImproperFunctionCall; |
| 183 |
} |
| 184 |
header_bytes_left += cur_size + VintBytect(cur_size); |
| 185 |
|
| 186 |
prev_type_idx = cur_type_idx; |
| 187 |
header_exts_iter = header_exts_iter->next; |
| 188 |
} while (header_exts_iter); |
| 189 |
header_bytes_left += S_CAST(uint32_t, prev_type_idx) / 7; |
| 190 |
} |
| 191 |
if (footer_exts) { |
| 192 |
PgenExtensionLl* footer_exts_iter = footer_exts; |
| 193 |
int32_t prev_type_idx = -1; |
| 194 |
do { |
| 195 |
const int32_t cur_type_idx = footer_exts_iter->type_idx; |
| 196 |
if (cur_type_idx <= prev_type_idx) { |
| 197 |
return kPglRetImproperFunctionCall; |
| 198 |
} |
| 199 |
prev_type_idx = cur_type_idx; |
| 200 |
footer_exts_iter = footer_exts_iter->next; |
| 201 |
} while (footer_exts_iter); |
| 202 |
// 8 more fixed bytes for (3). |
| 203 |
header_bytes_left += sizeof(int64_t) + S_CAST(uint32_t, prev_type_idx) / 7; |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
// this should be the position of the first variant |
| 208 |
pwcp->vblock_fpos_offset = 3 + header_bytes_left; |
| 209 |
|
| 210 |
uintptr_t zeroed_cachelines_needed = DivUp(header_bytes_left, kCacheline); |
| 211 |
if (zeroed_cachelines_needed > (kPglFwriteBlockSize / kCacheline)) { |
| 212 |
zeroed_cachelines_needed = kPglFwriteBlockSize / kCacheline; |
| 213 |
} |
| 214 |
// could wait until fwrite_buf is allocated, and make sure it's aligned? |
| 215 |
unsigned char zerobuf[kPglFwriteBlockSize]; |
| 216 |
memset(zerobuf, 0, zeroed_cachelines_needed * kCacheline); |
| 217 |
while (header_bytes_left > kPglFwriteBlockSize) { |
| 218 |
fwrite_unlocked(zerobuf, kPglFwriteBlockSize, 1, header_ff); |
| 219 |
header_bytes_left -= kPglFwriteBlockSize; |
| 220 |
} |
| 221 |
if (unlikely(fwrite_checked(zerobuf, header_bytes_left, header_ff))) { |
| 222 |
return kPglRetWriteFail; |
| 223 |
} |
| 224 |
return kPglRetSuccess; |
| 225 |
} |
| 226 |
|
| 227 |
uintptr_t CountSpgwAllocCachelinesRequired(uint32_t variant_ct_limit, uint32_t sample_ct, PgenGlobalFlags phase_dosage_gflags, uint32_t max_vrec_len) { |
| 228 |
// vblock_fpos |
| 229 |
const uint32_t vblock_ct_limit = DivUp(variant_ct_limit, kPglVblockSize); |
| 230 |
uintptr_t cachelines_required = Int64CtToCachelineCt(vblock_ct_limit); |
| 231 |
|
| 232 |
// vrec_len_buf |
| 233 |
const uintptr_t vrec_len_byte_ct = BytesToRepresentNzU32(max_vrec_len); |
| 234 |
cachelines_required += DivUp(variant_ct_limit * vrec_len_byte_ct, kCacheline); |
| 235 |
|
| 236 |
// vrtype_buf |
| 237 |
if (phase_dosage_gflags) { |
| 238 |
cachelines_required += DivUp(variant_ct_limit, kCacheline); |
| 239 |
} else { |
| 240 |
cachelines_required += DivUp(variant_ct_limit, kCacheline * 2); |
| 241 |
} |
| 242 |
|
| 243 |
// genovec_hets_buf, genovec_invert_buf, ldbase_genovec |
| 244 |
cachelines_required += 3 * NypCtToCachelineCt(sample_ct); |
| 245 |
|
| 246 |
const uint32_t max_difflist_len = 2 * (sample_ct / kPglMaxDifflistLenDivisor); |
| 247 |
// ldbase_raregeno |
| 248 |
cachelines_required += NypCtToCachelineCt(max_difflist_len); |
| 249 |
|
| 250 |
// ldbase_difflist_sample_ids |
| 251 |
cachelines_required += 1 + (max_difflist_len / kInt32PerCacheline); |
| 252 |
|
| 253 |
// fwrite_buf |
| 254 |
// + (5 + sizeof(AlleleCode)) * kPglDifflistGroupSize to avoid buffer |
| 255 |
// overflow in middle of difflist writing |
| 256 |
// TODO: document which code approaches this limit. sizeof(AlleleCode) |
| 257 |
// implies it's one of the multiallelic subcases? |
| 258 |
cachelines_required += DivUp(max_vrec_len + kPglFwriteBlockSize + (5 + sizeof(AlleleCode)) * kPglDifflistGroupSize, kCacheline); |
| 259 |
// possible todo: dosage (doesn't currently need an allocation, but that's |
| 260 |
// unlikely to remain true--e.g. get_ref_nonref_genotype_counts_and_dosages |
| 261 |
// tends to use workspace_vec when a function it calls doesn't use it...) |
| 262 |
|
| 263 |
// probable todo: multiallelic (phased) dosage |
| 264 |
return cachelines_required; |
| 265 |
} |
| 266 |
|
| 267 |
static_assert(kPglMaxAlleleCt == 255, "Need to update SpgwInitPhase1Ex()."); |
| 268 |
PglErr SpgwInitPhase1Ex(const char* __restrict fname, const uintptr_t* __restrict allele_idx_offsets, uintptr_t* __restrict explicit_nonref_flags, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, uint32_t variant_ct_limit, uint32_t sample_ct, uint32_t allele_ct_upper_bound, PgenWriteMode write_mode, PgenGlobalFlags phase_dosage_gflags, uint32_t nonref_flags_storage, STPgenWriter* spgwp, uintptr_t* alloc_cacheline_ct_ptr, uint32_t* max_vrec_len_ptr) { |
| 269 |
assert(variant_ct_limit); |
| 270 |
assert(sample_ct); |
| 271 |
|
| 272 |
// separate from MpgwInitPhase1's version of this computation since the |
| 273 |
// latter wants a better bound on the compressed size of an entire vblock |
| 274 |
// than max_vrec_len * kPglVblockSize... |
| 275 |
uint64_t max_vrec_len = NypCtToByteCt(sample_ct); |
| 276 |
uintptr_t max_alt_ct_p1 = 2; |
| 277 |
if (allele_idx_offsets) { |
| 278 |
const uint32_t variant_ct = variant_ct_limit; |
| 279 |
if (allele_idx_offsets[variant_ct] != 2 * variant_ct) { |
| 280 |
assert(allele_idx_offsets[0] == 0); |
| 281 |
assert(allele_idx_offsets[variant_ct] > 2 * variant_ct); |
| 282 |
max_alt_ct_p1 = 3; |
| 283 |
uintptr_t prev_offset = 0; |
| 284 |
for (uint32_t vidx = 1; vidx <= variant_ct; ++vidx) { |
| 285 |
const uintptr_t cur_offset = allele_idx_offsets[vidx]; |
| 286 |
if (cur_offset - prev_offset > max_alt_ct_p1) { |
| 287 |
max_alt_ct_p1 = cur_offset - prev_offset; |
| 288 |
} |
| 289 |
prev_offset = cur_offset; |
| 290 |
} |
| 291 |
} |
| 292 |
} else if (allele_ct_upper_bound) { |
| 293 |
max_alt_ct_p1 = allele_ct_upper_bound; |
| 294 |
} |
| 295 |
if (max_alt_ct_p1 > 2) { |
| 296 |
// see comments in middle of MpgwInitPhase1() |
| 297 |
// bugfix (29 Mar 2023): forgot (sample_ct + 6) / 8 term |
| 298 |
max_vrec_len += 2 + sizeof(AlleleCode) + (sample_ct + 6) / 8 + GetAux1bAlleleEntryByteCt(max_alt_ct_p1, sample_ct - 1); |
| 299 |
// try to permit uncompressed records to be larger than this, only error |
| 300 |
// out when trying to write a larger compressed record. |
| 301 |
} |
| 302 |
if (phase_dosage_gflags & kfPgenGlobalHardcallPhasePresent) { |
| 303 |
// phasepresent, phaseinfo |
| 304 |
max_vrec_len += 2 * DivUp(sample_ct, CHAR_BIT); |
| 305 |
} |
| 306 |
if (phase_dosage_gflags & kfPgenGlobalDosagePresent) { |
| 307 |
const uint32_t dphase_gflag = (phase_dosage_gflags / kfPgenGlobalDosagePhasePresent) & 1; |
| 308 |
// aux3, aux7 |
| 309 |
max_vrec_len += (1 + dphase_gflag) * DivUp(sample_ct, 8); |
| 310 |
// aux4, aux8 |
| 311 |
max_vrec_len += (2 + 2 * dphase_gflag) * S_CAST(uint64_t, sample_ct); |
| 312 |
// todo: multiallelic dosage |
| 313 |
} |
| 314 |
#ifdef __LP64__ |
| 315 |
if (max_vrec_len >= kPglMaxBytesPerVariant) { |
| 316 |
max_vrec_len = kPglMaxBytesPerVariant; |
| 317 |
} |
| 318 |
#else |
| 319 |
if (unlikely(max_vrec_len > kMaxBytesPerIO + 1 - kPglFwriteBlockSize)) { |
| 320 |
return kPglRetNomem; |
| 321 |
} |
| 322 |
#endif |
| 323 |
*max_vrec_len_ptr = max_vrec_len; |
| 324 |
const uintptr_t vrec_len_byte_ct = BytesToRepresentNzU32(max_vrec_len); |
| 325 |
|
| 326 |
PgenWriterCommon* pwcp = GetPwcp(spgwp); |
| 327 |
FILE** pgen_outfilep = GetPgenOutfilep(spgwp); |
| 328 |
FILE** pgi_or_final_pgen_outfilep = GetPgiOrFinalPgenOutfilep(spgwp); |
| 329 |
char** fname_bufp = GetFnameBufp(spgwp); |
| 330 |
PglErr reterr = PwcInitPhase1(fname, explicit_nonref_flags, header_exts, footer_exts, variant_ct_limit, sample_ct, write_mode, phase_dosage_gflags, nonref_flags_storage, vrec_len_byte_ct, pwcp, pgen_outfilep, pgi_or_final_pgen_outfilep, fname_bufp); |
| 331 |
if (likely(!reterr)) { |
| 332 |
*alloc_cacheline_ct_ptr = CountSpgwAllocCachelinesRequired(variant_ct_limit, sample_ct, phase_dosage_gflags, max_vrec_len); |
| 333 |
} |
| 334 |
return reterr; |
| 335 |
} |
| 336 |
|
| 337 |
static_assert(kPglMaxAlleleCt == 255, "Need to update MpgwInitPhase1()."); |
| 338 |
void MpgwInitPhase1(const uintptr_t* __restrict allele_idx_offsets, uint32_t variant_ct, uint32_t sample_ct, PgenGlobalFlags phase_dosage_gflags, uintptr_t* alloc_base_cacheline_ct_ptr, uint64_t* alloc_per_thread_cacheline_ct_ptr, uint32_t* vrec_len_byte_ct_ptr, uint64_t* vblock_cacheline_ct_ptr) { |
| 339 |
// variant_ct must be exact due to how MpgwFlush() works. |
| 340 |
assert(variant_ct); |
| 341 |
assert(sample_ct); |
| 342 |
// vblock_fpos |
| 343 |
const uint32_t vblock_ct = DivUp(variant_ct, kPglVblockSize); |
| 344 |
uint32_t alloc_base_cacheline_ct = Int64CtToCachelineCt(vblock_ct); |
| 345 |
|
| 346 |
// vrtype_buf |
| 347 |
if (phase_dosage_gflags) { |
| 348 |
alloc_base_cacheline_ct += DivUp(variant_ct, kCacheline); |
| 349 |
} else { |
| 350 |
alloc_base_cacheline_ct += DivUp(variant_ct, kCacheline * 2); |
| 351 |
} |
| 352 |
|
| 353 |
// pwcs |
| 354 |
uint64_t alloc_per_thread_cacheline_ct = DivUp(sizeof(PgenWriterCommon), kCacheline); |
| 355 |
|
| 356 |
// genovec_hets_buf, genovec_invert_buf, ldbase_genovec |
| 357 |
// (could make genovec_hets_buf allocation conditional, but not worth the |
| 358 |
// additional load this puts on import functions) |
| 359 |
alloc_per_thread_cacheline_ct += 3 * NypCtToCachelineCt(sample_ct); |
| 360 |
|
| 361 |
const uint32_t max_difflist_len = 2 * (sample_ct / kPglMaxDifflistLenDivisor); |
| 362 |
// ldbase_raregeno |
| 363 |
alloc_per_thread_cacheline_ct += NypCtToCachelineCt(max_difflist_len); |
| 364 |
|
| 365 |
// ldbase_difflist_sample_ids |
| 366 |
alloc_per_thread_cacheline_ct += 1 + (max_difflist_len / kInt32PerCacheline); |
| 367 |
|
| 368 |
uint64_t max_vrec_len = NypCtToByteCt(sample_ct); |
| 369 |
if (phase_dosage_gflags & kfPgenGlobalHardcallPhasePresent) { |
| 370 |
max_vrec_len += 2 * DivUp(sample_ct, CHAR_BIT); |
| 371 |
} |
| 372 |
const uint32_t dosage_gflag = (phase_dosage_gflags / kfPgenGlobalDosagePresent) & 1; |
| 373 |
const uint32_t dosage_phase_gflag = (phase_dosage_gflags / kfPgenGlobalDosagePhasePresent) & 1; |
| 374 |
if (dosage_gflag) { |
| 375 |
max_vrec_len += ((1 + dosage_phase_gflag) * DivUp(sample_ct, CHAR_BIT)) + (2 + 2 * dosage_phase_gflag) * S_CAST(uint64_t, sample_ct); |
| 376 |
} |
| 377 |
const uint32_t max_vblock_size = MINV(variant_ct, kPglVblockSize); |
| 378 |
// max_vrec_len is a uint64_t |
| 379 |
uint64_t max_vblock_byte_ct = max_vrec_len * max_vblock_size; |
| 380 |
if (allele_idx_offsets && (allele_idx_offsets[variant_ct] != 2 * variant_ct)) { |
| 381 |
assert(allele_idx_offsets[0] == 0); |
| 382 |
assert(allele_idx_offsets[variant_ct] > 2 * variant_ct); |
| 383 |
// When multiallelic variants are present, larger write buffers are needed. |
| 384 |
// we compute the largest possible size here. |
| 385 |
// |
| 386 |
// One way to hit the maximum size is to have exactly 1 ref/altx genotype, |
| 387 |
// all other genotypes are altx/alty, and all genotypes include a rarealt. |
| 388 |
// Then, we need 2 + sizeof(AlleleCode) bytes for the format byte and |
| 389 |
// aux1a, (sample_ct + 6) / 8 bytes for the bitarray at the front of aux1b, |
| 390 |
// and |
| 391 |
// alt ct aux1_last_quarter bytes required |
| 392 |
// ------ -------------------------------- |
| 393 |
// 2 (sample_ct - 1 + 7) / 8 |
| 394 |
// 3-4 (sample_ct - 1 + 1) / 2 |
| 395 |
// 5-16 (sample_ct - 1) |
| 396 |
// 17-256 2 * (sample_ct - 1) |
| 397 |
// |
| 398 |
// (todo: also take multiallelic dosage into account) |
| 399 |
assert(!dosage_gflag); |
| 400 |
uintptr_t prev_offset = 0; |
| 401 |
uint32_t vidx = 0; |
| 402 |
const uint32_t extra_bytes_base = 2 + sizeof(AlleleCode) + (sample_ct + 6) / 8; |
| 403 |
const uint64_t extra_bytes_max = kPglMaxBytesPerVariant - max_vrec_len; |
| 404 |
uint64_t extra_byte_cts[4]; |
| 405 |
uint32_t extra_alt_ceil = kPglMaxAlleleCt; |
| 406 |
|
| 407 |
// alt_ct == 2 |
| 408 |
uint64_t cur_extra_byte_ct = extra_bytes_base + (sample_ct + 6) / 8; |
| 409 |
extra_byte_cts[0] = cur_extra_byte_ct; |
| 410 |
extra_byte_cts[1] = 0; // force initialization |
| 411 |
extra_byte_cts[2] = 0; |
| 412 |
extra_byte_cts[3] = 0; |
| 413 |
if (cur_extra_byte_ct >= extra_bytes_max) { |
| 414 |
extra_alt_ceil = 2; |
| 415 |
} else { |
| 416 |
// alt_ct in [3, 4] |
| 417 |
cur_extra_byte_ct = extra_bytes_base + (sample_ct / 2); |
| 418 |
extra_byte_cts[1] = cur_extra_byte_ct; |
| 419 |
if (cur_extra_byte_ct >= extra_bytes_max) { |
| 420 |
extra_alt_ceil = 3; |
| 421 |
} else { |
| 422 |
// alt_ct in [5, 16] |
| 423 |
cur_extra_byte_ct = extra_bytes_base + sample_ct - 1; |
| 424 |
extra_byte_cts[2] = cur_extra_byte_ct; |
| 425 |
if (cur_extra_byte_ct >= extra_bytes_max) { |
| 426 |
extra_alt_ceil = 5; |
| 427 |
} else { |
| 428 |
// alt_ct in [17, 256] |
| 429 |
cur_extra_byte_ct = extra_bytes_base + 2 * (sample_ct - 1); |
| 430 |
extra_byte_cts[3] = cur_extra_byte_ct; |
| 431 |
if (cur_extra_byte_ct >= extra_bytes_max) { |
| 432 |
extra_alt_ceil = 16; |
| 433 |
} |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
uint32_t extra_alt_ceil_ct = 0; |
| 438 |
const uint64_t uncompressed_biallelic_vrec_len = max_vrec_len; |
| 439 |
uint32_t altx_seen_mask = 0; |
| 440 |
uint32_t max_alt_ct_p1 = 3; |
| 441 |
for (uint32_t vblock_end = vidx + kPglVblockSize; ; vblock_end += kPglVblockSize) { |
| 442 |
if (vblock_end > variant_ct) { |
| 443 |
if (vidx == variant_ct) { |
| 444 |
break; |
| 445 |
} |
| 446 |
vblock_end = variant_ct; |
| 447 |
} |
| 448 |
uint64_t cur_vblock_byte_ct = uncompressed_biallelic_vrec_len * (vblock_end - vidx); |
| 449 |
uint32_t altx_seen[4]; |
| 450 |
ZeroU32Arr(4, altx_seen); |
| 451 |
for (; vidx < vblock_end; ) { |
| 452 |
const uintptr_t cur_offset = allele_idx_offsets[++vidx]; |
| 453 |
const uint32_t alt_ct_p1 = cur_offset - prev_offset; |
| 454 |
if (alt_ct_p1 > 2) { |
| 455 |
if (alt_ct_p1 >= extra_alt_ceil) { |
| 456 |
++extra_alt_ceil_ct; |
| 457 |
} else { |
| 458 |
// don't need to track this when we hit the ceiling |
| 459 |
if (alt_ct_p1 > max_alt_ct_p1) { |
| 460 |
max_alt_ct_p1 = alt_ct_p1; |
| 461 |
} |
| 462 |
|
| 463 |
if (alt_ct_p1 < 6) { |
| 464 |
altx_seen[(alt_ct_p1 != 3)] += 1; |
| 465 |
} else { |
| 466 |
altx_seen[2 + (alt_ct_p1 >= 17)] += 1; |
| 467 |
} |
| 468 |
} |
| 469 |
} |
| 470 |
prev_offset = cur_offset; |
| 471 |
} |
| 472 |
cur_vblock_byte_ct += extra_alt_ceil_ct * extra_bytes_max; |
| 473 |
for (uint32_t uii = 0; uii != 4; ++uii) { |
| 474 |
if (altx_seen[uii]) { |
| 475 |
const uint32_t cur_seen_ct = altx_seen[uii]; |
| 476 |
altx_seen_mask |= 1 << uii; |
| 477 |
cur_vblock_byte_ct += cur_seen_ct * extra_byte_cts[uii]; |
| 478 |
} |
| 479 |
} |
| 480 |
if (cur_vblock_byte_ct > max_vblock_byte_ct) { |
| 481 |
max_vblock_byte_ct = cur_vblock_byte_ct; |
| 482 |
} |
| 483 |
} |
| 484 |
if (extra_alt_ceil_ct) { |
| 485 |
max_vrec_len = kPglMaxBytesPerVariant; |
| 486 |
} else { |
| 487 |
max_vrec_len = uncompressed_biallelic_vrec_len + extra_byte_cts[bsru32(altx_seen_mask)]; |
| 488 |
} |
| 489 |
} |
| 490 |
if (max_vrec_len >= kPglMaxBytesPerVariant) { |
| 491 |
max_vrec_len = kPglMaxBytesPerVariant; |
| 492 |
max_vblock_byte_ct = kPglMaxBytesPerVariant * S_CAST(uint64_t, max_vblock_size); |
| 493 |
} |
| 494 |
|
| 495 |
// vrec_len_buf |
| 496 |
// previously used overlapping uint32_t writes-to-memory, but that was |
| 497 |
// incompatible with multithreaded compression |
| 498 |
*vrec_len_byte_ct_ptr = BytesToRepresentNzU32(max_vrec_len); |
| 499 |
*alloc_base_cacheline_ct_ptr = alloc_base_cacheline_ct + DivUp(S_CAST(uintptr_t, variant_ct) * (*vrec_len_byte_ct_ptr), kCacheline); |
| 500 |
|
| 501 |
// main write buffer |
| 502 |
*vblock_cacheline_ct_ptr = DivUpU64(max_vblock_byte_ct, kCacheline); |
| 503 |
*alloc_per_thread_cacheline_ct_ptr = alloc_per_thread_cacheline_ct + (*vblock_cacheline_ct_ptr); |
| 504 |
} |
| 505 |
|
| 506 |
|
| 507 |
void PwcInitPhase2(uintptr_t fwrite_cacheline_ct, uint32_t thread_ct, PgenWriterCommon** pwcs, unsigned char* pwc_alloc) { |
| 508 |
const uint32_t variant_ct_limit = pwcs[0]->variant_ct_limit; |
| 509 |
|
| 510 |
unsigned char* alloc_iter = pwc_alloc; |
| 511 |
const uint32_t vblock_ct = DivUp(variant_ct_limit, kPglVblockSize); |
| 512 |
const PgenGlobalFlags phase_dosage_gflags = pwcs[0]->phase_dosage_gflags; |
| 513 |
uint32_t vrtype_buf_byte_ct; |
| 514 |
if (phase_dosage_gflags) { |
| 515 |
vrtype_buf_byte_ct = RoundUpPow2(variant_ct_limit, kCacheline); |
| 516 |
} else { |
| 517 |
vrtype_buf_byte_ct = DivUp(variant_ct_limit, kCacheline * 2) * kCacheline; |
| 518 |
} |
| 519 |
pwcs[0]->vblock_fpos = S_CAST(uint64_t*, arena_alloc_raw_rd(vblock_ct * sizeof(int64_t), &alloc_iter)); |
| 520 |
|
| 521 |
pwcs[0]->vrec_len_buf = S_CAST(unsigned char*, arena_alloc_raw_rd(variant_ct_limit * pwcs[0]->vrec_len_byte_ct, &alloc_iter)); |
| 522 |
|
| 523 |
pwcs[0]->vrtype_buf = S_CAST(uintptr_t*, arena_alloc_raw(vrtype_buf_byte_ct, &alloc_iter)); |
| 524 |
// the PwcAppend... functions assume these bytes are zeroed out |
| 525 |
memset(pwcs[0]->vrtype_buf, 0, vrtype_buf_byte_ct); |
| 526 |
|
| 527 |
const uint32_t sample_ct = pwcs[0]->sample_ct; |
| 528 |
const uint32_t genovec_byte_alloc = NypCtToCachelineCt(sample_ct) * kCacheline; |
| 529 |
const uint32_t max_difflist_len = 2 * (sample_ct / kPglMaxDifflistLenDivisor); |
| 530 |
for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) { |
| 531 |
if (tidx) { |
| 532 |
pwcs[tidx]->vblock_fpos = pwcs[0]->vblock_fpos; |
| 533 |
pwcs[tidx]->vrec_len_buf = pwcs[0]->vrec_len_buf; |
| 534 |
pwcs[tidx]->vrtype_buf = pwcs[0]->vrtype_buf; |
| 535 |
} |
| 536 |
pwcs[tidx]->genovec_hets_buf = S_CAST(uintptr_t*, arena_alloc_raw(genovec_byte_alloc, &alloc_iter)); |
| 537 |
pwcs[tidx]->genovec_invert_buf = S_CAST(uintptr_t*, arena_alloc_raw(genovec_byte_alloc, &alloc_iter)); |
| 538 |
pwcs[tidx]->ldbase_genovec = S_CAST(uintptr_t*, arena_alloc_raw(genovec_byte_alloc, &alloc_iter)); |
| 539 |
|
| 540 |
pwcs[tidx]->ldbase_raregeno = S_CAST(uintptr_t*, arena_alloc_raw(NypCtToCachelineCt(max_difflist_len) * kCacheline, &alloc_iter)); |
| 541 |
pwcs[tidx]->ldbase_difflist_sample_ids = S_CAST(uint32_t*, arena_alloc_raw_rd((max_difflist_len + 1) * sizeof(int32_t), &alloc_iter)); |
| 542 |
|
| 543 |
pwcs[tidx]->fwrite_buf = alloc_iter; |
| 544 |
pwcs[tidx]->fwrite_bufp = alloc_iter; |
| 545 |
alloc_iter = &(alloc_iter[fwrite_cacheline_ct * kCacheline]); |
| 546 |
} |
| 547 |
} |
| 548 |
|
| 549 |
void SpgwInitPhase2(uint32_t max_vrec_len, STPgenWriter* spgwp, unsigned char* spgw_alloc) { |
| 550 |
const uintptr_t fwrite_cacheline_ct = DivUp(max_vrec_len + kPglFwriteBlockSize + (5 + sizeof(AlleleCode)) * kPglDifflistGroupSize, kCacheline); |
| 551 |
PgenWriterCommon* pwcp = GetPwcp(spgwp); |
| 552 |
PwcInitPhase2(fwrite_cacheline_ct, 1, &pwcp, spgw_alloc); |
| 553 |
} |
| 554 |
|
| 555 |
PglErr MpgwInitPhase2Ex(const char* __restrict fname, uintptr_t* __restrict explicit_nonref_flags, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, uint32_t variant_ct, uint32_t sample_ct, PgenWriteMode write_mode, PgenGlobalFlags phase_dosage_gflags, uint32_t nonref_flags_storage, uint32_t vrec_len_byte_ct, uintptr_t vblock_cacheline_ct, uint32_t thread_ct, unsigned char* mpgw_alloc, MTPgenWriter* mpgwp) { |
| 556 |
assert(thread_ct); |
| 557 |
const uintptr_t pwc_byte_ct = RoundUpPow2(sizeof(PgenWriterCommon), kCacheline); |
| 558 |
for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) { |
| 559 |
mpgwp->pwcs[tidx] = R_CAST(PgenWriterCommon*, &(mpgw_alloc[tidx * pwc_byte_ct])); |
| 560 |
} |
| 561 |
PglErr reterr = PwcInitPhase1(fname, explicit_nonref_flags, header_exts, footer_exts, variant_ct, sample_ct, write_mode, phase_dosage_gflags, nonref_flags_storage, vrec_len_byte_ct, mpgwp->pwcs[0], &(mpgwp->pgen_outfile), &(mpgwp->pgi_or_final_pgen_outfile), &(mpgwp->fname_buf)); |
| 562 |
if (unlikely(reterr)) { |
| 563 |
return reterr; |
| 564 |
} |
| 565 |
mpgwp->thread_ct = thread_ct; |
| 566 |
for (uint32_t tidx = 1; tidx != thread_ct; ++tidx) { |
| 567 |
*(mpgwp->pwcs[tidx]) = *(mpgwp->pwcs[0]); |
| 568 |
mpgwp->pwcs[tidx]->vidx = tidx * kPglVblockSize; |
| 569 |
} |
| 570 |
PwcInitPhase2(vblock_cacheline_ct, thread_ct, mpgwp->pwcs, &(mpgw_alloc[thread_ct * pwc_byte_ct])); |
| 571 |
return kPglRetSuccess; |
| 572 |
} |
| 573 |
|
| 574 |
|
| 575 |
void CountLdAndInvertedLdDiffs(const uintptr_t* __restrict ldbase_genovec, const uintptr_t* __restrict genovec, uint32_t sample_ct, uint32_t* ld_diff_ctp, uint32_t* ld_inv_diff_ctp) { |
| 576 |
// Requires trailing bits to be zeroed out. |
| 577 |
const uint32_t word_ct = NypCtToWordCt(sample_ct); |
| 578 |
const uintptr_t* genovec_end = &(genovec[word_ct]); |
| 579 |
uint32_t ld_diff_ct = 0; |
| 580 |
uint32_t ld_inv_diff_ct = 0; |
| 581 |
// construct the words we want to popcount_nypvec_01 on the fly |
| 582 |
const VecW m1 = VCONST_W(kMask5555); |
| 583 |
const VecW m2 = VCONST_W(kMask3333); |
| 584 |
const VecW m4 = VCONST_W(kMask0F0F); |
| 585 |
const VecW* ldbase_vvec_iter = R_CAST(const VecW*, ldbase_genovec); |
| 586 |
const VecW* geno_vvec_iter = R_CAST(const VecW*, genovec); |
| 587 |
VecW acc_ld = vecw_setzero(); |
| 588 |
VecW acc_ld_inv = vecw_setzero(); |
| 589 |
uintptr_t cur_incr = 60; |
| 590 |
for (uintptr_t full_vecs_left = 3 * (word_ct / (3 * kWordsPerVec)); ; full_vecs_left -= cur_incr) { |
| 591 |
if (full_vecs_left < 60) { |
| 592 |
if (!full_vecs_left) { |
| 593 |
ld_diff_ct = HsumW(acc_ld); |
| 594 |
ld_inv_diff_ct = HsumW(acc_ld_inv); |
| 595 |
break; |
| 596 |
} |
| 597 |
cur_incr = full_vecs_left; |
| 598 |
} |
| 599 |
VecW inner_acc_ld = vecw_setzero(); |
| 600 |
VecW inner_acc_ld_inv = vecw_setzero(); |
| 601 |
const VecW* geno_vvec_stop = &(geno_vvec_iter[cur_incr]); |
| 602 |
do { |
| 603 |
VecW loader_ldbase1 = *ldbase_vvec_iter++; |
| 604 |
VecW loader_geno1 = *geno_vvec_iter++; |
| 605 |
VecW loader_ldbase2 = *ldbase_vvec_iter++; |
| 606 |
VecW loader_geno2 = *geno_vvec_iter++; |
| 607 |
VecW xor1 = loader_ldbase1 ^ loader_geno1; |
| 608 |
VecW xor2 = loader_ldbase2 ^ loader_geno2; |
| 609 |
VecW xor_shifted1 = vecw_srli(xor1, 1); |
| 610 |
VecW xor_shifted2 = vecw_srli(xor2, 1); |
| 611 |
// xor(_low) xor_shifted loader_geno result |
| 612 |
// 1 1 |
| 613 |
// 0 0 0 1 |
| 614 |
// 0 0 1 0 |
| 615 |
// 0 1 0 0 |
| 616 |
// 0 1 1 1 |
| 617 |
// gah, don't see a way to avoid throwing in an extra xor for |
| 618 |
// loader_geno... |
| 619 |
VecW count_ld_inv = (xor1 | (xor_shifted1 ^ loader_geno1 ^ m1)) & m1; |
| 620 |
loader_ldbase1 = *ldbase_vvec_iter++; |
| 621 |
VecW count_ld = (xor1 | xor_shifted1) & m1; |
| 622 |
loader_geno1 = *geno_vvec_iter++; |
| 623 |
count_ld_inv = count_ld_inv + ((xor2 | (xor_shifted2 ^ loader_geno2 ^ m1)) & m1); |
| 624 |
xor1 = loader_ldbase1 ^ loader_geno1; |
| 625 |
count_ld = count_ld + ((xor2 | xor_shifted2) & m1); |
| 626 |
xor_shifted1 = vecw_srli(xor1, 1); |
| 627 |
count_ld_inv = count_ld_inv + ((xor1 | (xor_shifted1 ^ loader_geno1 ^ m1)) & m1); |
| 628 |
count_ld = count_ld + ((xor1 | xor_shifted1) & m1); |
| 629 |
// now count_ld and count_ld_inv each have 64 2-bit values from 0-3 |
| 630 |
|
| 631 |
count_ld_inv = (count_ld_inv & m2) + (vecw_srli(count_ld_inv, 2) & m2); |
| 632 |
count_ld = (count_ld & m2) + (vecw_srli(count_ld, 2) & m2); |
| 633 |
// now they have 32 4-bit values from 0-6 |
| 634 |
|
| 635 |
inner_acc_ld_inv = inner_acc_ld_inv + ((count_ld_inv + vecw_srli(count_ld_inv, 4)) & m4); |
| 636 |
inner_acc_ld = inner_acc_ld + ((count_ld + vecw_srli(count_ld, 4)) & m4); |
| 637 |
} while (geno_vvec_iter < geno_vvec_stop); |
| 638 |
const VecW m0 = vecw_setzero(); |
| 639 |
acc_ld_inv = acc_ld_inv + vecw_bytesum(inner_acc_ld_inv, m0); |
| 640 |
acc_ld = acc_ld + vecw_bytesum(inner_acc_ld, m0); |
| 641 |
} |
| 642 |
const uintptr_t* ldbase_iter = DowncastKVecWToW(ldbase_vvec_iter); |
| 643 |
const uintptr_t* genovec_iter = DowncastKVecWToW(geno_vvec_iter); |
| 644 |
while (genovec_iter < genovec_end) { |
| 645 |
uintptr_t ldbase_word = *ldbase_iter++; |
| 646 |
uintptr_t geno_word = *genovec_iter++; |
| 647 |
uintptr_t xor_result = ldbase_word ^ geno_word; |
| 648 |
uintptr_t xor_result_shifted = xor_result >> 1; |
| 649 |
ld_diff_ct += Popcount01Word((xor_result | xor_result_shifted) & kMask5555); |
| 650 |
ld_inv_diff_ct += Popcount01Word((xor_result | (xor_result_shifted ^ (~geno_word))) & kMask5555); |
| 651 |
} |
| 652 |
*ld_diff_ctp = ld_diff_ct; |
| 653 |
// trailing entries in last word are always "different" |
| 654 |
*ld_inv_diff_ctp = ld_inv_diff_ct - ((-sample_ct) & (kBitsPerWordD2 - 1)); |
| 655 |
} |
| 656 |
|
| 657 |
void CountLdAndInvertedLdDiffsList(const uintptr_t* __restrict ldbase_raregeno, const uint32_t* __restrict ldbase_difflist_sample_ids, const uintptr_t* __restrict raregeno, const uint32_t* __restrict difflist_sample_ids, uint32_t ldbase_difflist_len, uint32_t difflist_len, uint32_t* ld_diff_ctp, uint32_t* ld_inv_diff_ctp) { |
| 658 |
// assumes ldbase_difflist_sample_ids[ldbase_difflist_len] == sample_ct |
| 659 |
|
| 660 |
// only the count(s) with aligned common_geno values are valid. e.g. if |
| 661 |
// ldbase_common_geno and difflist_common_geno are both zero, the ld_inv_diff |
| 662 |
// return value can be anything, while if they're both three, ld_diff and |
| 663 |
// ld_inv_diff are both accurate. |
| 664 |
|
| 665 |
// some similarities to ParseLdAndMergeDifflistSubset(), but much simpler. |
| 666 |
// noticeably slower than CountLdAndInvertedLdDiffs() when the lists aren't |
| 667 |
// tiny. |
| 668 |
// possible todo: take threshold into account? |
| 669 |
|
| 670 |
uint32_t collision_ct = 0; |
| 671 |
uint32_t ld_diff_ct = 0; |
| 672 |
uint32_t ld_inv_diff_ct = 0; |
| 673 |
uint32_t ldbase_sample_idx = ldbase_difflist_sample_ids[0]; |
| 674 |
uint32_t ldbase_difflist_idx = 1; |
| 675 |
// this loop is a bit slow. attempt to bail halfway through? |
| 676 |
for (uint32_t difflist_idx = 0; difflist_idx != difflist_len; ++difflist_idx) { |
| 677 |
const uint32_t raw_sample_idx = difflist_sample_ids[difflist_idx]; |
| 678 |
while (ldbase_sample_idx < raw_sample_idx) { |
| 679 |
ldbase_sample_idx = ldbase_difflist_sample_ids[ldbase_difflist_idx++]; |
| 680 |
} |
| 681 |
if (ldbase_sample_idx > raw_sample_idx) { |
| 682 |
continue; |
| 683 |
} |
| 684 |
const uint32_t cur_raregeno = GetNyparrEntry(raregeno, difflist_idx); |
| 685 |
const uint32_t cur_ldbase_raregeno = GetNyparrEntry(ldbase_raregeno, ldbase_difflist_idx - 1); |
| 686 |
const uint32_t cur_inv_raregeno = (6 - cur_raregeno) & 3; |
| 687 |
ld_diff_ct += (cur_ldbase_raregeno != cur_raregeno); |
| 688 |
ldbase_sample_idx = ldbase_difflist_sample_ids[ldbase_difflist_idx++]; |
| 689 |
++collision_ct; |
| 690 |
ld_inv_diff_ct += (cur_ldbase_raregeno != cur_inv_raregeno); |
| 691 |
} |
| 692 |
// no more collisions, don't actually need to look at rest of |
| 693 |
// ldbase_difflist |
| 694 |
const uint32_t base_diff_ct = ldbase_difflist_len + difflist_len - 2 * collision_ct; |
| 695 |
*ld_diff_ctp = base_diff_ct + ld_diff_ct; |
| 696 |
*ld_inv_diff_ctp = base_diff_ct + ld_inv_diff_ct; |
| 697 |
} |
| 698 |
|
| 699 |
uint32_t SaveLdDifflist(const uintptr_t* __restrict genovec, const uintptr_t* __restrict ldbase_genovec, uintptr_t common_geno, uint32_t difflist_len, PgenWriterCommon* pwcp) { |
| 700 |
unsigned char* fwrite_bufp = pwcp->fwrite_bufp; |
| 701 |
if (!difflist_len) { |
| 702 |
*fwrite_bufp = 0; |
| 703 |
pwcp->fwrite_bufp = &(fwrite_bufp[1]); |
| 704 |
return 1; |
| 705 |
} |
| 706 |
unsigned char* fwrite_bufp_start = fwrite_bufp; |
| 707 |
fwrite_bufp = Vint32Append(difflist_len, fwrite_bufp); |
| 708 |
const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(pwcp->sample_ct); |
| 709 |
const uintptr_t common_geno_word = common_geno * kMask5555; |
| 710 |
const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize); |
| 711 |
unsigned char* group_first_sample_ids_iter = fwrite_bufp; |
| 712 |
unsigned char* extra_byte_cts_iter = &(fwrite_bufp[group_ct * sample_id_byte_ct]); |
| 713 |
unsigned char* raregeno_biter = &(extra_byte_cts_iter[group_ct - 1]); |
| 714 |
fwrite_bufp = &(extra_byte_cts_iter[group_ct + (difflist_len - 1) / 4]); |
| 715 |
unsigned char* last_group_vint_start = fwrite_bufp; |
| 716 |
uintptr_t raregeno_word = 0; |
| 717 |
uint32_t last_sample_idx = 0; |
| 718 |
uint32_t difflist_idx = 0; |
| 719 |
for (uint32_t widx = 0; ; ++widx) { |
| 720 |
const uintptr_t cur_geno_word = genovec[widx]; |
| 721 |
uintptr_t xor_word = ldbase_genovec? ldbase_genovec[widx] : common_geno_word; |
| 722 |
xor_word ^= cur_geno_word; |
| 723 |
if (xor_word) { |
| 724 |
const uint32_t sample_idx_base = widx * kBitsPerWordD2; |
| 725 |
do { |
| 726 |
const uint32_t sample_idx_lowbits = ctzw(xor_word) / 2; |
| 727 |
const uint32_t new_sample_idx = sample_idx_base + sample_idx_lowbits; |
| 728 |
raregeno_word |= ((cur_geno_word >> (2 * sample_idx_lowbits)) & 3) << (2 * (difflist_idx % kBitsPerWordD2)); |
| 729 |
if (!(difflist_idx % kPglDifflistGroupSize)) { |
| 730 |
group_first_sample_ids_iter = memcpyua(group_first_sample_ids_iter, &new_sample_idx, sample_id_byte_ct); |
| 731 |
if (difflist_idx) { |
| 732 |
*extra_byte_cts_iter++ = S_CAST(uintptr_t, fwrite_bufp - last_group_vint_start) - (kPglDifflistGroupSize - 1); |
| 733 |
} |
| 734 |
last_group_vint_start = fwrite_bufp; |
| 735 |
} else { |
| 736 |
assert(new_sample_idx >= last_sample_idx + 1); |
| 737 |
fwrite_bufp = Vint32Append(new_sample_idx - last_sample_idx, fwrite_bufp); |
| 738 |
} |
| 739 |
++difflist_idx; |
| 740 |
last_sample_idx = new_sample_idx; |
| 741 |
if (difflist_idx == difflist_len) { |
| 742 |
SubwordStore(raregeno_word, 1 + (((difflist_len - 1) / 4) % sizeof(intptr_t)), raregeno_biter); |
| 743 |
pwcp->fwrite_bufp = fwrite_bufp; |
| 744 |
return fwrite_bufp - fwrite_bufp_start; |
| 745 |
} |
| 746 |
if (!(difflist_idx % kBitsPerWordD2)) { |
| 747 |
AppendW(raregeno_word, &raregeno_biter); |
| 748 |
raregeno_word = 0; |
| 749 |
} |
| 750 |
xor_word &= (~(3 * k1LU)) << (2 * sample_idx_lowbits); |
| 751 |
} while (xor_word); |
| 752 |
} |
| 753 |
} |
| 754 |
} |
| 755 |
|
| 756 |
void OnebitPreprocessBuf(const uintptr_t* __restrict genovec, uint32_t sample_ct, uint32_t common2_code, uintptr_t* __restrict genovec_buf) { |
| 757 |
assert(sample_ct); |
| 758 |
const uint32_t vec_ct = NypCtToVecCt(sample_ct); |
| 759 |
// todo: look for better ways to perform some of these operations |
| 760 |
const VecW* geno_vvec_iter = R_CAST(const VecW*, genovec); |
| 761 |
const VecW* geno_vvec_end = &(geno_vvec_iter[vec_ct]); |
| 762 |
VecW* write_iter = R_CAST(VecW*, genovec_buf); |
| 763 |
const VecW m1 = VCONST_W(kMask5555); |
| 764 |
if (common2_code < 5) { |
| 765 |
if (common2_code == 1) { |
| 766 |
// 11 -> 10, everything else unchanged |
| 767 |
// todo: check if these loops are actually faster as simple while loops |
| 768 |
// todo: check if it's better to unroll these loops to process 2 __m128is |
| 769 |
// at a time |
| 770 |
do { |
| 771 |
const VecW cur_geno = *geno_vvec_iter++; |
| 772 |
*write_iter++ = vecw_and_notfirst(m1 & vecw_srli(cur_geno, 1), cur_geno); |
| 773 |
} while (geno_vvec_iter < geno_vvec_end); |
| 774 |
} else if (common2_code == 3) { |
| 775 |
// 00 -> 00, 01 -> 10, 10 -> 10, 11 -> 01 |
| 776 |
do { |
| 777 |
const VecW cur_geno = *geno_vvec_iter++; |
| 778 |
const VecW cur_geno_rshift = vecw_srli(cur_geno, 1); |
| 779 |
const VecW cur_geno_xor_masked = (cur_geno ^ cur_geno_rshift) & m1; |
| 780 |
const VecW cur_geno_or_masked = (cur_geno | cur_geno_rshift) & m1; |
| 781 |
*write_iter++ = cur_geno_xor_masked + cur_geno_or_masked; |
| 782 |
} while (geno_vvec_iter < geno_vvec_end); |
| 783 |
} else { |
| 784 |
assert(common2_code == 2); |
| 785 |
// 00 -> 00, 01 -> 10, 10 -> 01, 11 -> 10 |
| 786 |
do { |
| 787 |
const VecW cur_geno = *geno_vvec_iter++; |
| 788 |
const VecW cur_geno_or_masked = (cur_geno | vecw_srli(cur_geno, 1)) & m1; |
| 789 |
const VecW cur_geno_lowbits = cur_geno & m1; |
| 790 |
*write_iter++ = cur_geno_lowbits + cur_geno_or_masked; |
| 791 |
} while (geno_vvec_iter < geno_vvec_end); |
| 792 |
} |
| 793 |
} else { |
| 794 |
if (common2_code == 5) { |
| 795 |
// 00 -> 10, 01 -> 00, 10 -> 01, 11 -> 10 |
| 796 |
do { |
| 797 |
const VecW cur_geno = *geno_vvec_iter++; |
| 798 |
const VecW cur_geno_rshift = vecw_srli(cur_geno, 1); |
| 799 |
const VecW cur_geno_not_xor_masked = vecw_and_notfirst(cur_geno ^ cur_geno_rshift, m1); |
| 800 |
const VecW cur_geno_rshift_masked = cur_geno_rshift & m1; |
| 801 |
*write_iter++ = cur_geno_not_xor_masked + (cur_geno_not_xor_masked | cur_geno_rshift_masked); |
| 802 |
} while (geno_vvec_iter < geno_vvec_end); |
| 803 |
} else if (common2_code == 9) { |
| 804 |
// 00 -> 10, 01 -> 10, 10 -> 00, 11 -> 01 |
| 805 |
const VecW not_m1 = VCONST_W(kMaskAAAA); |
| 806 |
do { |
| 807 |
const VecW cur_geno = *geno_vvec_iter++; |
| 808 |
*write_iter++ = (cur_geno ^ not_m1) - vecw_and_notfirst(not_m1, vecw_and_notfirst(vecw_srli(cur_geno, 1), cur_geno)); |
| 809 |
} while (geno_vvec_iter < geno_vvec_end); |
| 810 |
} else { |
| 811 |
assert(common2_code == 6); |
| 812 |
// 00 -> 10, 01 -> 00, 10 -> 10, 11 -> 01 |
| 813 |
do { |
| 814 |
const VecW cur_geno = *geno_vvec_iter++; |
| 815 |
const VecW cur_geno_not_lowbits = vecw_and_notfirst(cur_geno, m1); |
| 816 |
const VecW cur_geno_rshift_masked = vecw_srli(cur_geno, 1) & m1; |
| 817 |
*write_iter++ = cur_geno_not_lowbits + (cur_geno_not_lowbits | cur_geno_rshift_masked); |
| 818 |
} while (geno_vvec_iter < geno_vvec_end); |
| 819 |
} |
| 820 |
} |
| 821 |
} |
| 822 |
|
| 823 |
uint32_t SaveOnebit(const uintptr_t* __restrict genovec, uint32_t common2_code, uint32_t onebit_difflist_len, PgenWriterCommon* pwcp) { |
| 824 |
// Uses ldbase_genovec as a temporary buffer. |
| 825 |
|
| 826 |
// common2_code is expected to have the difference between the common |
| 827 |
// genotype values in bits 0-1, and the smaller common genotype value in bits |
| 828 |
// 2-3. |
| 829 |
unsigned char* fwrite_bufp_start = pwcp->fwrite_bufp; |
| 830 |
*fwrite_bufp_start = common2_code; |
| 831 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 832 |
uintptr_t* __restrict genovec_buf = pwcp->ldbase_genovec; |
| 833 |
// There's a 4-byte-interleaved format which is slightly more efficient for |
| 834 |
// unsubsetted handling (~10 fewer compression/decompression operations per |
| 835 |
// 32 genotypes), but that's only a 1-2% speedup, which probably isn't worth |
| 836 |
// the more annoying subsetting. |
| 837 |
// |
| 838 |
// Any 10s and 11s are saved as 00 in this part. |
| 839 |
// Similar logic is used to handle the other five possibilities (00/10, |
| 840 |
// 00/11, 01/10, 01/11, 10/11); all of them should be expected to actually |
| 841 |
// happen. (E.g. 01/11 can happen at a high MAF variant when there's lots of |
| 842 |
// missing data.) To reduce branching, we preprocess genovec_buf to have |
| 843 |
// even bit set iff the corresponding genotype is equal to the high common |
| 844 |
// genotype value, and odd bit set iff the corresponding genotype is one of |
| 845 |
// the two uncommon values. (There may be a better way to do this, analogous |
| 846 |
// to the simpler decompression algorithm.) |
| 847 |
OnebitPreprocessBuf(genovec, sample_ct, common2_code, genovec_buf); |
| 848 |
ZeroTrailingNyps(sample_ct, genovec_buf); |
| 849 |
const uint32_t word_read_ct = NypCtToWordCt(sample_ct); |
| 850 |
PackWordsToHalfwordsMask(genovec_buf, word_read_ct, &(fwrite_bufp_start[1])); |
| 851 |
const uint32_t onebit_block_len = (sample_ct + 15) / CHAR_BIT; |
| 852 |
unsigned char* fwrite_bufp = Vint32Append(onebit_difflist_len, &(fwrite_bufp_start[onebit_block_len])); |
| 853 |
// the rest is almost identical to SaveLdDifflist() |
| 854 |
if (!onebit_difflist_len) { |
| 855 |
pwcp->fwrite_bufp = fwrite_bufp; |
| 856 |
return (onebit_block_len + 1); |
| 857 |
} |
| 858 |
const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(pwcp->sample_ct); |
| 859 |
const uint32_t group_ct = DivUp(onebit_difflist_len, kPglDifflistGroupSize); |
| 860 |
unsigned char* group_first_sample_ids_iter = fwrite_bufp; |
| 861 |
unsigned char* extra_byte_cts_iter = &(fwrite_bufp[group_ct * sample_id_byte_ct]); |
| 862 |
unsigned char* raregeno_biter = &(extra_byte_cts_iter[group_ct - 1]); |
| 863 |
fwrite_bufp = &(extra_byte_cts_iter[group_ct + (onebit_difflist_len - 1) / 4]); |
| 864 |
unsigned char* last_group_vint_start = fwrite_bufp; |
| 865 |
uintptr_t raregeno_word = 0; |
| 866 |
uint32_t last_sample_idx = 0; |
| 867 |
uint32_t difflist_idx = 0; |
| 868 |
for (uint32_t widx = 0; ; ++widx) { |
| 869 |
uintptr_t xor_word = genovec_buf[widx] & kMaskAAAA; |
| 870 |
if (xor_word) { |
| 871 |
const uintptr_t cur_geno_word = genovec[widx]; |
| 872 |
const uint32_t sample_idx_base = widx * kBitsPerWordD2; |
| 873 |
|
| 874 |
do { |
| 875 |
const uint32_t sample_idx_lowbits = ctzw(xor_word) / 2; |
| 876 |
const uint32_t new_sample_idx = sample_idx_base + sample_idx_lowbits; |
| 877 |
if (!(difflist_idx % kBitsPerWordD2)) { |
| 878 |
if (!(difflist_idx % kPglDifflistGroupSize)) { |
| 879 |
SubU32StoreMov(new_sample_idx, sample_id_byte_ct, &group_first_sample_ids_iter); |
| 880 |
if (difflist_idx) { |
| 881 |
*extra_byte_cts_iter++ = S_CAST(uintptr_t, fwrite_bufp - last_group_vint_start) - (kPglDifflistGroupSize - 1); |
| 882 |
AppendW(raregeno_word, &raregeno_biter); |
| 883 |
raregeno_word = 0; |
| 884 |
} |
| 885 |
last_group_vint_start = fwrite_bufp; |
| 886 |
goto SaveOnebit_skip_delta_write; |
| 887 |
} |
| 888 |
AppendW(raregeno_word, &raregeno_biter); |
| 889 |
raregeno_word = 0; |
| 890 |
} |
| 891 |
assert(new_sample_idx >= last_sample_idx + 1); |
| 892 |
fwrite_bufp = Vint32Append(new_sample_idx - last_sample_idx, fwrite_bufp); |
| 893 |
SaveOnebit_skip_delta_write: |
| 894 |
raregeno_word |= ((cur_geno_word >> (2 * sample_idx_lowbits)) & 3) << (2 * (difflist_idx % kBitsPerWordD2)); |
| 895 |
++difflist_idx; |
| 896 |
last_sample_idx = new_sample_idx; |
| 897 |
xor_word &= xor_word - 1; |
| 898 |
} while (xor_word); |
| 899 |
// trailing bits of genovec_buf guaranteed to be zeroed out |
| 900 |
if (difflist_idx == onebit_difflist_len) { |
| 901 |
SubwordStore(raregeno_word, 1 + (((onebit_difflist_len - 1) / 4) % sizeof(intptr_t)), raregeno_biter); |
| 902 |
pwcp->fwrite_bufp = fwrite_bufp; |
| 903 |
return fwrite_bufp - fwrite_bufp_start; |
| 904 |
} |
| 905 |
} |
| 906 |
} |
| 907 |
} |
| 908 |
|
| 909 |
// returns vrec_len |
| 910 |
uint32_t PwcAppendBiallelicGenovecMain(const uintptr_t* __restrict genovec, uint32_t vidx, PgenWriterCommon* pwcp, uint32_t* het_ct_ptr, uint32_t* altxy_ct_ptr, unsigned char* vrtype_ptr) { |
| 911 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 912 |
assert((!(sample_ct % kBitsPerWordD2)) || (!(genovec[sample_ct / kBitsPerWordD2] >> (2 * (sample_ct % kBitsPerWordD2))))); |
| 913 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 914 |
GenoarrCountFreqsUnsafe(genovec, sample_ct, genocounts); |
| 915 |
if (het_ct_ptr) { |
| 916 |
*het_ct_ptr = genocounts[1]; |
| 917 |
if (altxy_ct_ptr) { |
| 918 |
*altxy_ct_ptr = genocounts[2]; |
| 919 |
} |
| 920 |
} |
| 921 |
uint32_t most_common_geno = (genocounts[1] > genocounts[0]); |
| 922 |
uint32_t second_most_common_geno = 1 - most_common_geno; |
| 923 |
uint32_t largest_geno_ct = genocounts[most_common_geno]; |
| 924 |
uint32_t second_largest_geno_ct = genocounts[second_most_common_geno]; |
| 925 |
for (uint32_t cur_geno = 2; cur_geno != 4; ++cur_geno) { |
| 926 |
const uint32_t cur_geno_ct = genocounts[cur_geno]; |
| 927 |
if (cur_geno_ct > second_largest_geno_ct) { |
| 928 |
if (cur_geno_ct > largest_geno_ct) { |
| 929 |
second_largest_geno_ct = largest_geno_ct; |
| 930 |
second_most_common_geno = most_common_geno; |
| 931 |
largest_geno_ct = cur_geno_ct; |
| 932 |
most_common_geno = cur_geno; |
| 933 |
} else { |
| 934 |
second_largest_geno_ct = cur_geno_ct; |
| 935 |
second_most_common_geno = cur_geno; |
| 936 |
} |
| 937 |
} |
| 938 |
} |
| 939 |
const uint32_t difflist_len = sample_ct - largest_geno_ct; |
| 940 |
const uint32_t rare_2_geno_ct_sum = difflist_len - second_largest_geno_ct; |
| 941 |
// average of 10-11 bits per difflist entry |
| 942 |
const uint32_t sample_ctd8 = sample_ct / 8; |
| 943 |
const uint32_t sample_ctd64 = sample_ct / 64; |
| 944 |
uint32_t max_difflist_len = sample_ctd8 - 2 * sample_ctd64 + rare_2_geno_ct_sum; |
| 945 |
if (max_difflist_len > sample_ctd8) { |
| 946 |
max_difflist_len = sample_ctd8; |
| 947 |
} |
| 948 |
const uint32_t difflist_viable = (most_common_geno != 1) && (difflist_len <= max_difflist_len); |
| 949 |
|
| 950 |
uintptr_t* ldbase_genovec = pwcp->ldbase_genovec; |
| 951 |
STD_ARRAY_REF(uint32_t, 4) ldbase_genocounts = pwcp->ldbase_genocounts; |
| 952 |
if (!(vidx % kPglVblockSize)) { |
| 953 |
// beginning of a variant block. save raw fpos in header; LD compression |
| 954 |
// prohibited. |
| 955 |
|
| 956 |
// er, need to use a relative offset in the multithreaded case, absolute |
| 957 |
// position isn't known |
| 958 |
pwcp->vblock_fpos[vidx / kPglVblockSize] = pwcp->vblock_fpos_offset + S_CAST(uintptr_t, pwcp->fwrite_bufp - pwcp->fwrite_buf); |
| 959 |
} else if (difflist_len > sample_ctd64) { |
| 960 |
// do not use LD compression if there are at least this many differences. |
| 961 |
// tune this threshold in the future. |
| 962 |
const uint32_t ld_diff_threshold = difflist_viable? (difflist_len - sample_ctd64) : max_difflist_len; |
| 963 |
// number of changes between current genovec and LD reference is bounded |
| 964 |
// below by sum(genocounts[x] - ldbase_genocounts[x]) / 2 |
| 965 |
const int32_t count02_limit = 2 * ld_diff_threshold - abs_i32(genocounts[1] - ldbase_genocounts[1]) + abs_i32(genocounts[3] - ldbase_genocounts[3]); |
| 966 |
if ((S_CAST(int32_t, abs_i32(genocounts[0] - ldbase_genocounts[0]) + abs_i32(genocounts[2] - ldbase_genocounts[2])) < count02_limit) || (S_CAST(int32_t, abs_i32(genocounts[0] - ldbase_genocounts[2]) + abs_i32(genocounts[2] - ldbase_genocounts[0])) < count02_limit)) { |
| 967 |
uint32_t ld_diff_ct; |
| 968 |
uint32_t ld_inv_diff_ct; |
| 969 |
// okay, perform a brute-force diff |
| 970 |
// (could check LD vs. inverted LD separately?) |
| 971 |
if (pwcp->ldbase_common_geno < 4) { |
| 972 |
// unpack to ldbase_genovec |
| 973 |
PgrDifflistToGenovecUnsafe(pwcp->ldbase_raregeno, pwcp->ldbase_difflist_sample_ids, pwcp->ldbase_common_geno, sample_ct, pwcp->ldbase_difflist_len, ldbase_genovec); |
| 974 |
ZeroTrailingNyps(sample_ct, ldbase_genovec); |
| 975 |
pwcp->ldbase_common_geno = UINT32_MAX; |
| 976 |
} |
| 977 |
CountLdAndInvertedLdDiffs(ldbase_genovec, genovec, sample_ct, &ld_diff_ct, &ld_inv_diff_ct); |
| 978 |
if ((ld_diff_ct < ld_diff_threshold) || (ld_inv_diff_ct < ld_diff_threshold)) { |
| 979 |
const uintptr_t invert_before_compressing = (ld_inv_diff_ct < ld_diff_ct); |
| 980 |
*vrtype_ptr = 2 + invert_before_compressing; |
| 981 |
if (invert_before_compressing) { |
| 982 |
GenovecInvertCopyUnsafe(genovec, sample_ct, pwcp->genovec_invert_buf); |
| 983 |
ld_diff_ct = ld_inv_diff_ct; |
| 984 |
} |
| 985 |
return SaveLdDifflist(invert_before_compressing? pwcp->genovec_invert_buf : genovec, ldbase_genovec, 0, ld_diff_ct, pwcp); |
| 986 |
} |
| 987 |
} |
| 988 |
} |
| 989 |
const uint32_t genovec_word_ct = NypCtToWordCt(sample_ct); |
| 990 |
STD_ARRAY_COPY(genocounts, 4, ldbase_genocounts); |
| 991 |
pwcp->ldbase_common_geno = UINT32_MAX; |
| 992 |
if ((!difflist_viable) && (rare_2_geno_ct_sum < sample_ct / (2 * kPglMaxDifflistLenDivisor))) { |
| 993 |
*vrtype_ptr = 1; |
| 994 |
uint32_t larger_common_geno = second_most_common_geno; |
| 995 |
uint32_t smaller_common_geno = most_common_geno; |
| 996 |
if (most_common_geno > second_most_common_geno) { |
| 997 |
larger_common_geno = most_common_geno; |
| 998 |
smaller_common_geno = second_most_common_geno; |
| 999 |
} |
| 1000 |
const uint32_t vrec_len = SaveOnebit(genovec, larger_common_geno + (smaller_common_geno * 3), rare_2_geno_ct_sum, pwcp); |
| 1001 |
memcpy(ldbase_genovec, genovec, genovec_word_ct * sizeof(intptr_t)); |
| 1002 |
return vrec_len; |
| 1003 |
} |
| 1004 |
memcpy(ldbase_genovec, genovec, genovec_word_ct * sizeof(intptr_t)); |
| 1005 |
if (difflist_viable) { |
| 1006 |
#ifdef FUTURE_ENCODER |
| 1007 |
if ((!difflist_len) && (!most_common_geno)) { |
| 1008 |
*vrtype_ptr = 5; |
| 1009 |
return 0; |
| 1010 |
} |
| 1011 |
#endif |
| 1012 |
*vrtype_ptr = 4 + most_common_geno; |
| 1013 |
return SaveLdDifflist(genovec, nullptr, most_common_geno, difflist_len, pwcp); |
| 1014 |
} |
| 1015 |
*vrtype_ptr = 0; |
| 1016 |
const uint32_t vrec_len = NypCtToByteCt(sample_ct); |
| 1017 |
pwcp->fwrite_bufp = memcpyua(pwcp->fwrite_bufp, genovec, vrec_len); |
| 1018 |
return vrec_len; |
| 1019 |
} |
| 1020 |
|
| 1021 |
void PwcAppendBiallelicGenovec(const uintptr_t* __restrict genovec, PgenWriterCommon* pwcp) { |
| 1022 |
const uint32_t vidx = pwcp->vidx; |
| 1023 |
unsigned char vrtype; |
| 1024 |
const uint32_t vrec_len = PwcAppendBiallelicGenovecMain(genovec, vidx, pwcp, nullptr, nullptr, &vrtype); |
| 1025 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 1026 |
pwcp->vidx += 1; |
| 1027 |
SubU32Store(vrec_len, vrec_len_byte_ct, &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct])); |
| 1028 |
// could have a single expression which branchlessly handles both cases, but |
| 1029 |
// doubt that's worthwhile |
| 1030 |
if (!pwcp->phase_dosage_gflags) { |
| 1031 |
pwcp->vrtype_buf[vidx / kBitsPerWordD4] |= S_CAST(uintptr_t, vrtype) << (4 * (vidx % kBitsPerWordD4)); |
| 1032 |
} else { |
| 1033 |
DowncastToUc(pwcp->vrtype_buf)[vidx] = vrtype; |
| 1034 |
} |
| 1035 |
} |
| 1036 |
|
| 1037 |
BoolErr SpgwFlush(STPgenWriter* spgwp) { |
| 1038 |
PgenWriterCommon* pwcp = GetPwcp(spgwp); |
| 1039 |
if (pwcp->fwrite_bufp >= &(pwcp->fwrite_buf[kPglFwriteBlockSize])) { |
| 1040 |
const uintptr_t cur_byte_ct = pwcp->fwrite_bufp - pwcp->fwrite_buf; |
| 1041 |
FILE** pgen_outfilep = GetPgenOutfilep(spgwp); |
| 1042 |
if (unlikely(fwrite_checked(pwcp->fwrite_buf, cur_byte_ct, *pgen_outfilep))) { |
| 1043 |
return 1; |
| 1044 |
} |
| 1045 |
pwcp->vblock_fpos_offset += cur_byte_ct; |
| 1046 |
pwcp->fwrite_bufp = pwcp->fwrite_buf; |
| 1047 |
} |
| 1048 |
return 0; |
| 1049 |
} |
| 1050 |
|
| 1051 |
|
| 1052 |
uint32_t SaveLdTwoListDelta(const uintptr_t* __restrict difflist_raregeno, const uint32_t* __restrict difflist_sample_ids, uint32_t ld_diff_ct, PgenWriterCommon* pwcp) { |
| 1053 |
// assumes ldbase_difflist_sample_ids[ldbase_difflist_len] == sample_ct, and |
| 1054 |
// difflist_sample_ids[ldbase_difflist_len] == sample_ct. |
| 1055 |
// assumes biallelic data. |
| 1056 |
|
| 1057 |
// similar to SaveLdDifflist() and, to a lesser degree, |
| 1058 |
// ParseLdAndMergeDifflistSubset() |
| 1059 |
unsigned char* fwrite_bufp = pwcp->fwrite_bufp; |
| 1060 |
if (!ld_diff_ct) { |
| 1061 |
*fwrite_bufp = 0; |
| 1062 |
pwcp->fwrite_bufp = &(fwrite_bufp[1]); |
| 1063 |
return 1; |
| 1064 |
} |
| 1065 |
unsigned char* fwrite_bufp_start = fwrite_bufp; |
| 1066 |
fwrite_bufp = Vint32Append(ld_diff_ct, fwrite_bufp); |
| 1067 |
const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(pwcp->sample_ct); |
| 1068 |
const uint32_t group_ct = DivUp(ld_diff_ct, kPglDifflistGroupSize); |
| 1069 |
const uint32_t ldbase_common_geno = pwcp->ldbase_common_geno; |
| 1070 |
assert(ldbase_common_geno < 4); |
| 1071 |
const uintptr_t* __restrict ldbase_raregeno = pwcp->ldbase_raregeno; |
| 1072 |
const uint32_t* __restrict ldbase_sample_ids = pwcp->ldbase_difflist_sample_ids; |
| 1073 |
unsigned char* group_first_sample_ids_iter = fwrite_bufp; |
| 1074 |
unsigned char* extra_byte_cts_iter = &(fwrite_bufp[group_ct * sample_id_byte_ct]); |
| 1075 |
unsigned char* raregeno_write_biter = &(extra_byte_cts_iter[group_ct - 1]); |
| 1076 |
fwrite_bufp = &(extra_byte_cts_iter[group_ct + (ld_diff_ct - 1) / 4]); |
| 1077 |
unsigned char* last_group_vint_start = fwrite_bufp; |
| 1078 |
uintptr_t ldbase_raregeno_word = 0; |
| 1079 |
uintptr_t difflist_raregeno_word = 0; |
| 1080 |
uintptr_t raregeno_write_word = 0; |
| 1081 |
uint32_t last_sample_idx = 0; |
| 1082 |
|
| 1083 |
uint32_t next_ldbase_sample_idx = ldbase_sample_ids[0]; |
| 1084 |
uint32_t next_difflist_sample_idx = difflist_sample_ids[0]; |
| 1085 |
uint32_t ldbase_idx = 0; |
| 1086 |
uint32_t difflist_idx = 0; |
| 1087 |
uint32_t diff_written_ct = 0; |
| 1088 |
while (diff_written_ct < ld_diff_ct) { |
| 1089 |
uintptr_t cur_geno; |
| 1090 |
uint32_t new_sample_idx; |
| 1091 |
if (next_ldbase_sample_idx <= next_difflist_sample_idx) { |
| 1092 |
ldbase_raregeno_word >>= 2; |
| 1093 |
if (!(ldbase_idx % kBitsPerWordD2)) { |
| 1094 |
ldbase_raregeno_word = ldbase_raregeno[ldbase_idx / kBitsPerWordD2]; |
| 1095 |
} |
| 1096 |
++ldbase_idx; |
| 1097 |
} |
| 1098 |
if (next_difflist_sample_idx <= next_ldbase_sample_idx) { |
| 1099 |
difflist_raregeno_word >>= 2; |
| 1100 |
if (!(difflist_idx % kBitsPerWordD2)) { |
| 1101 |
difflist_raregeno_word = difflist_raregeno[difflist_idx / kBitsPerWordD2]; |
| 1102 |
} |
| 1103 |
new_sample_idx = next_difflist_sample_idx; |
| 1104 |
++difflist_idx; |
| 1105 |
cur_geno = difflist_raregeno_word & 3; |
| 1106 |
next_difflist_sample_idx = difflist_sample_ids[difflist_idx]; |
| 1107 |
if (next_ldbase_sample_idx == new_sample_idx) { |
| 1108 |
next_ldbase_sample_idx = ldbase_sample_ids[ldbase_idx]; |
| 1109 |
if (cur_geno == (ldbase_raregeno_word & 3)) { |
| 1110 |
continue; |
| 1111 |
} |
| 1112 |
} |
| 1113 |
} else { |
| 1114 |
cur_geno = ldbase_common_geno; |
| 1115 |
new_sample_idx = next_ldbase_sample_idx; |
| 1116 |
next_ldbase_sample_idx = ldbase_sample_ids[ldbase_idx]; |
| 1117 |
} |
| 1118 |
raregeno_write_word |= cur_geno << (2 * (diff_written_ct % kBitsPerWordD2)); |
| 1119 |
if (!(diff_written_ct % kPglDifflistGroupSize)) { |
| 1120 |
SubU32StoreMov(new_sample_idx, sample_id_byte_ct, &group_first_sample_ids_iter); |
| 1121 |
if (diff_written_ct) { |
| 1122 |
*extra_byte_cts_iter++ = S_CAST(uintptr_t, fwrite_bufp - last_group_vint_start) - (kPglDifflistGroupSize - 1); |
| 1123 |
} |
| 1124 |
last_group_vint_start = fwrite_bufp; |
| 1125 |
} else { |
| 1126 |
fwrite_bufp = Vint32Append(new_sample_idx - last_sample_idx, fwrite_bufp); |
| 1127 |
} |
| 1128 |
last_sample_idx = new_sample_idx; |
| 1129 |
++diff_written_ct; |
| 1130 |
if (!(diff_written_ct % kBitsPerWordD2)) { |
| 1131 |
AppendW(raregeno_write_word, &raregeno_write_biter); |
| 1132 |
raregeno_write_word = 0; |
| 1133 |
} |
| 1134 |
} |
| 1135 |
if (diff_written_ct % kBitsPerWordD2) { |
| 1136 |
SubwordStore(raregeno_write_word, 1 + (((ld_diff_ct - 1) / 4) % kBytesPerWord), raregeno_write_biter); |
| 1137 |
} |
| 1138 |
pwcp->fwrite_bufp = fwrite_bufp; |
| 1139 |
return fwrite_bufp - fwrite_bufp_start; |
| 1140 |
} |
| 1141 |
|
| 1142 |
uint32_t SaveLdInputList(PgenWriterCommon* pwcp) { |
| 1143 |
// simply "copies" ldbase_{raregeno,difflist_sample_ids,difflist_len} to the |
| 1144 |
// write buffer. |
| 1145 |
unsigned char* fwrite_bufp = pwcp->fwrite_bufp; |
| 1146 |
const uint32_t difflist_len = pwcp->ldbase_difflist_len; |
| 1147 |
if (!difflist_len) { |
| 1148 |
*fwrite_bufp = 0; |
| 1149 |
pwcp->fwrite_bufp = &(fwrite_bufp[1]); |
| 1150 |
return 1; |
| 1151 |
} |
| 1152 |
unsigned char* fwrite_bufp_start = fwrite_bufp; |
| 1153 |
fwrite_bufp = Vint32Append(difflist_len, fwrite_bufp); |
| 1154 |
const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(pwcp->sample_ct); |
| 1155 |
const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize); |
| 1156 |
const uint32_t* __restrict difflist_sample_ids = pwcp->ldbase_difflist_sample_ids; |
| 1157 |
unsigned char* group_first_sample_ids_iter = fwrite_bufp; |
| 1158 |
unsigned char* extra_byte_cts_iter = &(fwrite_bufp[group_ct * sample_id_byte_ct]); |
| 1159 |
fwrite_bufp = memcpyua(&(extra_byte_cts_iter[group_ct - 1]), pwcp->ldbase_raregeno, NypCtToByteCt(difflist_len)); |
| 1160 |
unsigned char* last_group_vint_start = nullptr; |
| 1161 |
uint32_t last_sample_idx = 0; |
| 1162 |
for (uint32_t difflist_idx = 0; difflist_idx != difflist_len; ++difflist_idx) { |
| 1163 |
const uint32_t new_sample_idx = difflist_sample_ids[difflist_idx]; |
| 1164 |
if (!(difflist_idx % kPglDifflistGroupSize)) { |
| 1165 |
SubU32StoreMov(new_sample_idx, sample_id_byte_ct, &group_first_sample_ids_iter); |
| 1166 |
if (difflist_idx) { |
| 1167 |
*extra_byte_cts_iter++ = S_CAST(uintptr_t, fwrite_bufp - last_group_vint_start) - (kPglDifflistGroupSize - 1); |
| 1168 |
} |
| 1169 |
last_group_vint_start = fwrite_bufp; |
| 1170 |
} else { |
| 1171 |
// assert(new_sample_idx >= last_sample_idx + 1); |
| 1172 |
fwrite_bufp = Vint32Append(new_sample_idx - last_sample_idx, fwrite_bufp); |
| 1173 |
} |
| 1174 |
last_sample_idx = new_sample_idx; |
| 1175 |
} |
| 1176 |
pwcp->fwrite_bufp = fwrite_bufp; |
| 1177 |
return fwrite_bufp - fwrite_bufp_start; |
| 1178 |
} |
| 1179 |
|
| 1180 |
uint32_t PwcAppendBiallelicDifflistLimitedMain(const uintptr_t* __restrict raregeno, const uint32_t* __restrict difflist_sample_ids, uint32_t vidx, uint32_t difflist_common_geno, uint32_t difflist_len, PgenWriterCommon* pwcp, unsigned char* vrtype_ptr) { |
| 1181 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 1182 |
// caller's responsibility not to exceed this limit |
| 1183 |
assert(difflist_len <= 2 * (sample_ct / kPglMaxDifflistLenDivisor)); |
| 1184 |
|
| 1185 |
// trailing bits of raregeno must be zeroed out |
| 1186 |
|
| 1187 |
assert(difflist_common_geno < 4); |
| 1188 |
assert((!(difflist_len % kBitsPerWordD2)) || (!(raregeno[difflist_len / kBitsPerWordD2] >> (2 * (difflist_len % kBitsPerWordD2))))); |
| 1189 |
assert(difflist_sample_ids[difflist_len] == sample_ct); |
| 1190 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 1191 |
GenoarrCountFreqsUnsafe(raregeno, difflist_len, genocounts); |
| 1192 |
assert(!genocounts[difflist_common_geno]); |
| 1193 |
genocounts[difflist_common_geno] = sample_ct - difflist_len; |
| 1194 |
uint32_t second_most_common_geno = difflist_common_geno? 0 : 1; |
| 1195 |
uint32_t second_largest_geno_ct = genocounts[second_most_common_geno]; |
| 1196 |
for (uint32_t cur_geno = second_most_common_geno + 1; cur_geno != 4; ++cur_geno) { |
| 1197 |
if (cur_geno == difflist_common_geno) { |
| 1198 |
continue; |
| 1199 |
} |
| 1200 |
const uint32_t cur_geno_ct = genocounts[cur_geno]; |
| 1201 |
if (cur_geno_ct > second_largest_geno_ct) { |
| 1202 |
second_most_common_geno = cur_geno; |
| 1203 |
second_largest_geno_ct = cur_geno_ct; |
| 1204 |
} |
| 1205 |
} |
| 1206 |
const uint32_t rare_2_geno_ct_sum = difflist_len - second_largest_geno_ct; |
| 1207 |
const uint32_t sample_ctd8 = sample_ct / 8; |
| 1208 |
const uint32_t sample_ctd64 = sample_ct / 64; |
| 1209 |
uint32_t max_difflist_len = sample_ctd8 - 2 * sample_ctd64 + rare_2_geno_ct_sum; |
| 1210 |
if (max_difflist_len > sample_ctd8) { |
| 1211 |
max_difflist_len = sample_ctd8; |
| 1212 |
} |
| 1213 |
const uint32_t difflist_viable = (difflist_common_geno != 1) && (difflist_len <= max_difflist_len); |
| 1214 |
STD_ARRAY_REF(uint32_t, 4) ldbase_genocounts = pwcp->ldbase_genocounts; |
| 1215 |
if (!(vidx % kPglVblockSize)) { |
| 1216 |
pwcp->vblock_fpos[vidx / kPglVblockSize] = pwcp->vblock_fpos_offset + S_CAST(uintptr_t, pwcp->fwrite_bufp - pwcp->fwrite_buf); |
| 1217 |
} else if (difflist_len > sample_ctd64) { |
| 1218 |
const uint32_t ld_diff_threshold = difflist_viable? (difflist_len - sample_ctd64) : max_difflist_len; |
| 1219 |
// number of changes between current genovec and LD reference is bounded |
| 1220 |
// below by sum(genocounts[x] - ldbase_genocounts[x]) / 2 |
| 1221 |
const int32_t count02_limit = 2 * ld_diff_threshold - abs_i32(genocounts[1] - ldbase_genocounts[1]) + abs_i32(genocounts[3] - ldbase_genocounts[3]); |
| 1222 |
if ((S_CAST(int32_t, abs_i32(genocounts[0] - ldbase_genocounts[0]) + abs_i32(genocounts[2] - ldbase_genocounts[2])) < count02_limit) || (S_CAST(int32_t, abs_i32(genocounts[0] - ldbase_genocounts[2]) + abs_i32(genocounts[2] - ldbase_genocounts[0])) < count02_limit)) { |
| 1223 |
uint32_t ld_diff_ct; |
| 1224 |
uint32_t ld_inv_diff_ct; |
| 1225 |
if (pwcp->ldbase_common_geno < 4) { |
| 1226 |
pwcp->ldbase_difflist_sample_ids[pwcp->ldbase_difflist_len] = sample_ct; |
| 1227 |
CountLdAndInvertedLdDiffsList(pwcp->ldbase_raregeno, pwcp->ldbase_difflist_sample_ids, raregeno, difflist_sample_ids, pwcp->ldbase_difflist_len, difflist_len, &ld_diff_ct, &ld_inv_diff_ct); |
| 1228 |
const uint32_t difflist_common_geno_inv = (6 - difflist_common_geno) & 3; |
| 1229 |
if (pwcp->ldbase_common_geno != difflist_common_geno) { |
| 1230 |
ld_diff_ct = ld_diff_threshold; |
| 1231 |
} |
| 1232 |
if (pwcp->ldbase_common_geno != difflist_common_geno_inv) { |
| 1233 |
ld_inv_diff_ct = ld_diff_threshold; |
| 1234 |
} |
| 1235 |
if ((ld_diff_ct < ld_diff_threshold) || (ld_inv_diff_ct < ld_diff_threshold)) { |
| 1236 |
const uintptr_t invert_before_compressing = (ld_inv_diff_ct < ld_diff_ct); |
| 1237 |
*vrtype_ptr = 2 + invert_before_compressing; |
| 1238 |
if (invert_before_compressing) { |
| 1239 |
GenovecInvertCopyUnsafe(raregeno, difflist_len, pwcp->genovec_invert_buf); |
| 1240 |
// difflist_common_geno = difflist_common_geno_inv; |
| 1241 |
ld_diff_ct = ld_inv_diff_ct; |
| 1242 |
} |
| 1243 |
return SaveLdTwoListDelta(invert_before_compressing? pwcp->genovec_invert_buf : raregeno, difflist_sample_ids, ld_diff_ct, pwcp); |
| 1244 |
} |
| 1245 |
} else { |
| 1246 |
uintptr_t* __restrict genobuf = pwcp->genovec_invert_buf; |
| 1247 |
PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, sample_ct, difflist_len, genobuf); |
| 1248 |
ZeroTrailingNyps(sample_ct, genobuf); |
| 1249 |
CountLdAndInvertedLdDiffs(pwcp->ldbase_genovec, genobuf, sample_ct, &ld_diff_ct, &ld_inv_diff_ct); |
| 1250 |
if ((ld_diff_ct < ld_diff_threshold) || (ld_inv_diff_ct < ld_diff_threshold)) { |
| 1251 |
const uintptr_t invert_before_compressing = (ld_inv_diff_ct < ld_diff_ct); |
| 1252 |
*vrtype_ptr = 2 + invert_before_compressing; |
| 1253 |
if (invert_before_compressing) { |
| 1254 |
GenovecInvertUnsafe(sample_ct, genobuf); |
| 1255 |
ld_diff_ct = ld_inv_diff_ct; |
| 1256 |
} |
| 1257 |
return SaveLdDifflist(genobuf, pwcp->ldbase_genovec, 0, ld_diff_ct, pwcp); |
| 1258 |
} |
| 1259 |
} |
| 1260 |
} |
| 1261 |
} |
| 1262 |
STD_ARRAY_COPY(genocounts, 4, ldbase_genocounts); |
| 1263 |
if (difflist_viable) { |
| 1264 |
*vrtype_ptr = 4 + difflist_common_geno; |
| 1265 |
memcpy(pwcp->ldbase_raregeno, raregeno, NypCtToByteCt(difflist_len)); |
| 1266 |
memcpy(pwcp->ldbase_difflist_sample_ids, difflist_sample_ids, difflist_len * sizeof(int32_t)); |
| 1267 |
// memcpy(pwcp->ldbase_difflist_sample_ids, difflist_sample_ids, (difflist_len + 1) * sizeof(int32_t)); |
| 1268 |
pwcp->ldbase_common_geno = difflist_common_geno; |
| 1269 |
pwcp->ldbase_difflist_len = difflist_len; |
| 1270 |
return SaveLdInputList(pwcp); |
| 1271 |
} |
| 1272 |
pwcp->ldbase_common_geno = UINT32_MAX; |
| 1273 |
const uint32_t use_onebit = (rare_2_geno_ct_sum < sample_ct / (2 * kPglMaxDifflistLenDivisor)); |
| 1274 |
uintptr_t* genobuf = use_onebit? pwcp->genovec_invert_buf : pwcp->ldbase_genovec; |
| 1275 |
PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, sample_ct, difflist_len, genobuf); |
| 1276 |
ZeroTrailingNyps(sample_ct, genobuf); |
| 1277 |
*vrtype_ptr = use_onebit; |
| 1278 |
if (use_onebit) { |
| 1279 |
uint32_t larger_common_geno = second_most_common_geno; |
| 1280 |
uint32_t smaller_common_geno = difflist_common_geno; |
| 1281 |
if (difflist_common_geno > second_most_common_geno) { |
| 1282 |
larger_common_geno = difflist_common_geno; |
| 1283 |
smaller_common_geno = second_most_common_geno; |
| 1284 |
} |
| 1285 |
const uint32_t vrec_len = SaveOnebit(genobuf, larger_common_geno + (smaller_common_geno * 3), rare_2_geno_ct_sum, pwcp); |
| 1286 |
memcpy(pwcp->ldbase_genovec, genobuf, NypCtToWordCt(sample_ct) * sizeof(uintptr_t)); |
| 1287 |
return vrec_len; |
| 1288 |
} |
| 1289 |
const uint32_t vrec_len = NypCtToByteCt(sample_ct); |
| 1290 |
pwcp->fwrite_bufp = memcpyua(pwcp->fwrite_bufp, genobuf, vrec_len); |
| 1291 |
return vrec_len; |
| 1292 |
} |
| 1293 |
|
| 1294 |
void PwcAppendBiallelicDifflistLimited(const uintptr_t* __restrict raregeno, const uint32_t* __restrict difflist_sample_ids, uint32_t difflist_common_geno, uint32_t difflist_len, PgenWriterCommon* pwcp) { |
| 1295 |
const uint32_t vidx = pwcp->vidx; |
| 1296 |
unsigned char vrtype; |
| 1297 |
const uint32_t vrec_len = PwcAppendBiallelicDifflistLimitedMain(raregeno, difflist_sample_ids, vidx, difflist_common_geno, difflist_len, pwcp, &vrtype); |
| 1298 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 1299 |
pwcp->vidx += 1; |
| 1300 |
SubU32Store(vrec_len, vrec_len_byte_ct, &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct])); |
| 1301 |
if (!pwcp->phase_dosage_gflags) { |
| 1302 |
pwcp->vrtype_buf[vidx / kBitsPerWordD4] |= S_CAST(uintptr_t, vrtype) << (4 * (vidx % kBitsPerWordD4)); |
| 1303 |
} else { |
| 1304 |
DowncastToUc(pwcp->vrtype_buf)[vidx] = vrtype; |
| 1305 |
} |
| 1306 |
} |
| 1307 |
|
| 1308 |
|
| 1309 |
static inline BoolErr CheckedVrecLenIncr(uintptr_t incr, uint32_t* vrec_len_ptr) { |
| 1310 |
// maybe track vrec_left instead of vrec_len... |
| 1311 |
#ifdef __LP64__ |
| 1312 |
const uintptr_t new_vrec_len = *vrec_len_ptr + incr; |
| 1313 |
if (unlikely(new_vrec_len > kPglMaxBytesPerVariant)) { |
| 1314 |
return 1; |
| 1315 |
} |
| 1316 |
*vrec_len_ptr = new_vrec_len; |
| 1317 |
return 0; |
| 1318 |
#else |
| 1319 |
*vrec_len_ptr += incr; |
| 1320 |
return 0; |
| 1321 |
#endif |
| 1322 |
} |
| 1323 |
|
| 1324 |
// ok if delta_bitarr trailing bits set |
| 1325 |
BoolErr PwcAppendDeltalist(const uintptr_t* delta_bitarr, uint32_t deltalist_len, PgenWriterCommon* pwcp, uint32_t* vrec_len_ptr) { |
| 1326 |
assert(deltalist_len); |
| 1327 |
unsigned char* fwrite_bufp = pwcp->fwrite_bufp; |
| 1328 |
unsigned char* fwrite_bufp_start = fwrite_bufp; |
| 1329 |
fwrite_bufp = Vint32Append(deltalist_len, fwrite_bufp); |
| 1330 |
const uint32_t sample_id_byte_ct = BytesToRepresentNzU32(pwcp->sample_ct); |
| 1331 |
const uint32_t group_ct = DivUp(deltalist_len, kPglDifflistGroupSize); |
| 1332 |
unsigned char* group_first_sample_ids_iter = fwrite_bufp; |
| 1333 |
if (unlikely(CheckedVrecLenIncr(S_CAST(uintptr_t, fwrite_bufp - fwrite_bufp_start) + group_ct * sample_id_byte_ct + (group_ct - 1), vrec_len_ptr))) { |
| 1334 |
return 1; |
| 1335 |
} |
| 1336 |
unsigned char* extra_byte_cts_iter = &(fwrite_bufp[group_ct * sample_id_byte_ct]); |
| 1337 |
fwrite_bufp_start = &(extra_byte_cts_iter[group_ct - 1]); |
| 1338 |
fwrite_bufp = fwrite_bufp_start; |
| 1339 |
#ifdef __LP64__ |
| 1340 |
const intptr_t vrec_left = kPglMaxBytesPerVariant - (*vrec_len_ptr); |
| 1341 |
#endif |
| 1342 |
unsigned char* last_group_vint_start = nullptr; |
| 1343 |
uintptr_t last_sample_idx = 0; |
| 1344 |
uintptr_t new_sample_idx_base = 0; |
| 1345 |
uintptr_t delta_bits = delta_bitarr[0]; |
| 1346 |
for (uint32_t deltalist_idx = 0; deltalist_idx != deltalist_len; ++deltalist_idx) { |
| 1347 |
const uintptr_t new_sample_idx = BitIter1(delta_bitarr, &new_sample_idx_base, &delta_bits); |
| 1348 |
if (!(deltalist_idx % kPglDifflistGroupSize)) { |
| 1349 |
SubU32StoreMov(new_sample_idx, sample_id_byte_ct, &group_first_sample_ids_iter); |
| 1350 |
if (deltalist_idx) { |
| 1351 |
*extra_byte_cts_iter++ = S_CAST(uintptr_t, fwrite_bufp - last_group_vint_start) - (kPglDifflistGroupSize - 1); |
| 1352 |
} |
| 1353 |
#ifdef __LP64__ |
| 1354 |
// Note that this inequality goes in the opposite direction from the |
| 1355 |
// usual PtrCheck. |
| 1356 |
if (unlikely(S_CAST(intptr_t, fwrite_bufp - fwrite_bufp_start) > vrec_left)) { |
| 1357 |
return 1; |
| 1358 |
} |
| 1359 |
#endif |
| 1360 |
last_group_vint_start = fwrite_bufp; |
| 1361 |
} else { |
| 1362 |
assert(new_sample_idx >= last_sample_idx + 1); |
| 1363 |
fwrite_bufp = Vint32Append(new_sample_idx - last_sample_idx, fwrite_bufp); |
| 1364 |
} |
| 1365 |
last_sample_idx = new_sample_idx; |
| 1366 |
} |
| 1367 |
pwcp->fwrite_bufp = fwrite_bufp; |
| 1368 |
return CheckedVrecLenIncr(fwrite_bufp - fwrite_bufp_start, vrec_len_ptr); |
| 1369 |
} |
| 1370 |
|
| 1371 |
static_assert(sizeof(AlleleCode) == 1, "PwcAppendMultiallelicMain() needs to be updated."); |
| 1372 |
BoolErr PwcAppendMultiallelicMain(const uintptr_t* __restrict genovec, const uintptr_t* __restrict patch_01_set, const AlleleCode* __restrict patch_01_vals, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, uint32_t allele_ct, uint32_t patch_01_ct, uint32_t patch_10_ct, uint32_t vidx, PgenWriterCommon* pwcp, const uintptr_t** genovec_hets_ptr, uint32_t* het_ct_ptr, unsigned char* vrtype_ptr, uint32_t* vrec_len_ptr) { |
| 1373 |
uint32_t genovec_het_ct; |
| 1374 |
uint32_t genovec_altxy_ct; |
| 1375 |
uint32_t vrec_len = PwcAppendBiallelicGenovecMain(genovec, vidx, pwcp, &genovec_het_ct, &genovec_altxy_ct, vrtype_ptr); |
| 1376 |
if ((!patch_01_ct) && (!patch_10_ct)) { |
| 1377 |
if (genovec_hets_ptr) { |
| 1378 |
*genovec_hets_ptr = genovec; |
| 1379 |
*het_ct_ptr = genovec_het_ct; |
| 1380 |
} |
| 1381 |
*vrec_len_ptr = vrec_len; |
| 1382 |
return 0; |
| 1383 |
} |
| 1384 |
assert(allele_ct > 2); |
| 1385 |
unsigned char* format_byte_ptr = pwcp->fwrite_bufp; |
| 1386 |
++vrec_len; |
| 1387 |
pwcp->fwrite_bufp += 1; |
| 1388 |
unsigned char format_byte = 0; |
| 1389 |
if (!patch_01_ct) { |
| 1390 |
format_byte = 15; |
| 1391 |
} else { |
| 1392 |
// We could use a different bitarray vs. deltalist threshold, since the |
| 1393 |
// usual threshold was chosen under the assumption that |
| 1394 |
// (maximum allowed deltalist index + 1) == bitarray length. |
| 1395 |
// However, the subsetting-speed advantage of the deltalist representation |
| 1396 |
// can be expected to make up for its larger size, so we may actually want |
| 1397 |
// to increase instead of decrease the current 1/9 fraction. For now, I'll |
| 1398 |
// punt on this decision. |
| 1399 |
const uint32_t max_deltalist_entry_ct = genovec_het_ct / kPglMaxDeltalistLenDivisor; |
| 1400 |
if (patch_01_ct < max_deltalist_entry_ct) { |
| 1401 |
// impossible for this to run out of space |
| 1402 |
PwcAppendDeltalist(patch_01_set, patch_01_ct, pwcp, &vrec_len); |
| 1403 |
format_byte = 1; |
| 1404 |
} else { |
| 1405 |
const uint32_t genovec_het_ctb = DivUp(genovec_het_ct, CHAR_BIT); |
| 1406 |
CopyGenomatchSubset(patch_01_set, genovec, kMask5555, 0, genovec_het_ct, pwcp->fwrite_bufp); |
| 1407 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[genovec_het_ctb]); |
| 1408 |
vrec_len += genovec_het_ctb; |
| 1409 |
} |
| 1410 |
if (allele_ct > 3) { |
| 1411 |
if (allele_ct <= 18) { |
| 1412 |
const AlleleCode* patch_01_vals_iter = patch_01_vals; |
| 1413 |
|
| 1414 |
// todo: revisit this logic, we may not always want to write a word at |
| 1415 |
// a time |
| 1416 |
unsigned char* write_fixed_width_start = pwcp->fwrite_bufp; |
| 1417 |
uint32_t written_byte_ct; |
| 1418 |
if (allele_ct == 4) { |
| 1419 |
// 1 bit per entry, clear = ref/alt2, set = ref/alt3 |
| 1420 |
#ifdef USE_SSE2 |
| 1421 |
const uint32_t fullvec_ct = patch_01_ct / kBytesPerVec; |
| 1422 |
if (fullvec_ct) { |
| 1423 |
// parallel-equality-to-3 check, movemask |
| 1424 |
// (+125 or <<7 followed by movemask also works) |
| 1425 |
// todo: better ARM implementation |
| 1426 |
for (uint32_t vec_idx = 0; vec_idx != fullvec_ct; ++vec_idx) { |
| 1427 |
VecUc cur_vec = vecuc_loadu(patch_01_vals_iter); |
| 1428 |
patch_01_vals_iter = &(patch_01_vals_iter[kBytesPerVec]); |
| 1429 |
const Vec8thUint v8ui = vecuc_movemask(VecWToUc(vecw_slli(VecUcToW(cur_vec), 7))); |
| 1430 |
CopyToUnalignedOffsetV8(write_fixed_width_start, &v8ui, vec_idx); |
| 1431 |
} |
| 1432 |
} |
| 1433 |
const uint32_t remainder = patch_01_ct % kBytesPerVec; |
| 1434 |
if (remainder) { |
| 1435 |
const uintptr_t* cur_read_iter = R_CAST(const uintptr_t*, patch_01_vals_iter); |
| 1436 |
unsigned char* write_uc = &(write_fixed_width_start[fullvec_ct * sizeof(Vec8thUint)]); |
| 1437 |
const uint32_t word_ct_m1 = (remainder - 1) / kBytesPerWord; |
| 1438 |
for (uint32_t widx = 0; ; ++widx) { |
| 1439 |
uintptr_t cur_word; |
| 1440 |
if (widx >= word_ct_m1) { |
| 1441 |
if (widx > word_ct_m1) { |
| 1442 |
break; |
| 1443 |
} |
| 1444 |
cur_word = SubwordLoad(cur_read_iter, ModNz(remainder, kBytesPerWord)); |
| 1445 |
} else { |
| 1446 |
cur_word = *cur_read_iter++; |
| 1447 |
} |
| 1448 |
# ifdef USE_AVX2 |
| 1449 |
cur_word = _pext_u64(cur_word, kMask0101); |
| 1450 |
# else |
| 1451 |
// extract the low bit from each byte |
| 1452 |
cur_word = cur_word & kMask0101; |
| 1453 |
cur_word = (cur_word * 0x102040810204080LLU) >> 56; |
| 1454 |
# endif |
| 1455 |
write_uc[widx] = cur_word; |
| 1456 |
} |
| 1457 |
} |
| 1458 |
#else // !USE_SSE2 |
| 1459 |
const uint32_t word_ct_m1 = (patch_01_ct - 1) / kBitsPerWord; |
| 1460 |
uint32_t loop_len = kBitsPerWord; |
| 1461 |
for (uint32_t widx = 0; ; ++widx) { |
| 1462 |
if (widx >= word_ct_m1) { |
| 1463 |
if (widx > word_ct_m1) { |
| 1464 |
break; |
| 1465 |
} |
| 1466 |
loop_len = ModNz(patch_01_ct, kBitsPerWord); |
| 1467 |
} |
| 1468 |
uintptr_t cur_word = 0; |
| 1469 |
for (uint32_t uii = loop_len - 1; ; --uii) { |
| 1470 |
cur_word |= patch_01_vals_iter[uii] & 1; |
| 1471 |
if (!uii) { |
| 1472 |
break; |
| 1473 |
} |
| 1474 |
cur_word <<= 1; |
| 1475 |
} |
| 1476 |
CopyToUnalignedOffsetW(write_fixed_width_start, &cur_word, widx); |
| 1477 |
patch_01_vals_iter = &(patch_01_vals_iter[loop_len]); |
| 1478 |
} |
| 1479 |
#endif // !USE_SSE2 |
| 1480 |
written_byte_ct = DivUp(patch_01_ct, 8); |
| 1481 |
} else if (allele_ct <= 6) { |
| 1482 |
// 2 bits per entry |
| 1483 |
const uint32_t word_ct_m1 = (patch_01_ct - 1) / kBitsPerWordD2; |
| 1484 |
uint32_t loop_len = kBitsPerWordD2; |
| 1485 |
for (uint32_t widx = 0; ; ++widx) { |
| 1486 |
if (widx >= word_ct_m1) { |
| 1487 |
if (widx > word_ct_m1) { |
| 1488 |
break; |
| 1489 |
} |
| 1490 |
loop_len = ModNz(patch_01_ct, kBitsPerWordD2); |
| 1491 |
} |
| 1492 |
uintptr_t cur_word = 0; |
| 1493 |
for (uint32_t uii = loop_len - 1; ; --uii) { |
| 1494 |
// todo: |
| 1495 |
// 1. parallel-subtract (now all bytes are in 0..3) |
| 1496 |
// 2. bitwise or with right-shift-6 |
| 1497 |
// 3. bitwise or with right-shift-12 |
| 1498 |
// 4. _mm{256}_shuffle_epi8() gather from bytes 0, 4, 8, ... |
| 1499 |
// SSE4.2: |
| 1500 |
// 5. store result of _mm_extract_epi32(, 0) |
| 1501 |
// AVX2: |
| 1502 |
// 5. store results of _mm256_extract_epi32(, 0) and (, 4) |
| 1503 |
cur_word |= patch_01_vals_iter[uii] - 2; |
| 1504 |
if (!uii) { |
| 1505 |
break; |
| 1506 |
} |
| 1507 |
cur_word <<= 2; |
| 1508 |
} |
| 1509 |
CopyToUnalignedOffsetW(write_fixed_width_start, &cur_word, widx); |
| 1510 |
patch_01_vals_iter = &(patch_01_vals_iter[loop_len]); |
| 1511 |
} |
| 1512 |
written_byte_ct = DivUp(patch_01_ct, 4); |
| 1513 |
} else { |
| 1514 |
// 4 bits per entry |
| 1515 |
const uint32_t word_ct_m1 = (patch_01_ct - 1) / kBitsPerWordD4; |
| 1516 |
uint32_t loop_len = kBitsPerWordD4; |
| 1517 |
for (uint32_t widx = 0; ; ++widx) { |
| 1518 |
if (widx >= word_ct_m1) { |
| 1519 |
if (widx > word_ct_m1) { |
| 1520 |
break; |
| 1521 |
} |
| 1522 |
loop_len = ModNz(patch_01_ct, kBitsPerWordD4); |
| 1523 |
} |
| 1524 |
uintptr_t cur_word = 0; |
| 1525 |
for (uint32_t uii = loop_len - 1; ; --uii) { |
| 1526 |
// todo: replace this with parallel-subtract, followed by bitwise |
| 1527 |
// or with right-shift-4, followed by _mm{256}_shuffle_epi8() |
| 1528 |
// gather from even bytes, followed by _mm{256}_extract_epi64() |
| 1529 |
// (or _mm256_permute4x64_epi64() followed by |
| 1530 |
// _mm256_extracti128_si256()? test this.) |
| 1531 |
// Or in non-SSE4.2 case, use end of PackWordToHalfword logic. |
| 1532 |
cur_word |= patch_01_vals_iter[uii] - 2; |
| 1533 |
if (!uii) { |
| 1534 |
break; |
| 1535 |
} |
| 1536 |
cur_word <<= 4; |
| 1537 |
} |
| 1538 |
CopyToUnalignedOffsetW(write_fixed_width_start, &cur_word, widx); |
| 1539 |
patch_01_vals_iter = &(patch_01_vals_iter[loop_len]); |
| 1540 |
} |
| 1541 |
written_byte_ct = DivUp(patch_01_ct, 2); |
| 1542 |
} |
| 1543 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[written_byte_ct]); |
| 1544 |
vrec_len += written_byte_ct; |
| 1545 |
} else { |
| 1546 |
// 1 byte per entry |
| 1547 |
// need 2-byte and 3-byte cases here for larger AlleleCode, those also |
| 1548 |
// need to check for vrec_len overflow |
| 1549 |
unsigned char* payload = pwcp->fwrite_bufp; |
| 1550 |
for (uint32_t patch_idx = 0; patch_idx != patch_01_ct; ++patch_idx) { |
| 1551 |
// todo: check if the compiler vectorizes this |
| 1552 |
payload[patch_idx] = patch_01_vals[patch_idx] - 2; |
| 1553 |
} |
| 1554 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[patch_01_ct]); |
| 1555 |
vrec_len += patch_01_ct; |
| 1556 |
} |
| 1557 |
} |
| 1558 |
} |
| 1559 |
if (!patch_10_ct) { |
| 1560 |
format_byte |= 240; |
| 1561 |
if (genovec_hets_ptr) { |
| 1562 |
*genovec_hets_ptr = genovec; |
| 1563 |
*het_ct_ptr = genovec_het_ct; |
| 1564 |
} |
| 1565 |
} else { |
| 1566 |
const uint32_t max_deltalist_entry_ct = genovec_altxy_ct / kPglMaxDeltalistLenDivisor; |
| 1567 |
if (patch_10_ct < max_deltalist_entry_ct) { |
| 1568 |
// can't actually fail for now, but cannot ignore overflow check if |
| 1569 |
// sizeof(AlleleCode) > 1 |
| 1570 |
if (unlikely(PwcAppendDeltalist(patch_10_set, patch_10_ct, pwcp, &vrec_len))) { |
| 1571 |
return 1; |
| 1572 |
} |
| 1573 |
format_byte |= 16; |
| 1574 |
} else { |
| 1575 |
const uintptr_t genovec_altxy_ctb = DivUp(genovec_altxy_ct, CHAR_BIT); |
| 1576 |
if (unlikely(CheckedVrecLenIncr(genovec_altxy_ctb, &vrec_len))) { |
| 1577 |
return 1; |
| 1578 |
} |
| 1579 |
CopyGenomatchSubset(patch_10_set, genovec, kMaskAAAA, 0, genovec_altxy_ct, pwcp->fwrite_bufp); |
| 1580 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[genovec_altxy_ctb]); |
| 1581 |
} |
| 1582 |
if (allele_ct <= 17) { |
| 1583 |
const AlleleCode* patch_10_vals_iter = patch_10_vals; |
| 1584 |
unsigned char* write_fixed_width_start = pwcp->fwrite_bufp; |
| 1585 |
uint32_t bytes_to_write; |
| 1586 |
if (allele_ct == 3) { |
| 1587 |
// 1 bit per entry, clear = alt1/alt2, set = alt2/alt2 |
| 1588 |
bytes_to_write = DivUp(patch_10_ct, 8); |
| 1589 |
if (unlikely(CheckedVrecLenIncr(bytes_to_write, &vrec_len))) { |
| 1590 |
return 1; |
| 1591 |
} |
| 1592 |
#ifdef USE_SSE2 |
| 1593 |
const uint32_t fullvec_ct = patch_10_ct / (kBytesPerVec / 2); |
| 1594 |
if (fullvec_ct) { |
| 1595 |
# if defined(USE_SHUFFLE8) && !defined(USE_AVX2) |
| 1596 |
// SSE4.2: _mm_shuffle_epi8() to gather even bytes, parallel |
| 1597 |
// equality-to-2 check, movemask |
| 1598 |
// (+126 or <<6 followed by movemask also works) |
| 1599 |
// todo: better ARM implementation |
| 1600 |
const VecUc gather_even = vecuc_setr8(0, 2, 4, 6, 8, 10, 12, 14, |
| 1601 |
-1, -1, -1, -1, -1, -1, -1, -1); |
| 1602 |
for (uint32_t vec_idx = 0; vec_idx != fullvec_ct; ++vec_idx) { |
| 1603 |
const VecUc cur_vec = vecuc_loadu(patch_10_vals_iter); |
| 1604 |
patch_10_vals_iter = &(patch_10_vals_iter[kBytesPerVec]); |
| 1605 |
const VecUc even_vec = vecuc_shuffle8(cur_vec, gather_even); |
| 1606 |
write_fixed_width_start[vec_idx] = vecuc_movemask(VecWToUc(vecw_slli(VecUcToW(even_vec), 6))); |
| 1607 |
} |
| 1608 |
# else |
| 1609 |
// SSE2/AVX2: parallel equality-to-{2, 2} check, movemask, |
| 1610 |
// PackWordToHalfword |
| 1611 |
// (uint16_t +126 followed by movemask also works, and avoids an |
| 1612 |
// extra masking step in SSE2 case) |
| 1613 |
// (<<6 doesn't work here) |
| 1614 |
const VecU16 all126 = vecu16_set1(126); |
| 1615 |
for (uint32_t vec_idx = 0; vec_idx != fullvec_ct; ++vec_idx) { |
| 1616 |
VecU16 cur_vec = vecu16_loadu(patch_10_vals_iter); |
| 1617 |
patch_10_vals_iter = &(patch_10_vals_iter[kBytesPerVec]); |
| 1618 |
const uint32_t cur_u32 = vecu16_movemask(cur_vec + all126); |
| 1619 |
const Vec16thUint v16ui = PackVec8thUintTo16th(cur_u32); |
| 1620 |
CopyToUnalignedOffsetV16(write_fixed_width_start, &v16ui, vec_idx); |
| 1621 |
} |
| 1622 |
# endif |
| 1623 |
} |
| 1624 |
const uint32_t remainder = patch_10_ct % (kBytesPerVec / 2); |
| 1625 |
if (remainder) { |
| 1626 |
uint32_t cur_u32 = 0; |
| 1627 |
for (uint32_t uii = remainder - 1; ; --uii) { |
| 1628 |
cur_u32 += patch_10_vals_iter[2 * uii]; |
| 1629 |
if (!uii) { |
| 1630 |
break; |
| 1631 |
} |
| 1632 |
cur_u32 <<= 1; |
| 1633 |
} |
| 1634 |
// this effectively subtracts 1 from each entry |
| 1635 |
const Vec16thUint v16ui = cur_u32 + 1 - (1U << remainder); |
| 1636 |
CopyToUnalignedOffsetV16(write_fixed_width_start, &v16ui, fullvec_ct); |
| 1637 |
patch_10_vals_iter = &(patch_10_vals_iter[remainder * 2]); |
| 1638 |
} |
| 1639 |
#else // !USE_SSE2 |
| 1640 |
const uint32_t word_ct_m1 = (patch_10_ct - 1) / kBitsPerWord; |
| 1641 |
uint32_t loop_len = kBitsPerWord; |
| 1642 |
for (uint32_t widx = 0; ; ++widx) { |
| 1643 |
if (widx >= word_ct_m1) { |
| 1644 |
if (widx > word_ct_m1) { |
| 1645 |
break; |
| 1646 |
} |
| 1647 |
loop_len = ModNz(patch_10_ct, kBitsPerWord); |
| 1648 |
} |
| 1649 |
uintptr_t cur_word = 0; |
| 1650 |
for (uint32_t uii = loop_len - 1; ; --uii) { |
| 1651 |
cur_word |= patch_10_vals_iter[2 * uii] - 1; |
| 1652 |
if (!uii) { |
| 1653 |
break; |
| 1654 |
} |
| 1655 |
cur_word <<= 1; |
| 1656 |
} |
| 1657 |
CopyToUnalignedOffsetW(write_fixed_width_start, &cur_word, widx); |
| 1658 |
patch_10_vals_iter = &(patch_10_vals_iter[loop_len * 2]); |
| 1659 |
} |
| 1660 |
#endif // !USE_SSE2 |
| 1661 |
} else if (allele_ct <= 5) { |
| 1662 |
// 2 bits per half-entry |
| 1663 |
bytes_to_write = DivUp(patch_10_ct, 2); |
| 1664 |
if (unlikely(CheckedVrecLenIncr(bytes_to_write, &vrec_len))) { |
| 1665 |
return 1; |
| 1666 |
} |
| 1667 |
// this may be worse than simple loop, check this later |
| 1668 |
const uint32_t word_ct_m1 = (patch_10_ct - 1) / kBitsPerWordD4; |
| 1669 |
uint32_t loop_len = kBitsPerWordD2; |
| 1670 |
for (uint32_t widx = 0; ; ++widx) { |
| 1671 |
if (widx >= word_ct_m1) { |
| 1672 |
if (widx > word_ct_m1) { |
| 1673 |
break; |
| 1674 |
} |
| 1675 |
loop_len = 2 * ModNz(patch_10_ct, kBitsPerWordD4); |
| 1676 |
} |
| 1677 |
uintptr_t cur_word = 0; |
| 1678 |
for (uint32_t uii = loop_len - 1; ; --uii) { |
| 1679 |
// todo: same as 2-bit patch_01 case, except starting with |
| 1680 |
// parallel-subtract 1 instead of 2 |
| 1681 |
cur_word |= patch_10_vals_iter[uii] - 1; |
| 1682 |
if (!uii) { |
| 1683 |
break; |
| 1684 |
} |
| 1685 |
cur_word <<= 2; |
| 1686 |
} |
| 1687 |
CopyToUnalignedOffsetW(write_fixed_width_start, &cur_word, widx); |
| 1688 |
patch_10_vals_iter = &(patch_10_vals_iter[loop_len]); |
| 1689 |
} |
| 1690 |
} else { |
| 1691 |
// 4 bits per half-entry |
| 1692 |
bytes_to_write = patch_10_ct; |
| 1693 |
if (unlikely(CheckedVrecLenIncr(bytes_to_write, &vrec_len))) { |
| 1694 |
return 1; |
| 1695 |
} |
| 1696 |
const uint32_t word_ct_m1 = (patch_10_ct - 1) / kBytesPerWord; |
| 1697 |
uint32_t loop_len = kBitsPerWordD4; |
| 1698 |
for (uint32_t widx = 0; ; ++widx) { |
| 1699 |
if (widx >= word_ct_m1) { |
| 1700 |
if (widx > word_ct_m1) { |
| 1701 |
break; |
| 1702 |
} |
| 1703 |
loop_len = 2 * ModNz(patch_10_ct, kBytesPerWord); |
| 1704 |
} |
| 1705 |
uintptr_t cur_word = 0; |
| 1706 |
for (uint32_t uii = loop_len - 1; ; --uii) { |
| 1707 |
cur_word |= patch_10_vals_iter[uii] - 1; |
| 1708 |
if (!uii) { |
| 1709 |
break; |
| 1710 |
} |
| 1711 |
cur_word <<= 4; |
| 1712 |
} |
| 1713 |
CopyToUnalignedOffsetW(write_fixed_width_start, &cur_word, widx); |
| 1714 |
patch_10_vals_iter = &(patch_10_vals_iter[loop_len]); |
| 1715 |
} |
| 1716 |
} |
| 1717 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[bytes_to_write]); |
| 1718 |
} else { |
| 1719 |
// 1 byte per half-entry |
| 1720 |
// need 2- and 3-byte cases for larger AlleleCode |
| 1721 |
unsigned char* payload = pwcp->fwrite_bufp; |
| 1722 |
if (unlikely(CheckedVrecLenIncr(patch_10_ct * (2 * k1LU), &vrec_len))) { |
| 1723 |
return 1; |
| 1724 |
} |
| 1725 |
const uint32_t patch_10_ct_x2 = patch_10_ct * 2; |
| 1726 |
// hopefully the compiler automatically vectorizes this when |
| 1727 |
// sizeof(AlleleCode) == 1 |
| 1728 |
for (uint32_t uii = 0; uii != patch_10_ct_x2; ++uii) { |
| 1729 |
payload[uii] = patch_10_vals[uii] - 1; |
| 1730 |
} |
| 1731 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[patch_10_ct * 2]); |
| 1732 |
} |
| 1733 |
if (genovec_hets_ptr) { |
| 1734 |
// This is somewhat redundant with the earlier steps, but let's get |
| 1735 |
// everything working before doing more optimization. |
| 1736 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 1737 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 1738 |
const Halfword* patch_10_set_alias = DowncastKWToHW(patch_10_set); |
| 1739 |
const AlleleCode* patch_10_vals_iter = patch_10_vals; |
| 1740 |
const AlleleCode* patch_10_vals_end = &(patch_10_vals[patch_10_ct * 2]); |
| 1741 |
uintptr_t* genovec_hets = nullptr; |
| 1742 |
uint32_t het_ct = genovec_het_ct; |
| 1743 |
// todo: try inverting this loop, at least in 64-bit case. perform |
| 1744 |
// movemask-based scan for heterozygous patch_10_vals entries, then |
| 1745 |
// advance widx/detect_10 as needed. |
| 1746 |
for (uint32_t widx = 0; widx != sample_ctl2; ++widx) { |
| 1747 |
uint32_t patch_10_hw = patch_10_set_alias[widx]; |
| 1748 |
if (patch_10_hw) { |
| 1749 |
do { |
| 1750 |
const AlleleCode val1 = *patch_10_vals_iter++; |
| 1751 |
const AlleleCode val2 = *patch_10_vals_iter++; |
| 1752 |
const uintptr_t lowbit = patch_10_hw & (-patch_10_hw); |
| 1753 |
if (val1 != val2) { |
| 1754 |
if (!genovec_hets) { |
| 1755 |
genovec_hets = pwcp->genovec_hets_buf; |
| 1756 |
memcpy(genovec_hets, genovec, sample_ctl2 * sizeof(intptr_t)); |
| 1757 |
} |
| 1758 |
// clear high bit, set low bit |
| 1759 |
genovec_hets[widx] ^= lowbit * lowbit * 3; |
| 1760 |
++het_ct; |
| 1761 |
} |
| 1762 |
patch_10_hw ^= lowbit; |
| 1763 |
} while (patch_10_hw); |
| 1764 |
if (patch_10_vals_iter == patch_10_vals_end) { |
| 1765 |
break; |
| 1766 |
} |
| 1767 |
} |
| 1768 |
} |
| 1769 |
*het_ct_ptr = het_ct; |
| 1770 |
if (genovec_hets) { |
| 1771 |
*genovec_hets_ptr = genovec_hets; |
| 1772 |
} else { |
| 1773 |
*genovec_hets_ptr = genovec; |
| 1774 |
} |
| 1775 |
} |
| 1776 |
} |
| 1777 |
*format_byte_ptr = format_byte; |
| 1778 |
*vrtype_ptr |= 8; |
| 1779 |
*vrec_len_ptr = vrec_len; |
| 1780 |
return 0; |
| 1781 |
} |
| 1782 |
|
| 1783 |
BoolErr PwcAppendMultiallelicSparse(const uintptr_t* __restrict genovec, const uintptr_t* __restrict patch_01_set, const AlleleCode* __restrict patch_01_vals, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, uint32_t allele_ct, uint32_t patch_01_ct, uint32_t patch_10_ct, PgenWriterCommon* pwcp) { |
| 1784 |
const uint32_t vidx = pwcp->vidx; |
| 1785 |
unsigned char vrtype; |
| 1786 |
uint32_t vrec_len; |
| 1787 |
if (unlikely(PwcAppendMultiallelicMain(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, allele_ct, patch_01_ct, patch_10_ct, vidx, pwcp, nullptr, nullptr, &vrtype, &vrec_len))) { |
| 1788 |
return 1; |
| 1789 |
} |
| 1790 |
pwcp->vidx += 1; |
| 1791 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 1792 |
SubU32Store(vrec_len, vrec_len_byte_ct, &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct])); |
| 1793 |
if (!pwcp->phase_dosage_gflags) { |
| 1794 |
pwcp->vrtype_buf[vidx / kBitsPerWordD4] |= S_CAST(uintptr_t, vrtype) << (4 * (vidx % kBitsPerWordD4)); |
| 1795 |
} else { |
| 1796 |
DowncastToUc(pwcp->vrtype_buf)[vidx] = vrtype; |
| 1797 |
} |
| 1798 |
return 0; |
| 1799 |
} |
| 1800 |
|
| 1801 |
void PglMultiallelicDenseToSparse(const AlleleCode* __restrict wide_codes, uint32_t sample_ct, uintptr_t* __restrict genoarr, uintptr_t* __restrict patch_01_set, AlleleCode* __restrict patch_01_vals, uintptr_t* __restrict patch_10_set, AlleleCode* __restrict patch_10_vals, uint32_t* __restrict patch_01_ct_ptr, uint32_t* __restrict patch_10_ct_ptr) { |
| 1802 |
const uint32_t word_ct_m1 = (sample_ct - 1) / kBitsPerWordD2; |
| 1803 |
const AlleleCode* wide_codes_iter = wide_codes; |
| 1804 |
Halfword* patch_01_set_alias = DowncastWToHW(patch_01_set); |
| 1805 |
Halfword* patch_10_set_alias = DowncastWToHW(patch_10_set); |
| 1806 |
AlleleCode* patch_01_vals_iter = patch_01_vals; |
| 1807 |
AlleleCode* patch_10_vals_iter = patch_10_vals; |
| 1808 |
uint32_t loop_len = kBitsPerWordD2; |
| 1809 |
for (uint32_t widx = 0; ; ++widx) { |
| 1810 |
if (widx >= word_ct_m1) { |
| 1811 |
if (widx > word_ct_m1) { |
| 1812 |
*patch_01_ct_ptr = patch_01_vals_iter - patch_01_vals; |
| 1813 |
*patch_10_ct_ptr = S_CAST(uintptr_t, patch_10_vals_iter - patch_10_vals) / 2; |
| 1814 |
return; |
| 1815 |
} |
| 1816 |
loop_len = ModNz(sample_ct, kBitsPerWordD2); |
| 1817 |
} |
| 1818 |
uintptr_t geno_word = 0; |
| 1819 |
uint32_t patch_01_hw = 0; |
| 1820 |
uint32_t patch_10_hw = 0; |
| 1821 |
// ascending loop may be worse than descending here |
| 1822 |
for (uint32_t sample_idx_lowbits = 0; sample_idx_lowbits != loop_len; ++sample_idx_lowbits) { |
| 1823 |
// todo: try making this movemask-based in 64-bit case |
| 1824 |
// parallel checks for equality-to-255, equality-to-0, inequality-to-1 |
| 1825 |
// rarealts are inequality-to-1 and (not 0 or 255); can use ctzu32() and |
| 1826 |
// &= x - 1 to iterate |
| 1827 |
// hom-ref iff double-equality to 0 |
| 1828 |
// het-ref iff low equality-to-0 bit set, high clear |
| 1829 |
// missing iff equality-to-255 (better be double) |
| 1830 |
// altx-alty otherwise |
| 1831 |
const AlleleCode first_code = *wide_codes_iter++; |
| 1832 |
const AlleleCode second_code = *wide_codes_iter++; |
| 1833 |
uintptr_t cur_geno; |
| 1834 |
if (first_code) { |
| 1835 |
if (first_code == kMissingAlleleCode) { |
| 1836 |
cur_geno = 3; |
| 1837 |
} else { |
| 1838 |
cur_geno = 2; |
| 1839 |
if (second_code > 1) { |
| 1840 |
patch_10_hw |= 1U << sample_idx_lowbits; |
| 1841 |
*patch_10_vals_iter++ = first_code; |
| 1842 |
*patch_10_vals_iter++ = second_code; |
| 1843 |
} |
| 1844 |
} |
| 1845 |
} else if (!second_code) { |
| 1846 |
continue; |
| 1847 |
} else { |
| 1848 |
cur_geno = 1; |
| 1849 |
if (second_code > 1) { |
| 1850 |
patch_01_hw |= 1U << sample_idx_lowbits; |
| 1851 |
*patch_01_vals_iter++ = second_code; |
| 1852 |
} |
| 1853 |
} |
| 1854 |
geno_word |= cur_geno << (2 * sample_idx_lowbits); |
| 1855 |
} |
| 1856 |
genoarr[widx] = geno_word; |
| 1857 |
patch_01_set_alias[widx] = patch_01_hw; |
| 1858 |
patch_10_set_alias[widx] = patch_10_hw; |
| 1859 |
} |
| 1860 |
} |
| 1861 |
|
| 1862 |
static_assert(sizeof(AlleleCode) == 1, "PglMultiallelicSparseToDense() needs to be updated."); |
| 1863 |
void PglMultiallelicSparseToDense(const uintptr_t* __restrict genoarr, const uintptr_t* __restrict patch_01_set, const AlleleCode* __restrict patch_01_vals, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, const AlleleCode* __restrict remap, uint32_t sample_ct, uint32_t patch_01_ct, uint32_t patch_10_ct, uintptr_t* __restrict flipped, AlleleCode* __restrict wide_codes) { |
| 1864 |
if (flipped) { |
| 1865 |
ZeroWArr(BitCtToWordCt(sample_ct), flipped); |
| 1866 |
} |
| 1867 |
if ((!remap) || ((!remap[0]) && (remap[1] == 1))) { |
| 1868 |
GenoarrLookup256x2bx4(genoarr, kHcToAlleleCodes, sample_ct, wide_codes); |
| 1869 |
if (!remap) { |
| 1870 |
if (patch_01_ct) { |
| 1871 |
uintptr_t sample_idx_base = 0; |
| 1872 |
uintptr_t cur_bits = patch_01_set[0]; |
| 1873 |
AlleleCode* wide_codes1 = &(wide_codes[1]); |
| 1874 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 1875 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits); |
| 1876 |
wide_codes1[2 * sample_idx] = patch_01_vals[uii]; |
| 1877 |
} |
| 1878 |
} |
| 1879 |
if (patch_10_ct) { |
| 1880 |
uintptr_t sample_idx_base = 0; |
| 1881 |
uintptr_t cur_bits = patch_10_set[0]; |
| 1882 |
const DoubleAlleleCode* patch_10_vals_alias = R_CAST(const DoubleAlleleCode*, patch_10_vals); |
| 1883 |
DoubleAlleleCode* wide_codes_alias = R_CAST(DoubleAlleleCode*, wide_codes); |
| 1884 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 1885 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &cur_bits); |
| 1886 |
wide_codes_alias[sample_idx] = patch_10_vals_alias[uii]; |
| 1887 |
} |
| 1888 |
} |
| 1889 |
return; |
| 1890 |
} |
| 1891 |
} else { |
| 1892 |
// 0 -> (remap[0], remap[0]) |
| 1893 |
// 1 -> (remap[0], remap[1]) |
| 1894 |
// 2 -> (remap[1], remap[1]) |
| 1895 |
// 3 -> (255, 255) |
| 1896 |
// 256x4 lookup table usually too expensive to reinitialize for every |
| 1897 |
// single variant. 16x2 should be a good compromise? |
| 1898 |
// todo: try Expand1bitTo8 strategy in SSE4.2+ case, see if that's fast |
| 1899 |
// enough to remove 0/1 special case |
| 1900 |
const uint32_t remap0 = remap[0]; |
| 1901 |
const uint32_t remap1 = remap[1]; |
| 1902 |
uint32_t table4[4]; |
| 1903 |
table4[0] = remap0 * 257; |
| 1904 |
table4[1] = remap0 + remap1 * 256; |
| 1905 |
table4[2] = remap1 * 257; |
| 1906 |
table4[3] = 0xffff; |
| 1907 |
if (remap1 < remap0) { |
| 1908 |
table4[1] = remap1 + remap0 * 256; |
| 1909 |
if (flipped) { |
| 1910 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 1911 |
PackWordsToHalfwordsInvmatch(genoarr, kMaskAAAA, sample_ctl2, flipped); |
| 1912 |
} |
| 1913 |
} |
| 1914 |
// could have an InitLookup16x2bx2 function for this |
| 1915 |
uint32_t table16[16]; |
| 1916 |
for (uint32_t uii = 0; uii != 4; ++uii) { |
| 1917 |
const uint32_t high_bits = table4[uii] << 16; |
| 1918 |
uint32_t* table_row = &(table16[uii * 4]); |
| 1919 |
for (uint32_t ujj = 0; ujj != 4; ++ujj) { |
| 1920 |
table_row[ujj] = high_bits | table4[ujj]; |
| 1921 |
} |
| 1922 |
} |
| 1923 |
const uint32_t sample_ctd4 = sample_ct / 4; |
| 1924 |
const unsigned char* genoarr_alias = DowncastKToUc(genoarr); |
| 1925 |
uint32_t* wide_codes_alias_iter = R_CAST(uint32_t*, wide_codes); |
| 1926 |
for (uint32_t byte_idx = 0; byte_idx != sample_ctd4; ++byte_idx) { |
| 1927 |
const uint32_t geno_byte = genoarr_alias[byte_idx]; |
| 1928 |
*wide_codes_alias_iter++ = table16[geno_byte & 15]; |
| 1929 |
*wide_codes_alias_iter++ = table16[geno_byte >> 4]; |
| 1930 |
} |
| 1931 |
const uint32_t remainder = sample_ct % 4; |
| 1932 |
if (remainder) { |
| 1933 |
uint32_t geno_byte = genoarr_alias[sample_ctd4]; |
| 1934 |
if (remainder & 2) { |
| 1935 |
*wide_codes_alias_iter++ = table16[geno_byte & 15]; |
| 1936 |
geno_byte = geno_byte >> 4; |
| 1937 |
} |
| 1938 |
if (remainder & 1) { |
| 1939 |
uint16_t* last_code_pair_ptr = DowncastU32ToU16(wide_codes_alias_iter); |
| 1940 |
// guess it's easy enough to defend against dirty trailing bits for now |
| 1941 |
*last_code_pair_ptr = table4[geno_byte & 3]; |
| 1942 |
} |
| 1943 |
} |
| 1944 |
} |
| 1945 |
if (patch_01_vals) { |
| 1946 |
uintptr_t sample_idx_base = 0; |
| 1947 |
uintptr_t cur_bits = patch_01_set[0]; |
| 1948 |
const AlleleCode remap0 = remap[0]; |
| 1949 |
const AlleleCode remap1 = remap[1]; |
| 1950 |
if ((!remap0) || ((!flipped) && (remap0 == 1) && (!remap1))) { |
| 1951 |
// no flips possible |
| 1952 |
AlleleCode* wide_codes1 = &(wide_codes[1]); |
| 1953 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 1954 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits); |
| 1955 |
wide_codes1[2 * sample_idx] = remap[patch_01_vals[uii]]; |
| 1956 |
} |
| 1957 |
} else if (!flipped) { |
| 1958 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 1959 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits); |
| 1960 |
const AlleleCode ac = remap[patch_01_vals[uii]]; |
| 1961 |
if (ac > remap0) { |
| 1962 |
// bugfix (4 Jul 2024): cannot assume wide_codes[2 * sample_idx] == |
| 1963 |
// remap0. It's remap1 when remap1 < remap0. |
| 1964 |
wide_codes[2 * sample_idx] = remap0; |
| 1965 |
wide_codes[2 * sample_idx + 1] = ac; |
| 1966 |
} else { |
| 1967 |
wide_codes[2 * sample_idx] = ac; |
| 1968 |
wide_codes[2 * sample_idx + 1] = remap0; |
| 1969 |
} |
| 1970 |
} |
| 1971 |
} else if (remap1 >= remap0) { |
| 1972 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 1973 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits); |
| 1974 |
const AlleleCode ac = remap[patch_01_vals[uii]]; |
| 1975 |
if (ac > remap0) { |
| 1976 |
wide_codes[2 * sample_idx + 1] = ac; |
| 1977 |
} else { |
| 1978 |
wide_codes[2 * sample_idx] = ac; |
| 1979 |
wide_codes[2 * sample_idx + 1] = remap0; |
| 1980 |
SetBit(sample_idx, flipped); |
| 1981 |
} |
| 1982 |
} |
| 1983 |
} else { |
| 1984 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 1985 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits); |
| 1986 |
const AlleleCode ac = remap[patch_01_vals[uii]]; |
| 1987 |
if (ac > remap0) { |
| 1988 |
wide_codes[2 * sample_idx] = remap0; |
| 1989 |
wide_codes[2 * sample_idx + 1] = ac; |
| 1990 |
ClearBit(sample_idx, flipped); |
| 1991 |
} else { |
| 1992 |
wide_codes[2 * sample_idx] = ac; |
| 1993 |
wide_codes[2 * sample_idx + 1] = remap0; |
| 1994 |
} |
| 1995 |
} |
| 1996 |
} |
| 1997 |
} |
| 1998 |
if (patch_10_ct) { |
| 1999 |
uintptr_t sample_idx_base = 0; |
| 2000 |
uintptr_t cur_bits = patch_10_set[0]; |
| 2001 |
if (!flipped) { |
| 2002 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 2003 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &cur_bits); |
| 2004 |
const AlleleCode ac0 = remap[patch_10_vals[2 * uii]]; |
| 2005 |
const AlleleCode ac1 = remap[patch_10_vals[2 * uii + 1]]; |
| 2006 |
if (ac0 <= ac1) { |
| 2007 |
wide_codes[2 * sample_idx] = ac0; |
| 2008 |
wide_codes[2 * sample_idx + 1] = ac1; |
| 2009 |
} else { |
| 2010 |
wide_codes[2 * sample_idx] = ac1; |
| 2011 |
wide_codes[2 * sample_idx + 1] = ac0; |
| 2012 |
} |
| 2013 |
} |
| 2014 |
} else { |
| 2015 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 2016 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &cur_bits); |
| 2017 |
const AlleleCode ac0 = remap[patch_10_vals[2 * uii]]; |
| 2018 |
const AlleleCode ac1 = remap[patch_10_vals[2 * uii + 1]]; |
| 2019 |
if (ac0 <= ac1) { |
| 2020 |
wide_codes[2 * sample_idx] = ac0; |
| 2021 |
wide_codes[2 * sample_idx + 1] = ac1; |
| 2022 |
} else { |
| 2023 |
wide_codes[2 * sample_idx] = ac1; |
| 2024 |
wide_codes[2 * sample_idx + 1] = ac0; |
| 2025 |
SetBit(sample_idx, flipped); |
| 2026 |
} |
| 2027 |
} |
| 2028 |
} |
| 2029 |
} |
| 2030 |
} |
| 2031 |
|
| 2032 |
// tolerates extraneous phaseinfo bits |
| 2033 |
BoolErr AppendHphase(const uintptr_t* __restrict genoarr_hets, const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict phaseinfo, uint32_t het_ct, uint32_t phasepresent_ct, PgenWriterCommon* pwcp, unsigned char* vrtype_ptr, uint32_t* vrec_len_ptr) { |
| 2034 |
assert(phasepresent_ct); |
| 2035 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 2036 |
*vrtype_ptr += 16; |
| 2037 |
const uint32_t het_ctp1_8 = 1 + (het_ct / CHAR_BIT); |
| 2038 |
unsigned char* fwrite_bufp_iter = pwcp->fwrite_bufp; |
| 2039 |
uintptr_t phaseinfo_write_word = 0; |
| 2040 |
uint32_t phaseinfo_write_idx_lowbits; |
| 2041 |
if (het_ct == phasepresent_ct) { |
| 2042 |
// no need to write phasepresent; just write phaseinfo directly to output |
| 2043 |
// buffer |
| 2044 |
if (unlikely(CheckedVrecLenIncr(het_ctp1_8, vrec_len_ptr))) { |
| 2045 |
return 1; |
| 2046 |
} |
| 2047 |
CopyGenomatchSubset(phaseinfo, genoarr_hets, kMask5555, 1, het_ct, pwcp->fwrite_bufp); |
| 2048 |
fwrite_bufp_iter = &(pwcp->fwrite_bufp[het_ctp1_8]); |
| 2049 |
} else { |
| 2050 |
// this is a minor variant of ExpandThenSubsetBytearr() |
| 2051 |
if (unlikely(CheckedVrecLenIncr(het_ctp1_8 + DivUp(phasepresent_ct, 8), vrec_len_ptr))) { |
| 2052 |
return 1; |
| 2053 |
} |
| 2054 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 2055 |
uintptr_t* phaseinfo_tmp = pwcp->genovec_invert_buf; |
| 2056 |
uintptr_t* phaseinfo_tmp_iter = phaseinfo_tmp; |
| 2057 |
uint32_t phasepresent_write_idx_lowbits = 1; |
| 2058 |
phaseinfo_write_idx_lowbits = 0; |
| 2059 |
uintptr_t phasepresent_write_word = 1; // first bit set |
| 2060 |
for (uint32_t widx = 0; widx != sample_ctl2; ++widx) { |
| 2061 |
const uintptr_t geno_word = genoarr_hets[widx]; |
| 2062 |
uintptr_t geno_hets = Word01(geno_word); |
| 2063 |
if (geno_hets) { |
| 2064 |
const uint32_t phasepresent_halfword = DowncastKWToHW(phasepresent)[widx]; |
| 2065 |
if (phasepresent_halfword) { |
| 2066 |
const uint32_t phaseinfo_halfword = DowncastKWToHW(phaseinfo)[widx]; |
| 2067 |
do { |
| 2068 |
const uint32_t sample_idx_lowbits = ctzw(geno_hets) / 2; |
| 2069 |
if ((phasepresent_halfword >> sample_idx_lowbits) & 1) { |
| 2070 |
phasepresent_write_word |= k1LU << phasepresent_write_idx_lowbits; |
| 2071 |
phaseinfo_write_word |= S_CAST(uintptr_t, (phaseinfo_halfword >> sample_idx_lowbits) & k1LU) << phaseinfo_write_idx_lowbits; |
| 2072 |
if (++phaseinfo_write_idx_lowbits == kBitsPerWord) { |
| 2073 |
*phaseinfo_tmp_iter++ = phaseinfo_write_word; |
| 2074 |
phaseinfo_write_word = 0; |
| 2075 |
phaseinfo_write_idx_lowbits = 0; |
| 2076 |
} |
| 2077 |
} |
| 2078 |
if (++phasepresent_write_idx_lowbits == kBitsPerWord) { |
| 2079 |
AppendW(phasepresent_write_word, &fwrite_bufp_iter); |
| 2080 |
phasepresent_write_word = 0; |
| 2081 |
phasepresent_write_idx_lowbits = 0; |
| 2082 |
} |
| 2083 |
geno_hets &= geno_hets - 1; |
| 2084 |
} while (geno_hets); |
| 2085 |
} else { |
| 2086 |
phasepresent_write_idx_lowbits += PopcountWord(geno_hets); |
| 2087 |
if (phasepresent_write_idx_lowbits >= kBitsPerWord) { |
| 2088 |
AppendW(phasepresent_write_word, &fwrite_bufp_iter); |
| 2089 |
phasepresent_write_word = 0; |
| 2090 |
phasepresent_write_idx_lowbits -= kBitsPerWord; |
| 2091 |
} |
| 2092 |
} |
| 2093 |
} |
| 2094 |
} |
| 2095 |
if (phasepresent_write_idx_lowbits) { |
| 2096 |
const uint32_t cur_byte_ct = DivUp(phasepresent_write_idx_lowbits, CHAR_BIT); |
| 2097 |
// er, safe to write the entire word... |
| 2098 |
SubwordStoreMov(phasepresent_write_word, cur_byte_ct, &fwrite_bufp_iter); |
| 2099 |
} |
| 2100 |
fwrite_bufp_iter = memcpyua(fwrite_bufp_iter, phaseinfo_tmp, sizeof(intptr_t) * (phaseinfo_tmp_iter - phaseinfo_tmp)); |
| 2101 |
if (phaseinfo_write_idx_lowbits) { |
| 2102 |
const uint32_t cur_byte_ct = DivUp(phaseinfo_write_idx_lowbits, CHAR_BIT); |
| 2103 |
SubwordStoreMov(phaseinfo_write_word, cur_byte_ct, &fwrite_bufp_iter); |
| 2104 |
} |
| 2105 |
assert(S_CAST(uintptr_t, fwrite_bufp_iter - pwcp->fwrite_bufp) == het_ctp1_8 + DivUp(phasepresent_ct, 8)); |
| 2106 |
} |
| 2107 |
pwcp->fwrite_bufp = fwrite_bufp_iter; |
| 2108 |
return 0; |
| 2109 |
} |
| 2110 |
|
| 2111 |
void PwcAppendBiallelicGenovecHphase(const uintptr_t* __restrict genovec, const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict phaseinfo, PgenWriterCommon* pwcp) { |
| 2112 |
// assumes phase_dosage_gflags is nonzero |
| 2113 |
const uint32_t vidx = pwcp->vidx; |
| 2114 |
unsigned char* vrtype_dest = &(DowncastToUc(pwcp->vrtype_buf)[vidx]); |
| 2115 |
uint32_t het_ct; |
| 2116 |
uint32_t vrec_len = PwcAppendBiallelicGenovecMain(genovec, vidx, pwcp, &het_ct, nullptr, vrtype_dest); |
| 2117 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 2118 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 2119 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 2120 |
pwcp->vidx += 1; |
| 2121 |
unsigned char* vrec_len_dest = &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct]); |
| 2122 |
const uint32_t phasepresent_ct = phasepresent? PopcountWords(phasepresent, sample_ctl) : het_ct; |
| 2123 |
if (phasepresent_ct) { |
| 2124 |
AppendHphase(genovec, phasepresent, phaseinfo, het_ct, phasepresent_ct, pwcp, vrtype_dest, &vrec_len); |
| 2125 |
} |
| 2126 |
SubU32Store(vrec_len, vrec_len_byte_ct, vrec_len_dest); |
| 2127 |
} |
| 2128 |
|
| 2129 |
BoolErr PwcAppendMultiallelicGenovecHphase(const uintptr_t* __restrict genovec, const uintptr_t* __restrict patch_01_set, const AlleleCode* __restrict patch_01_vals, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict phaseinfo, uint32_t allele_ct, uint32_t patch_01_ct, uint32_t patch_10_ct, PgenWriterCommon* pwcp) { |
| 2130 |
const uint32_t vidx = pwcp->vidx; |
| 2131 |
const uintptr_t* genovec_hets; |
| 2132 |
unsigned char vrtype; |
| 2133 |
uint32_t het_ct; |
| 2134 |
uint32_t vrec_len; |
| 2135 |
if (unlikely(PwcAppendMultiallelicMain(genovec, patch_01_set, patch_01_vals, patch_10_set, patch_10_vals, allele_ct, patch_01_ct, patch_10_ct, vidx, pwcp, &genovec_hets, &het_ct, &vrtype, &vrec_len))) { |
| 2136 |
return 1; |
| 2137 |
} |
| 2138 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 2139 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 2140 |
const uint32_t phasepresent_ct = phasepresent? PopcountWords(phasepresent, sample_ctl) : het_ct; |
| 2141 |
unsigned char* vrtype_dest = &(DowncastToUc(pwcp->vrtype_buf)[vidx]); |
| 2142 |
*vrtype_dest = vrtype; |
| 2143 |
if (phasepresent_ct) { |
| 2144 |
if (unlikely(AppendHphase(genovec_hets, phasepresent, phaseinfo, het_ct, phasepresent_ct, pwcp, vrtype_dest, &vrec_len))) { |
| 2145 |
return 1; |
| 2146 |
} |
| 2147 |
} |
| 2148 |
pwcp->vidx += 1; |
| 2149 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 2150 |
SubU32Store(vrec_len, vrec_len_byte_ct, &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct])); |
| 2151 |
return 0; |
| 2152 |
} |
| 2153 |
|
| 2154 |
// ok if dosage_present trailing bits set |
| 2155 |
BoolErr AppendDosage16(const uintptr_t* __restrict dosage_present, const uint16_t* dosage_main, uint32_t dosage_ct, uint32_t dphase_ct, PgenWriterCommon* pwcp, unsigned char* vrtype_ptr, uint32_t* vrec_len_ptr) { |
| 2156 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 2157 |
const uint32_t max_deltalist_entry_ct = sample_ct / kPglMaxDeltalistLenDivisor; |
| 2158 |
if (dosage_ct < max_deltalist_entry_ct) { |
| 2159 |
// case 1: store dosage IDs as deltalist. |
| 2160 |
if (unlikely(PwcAppendDeltalist(dosage_present, dosage_ct, pwcp, vrec_len_ptr))) { |
| 2161 |
return 1; |
| 2162 |
} |
| 2163 |
*vrtype_ptr += 0x20; |
| 2164 |
} else if ((dosage_ct == sample_ct) && ((!dphase_ct) || (dphase_ct == sample_ct))) { |
| 2165 |
// case 2: fixed-width, no need to store dosage IDs at all. |
| 2166 |
// dosage_main permitted to have 65535 = missing |
| 2167 |
// bugfix (9 Dec 2018): since this forces fixed-width dosage-phase storage, |
| 2168 |
// also require dphase_ct == 0 or dphase_ct == sample_ct. |
| 2169 |
*vrtype_ptr += 0x40; |
| 2170 |
} else { |
| 2171 |
// case 3: save dosage_present bitarray directly. |
| 2172 |
const uint32_t sample_ctb = DivUp(sample_ct, CHAR_BIT); |
| 2173 |
if (unlikely(CheckedVrecLenIncr(sample_ctb, vrec_len_ptr))) { |
| 2174 |
return 1; |
| 2175 |
} |
| 2176 |
pwcp->fwrite_bufp = memcpyua(pwcp->fwrite_bufp, dosage_present, sample_ctb); |
| 2177 |
*vrtype_ptr += 0x60; |
| 2178 |
} |
| 2179 |
if (unlikely(CheckedVrecLenIncr(dosage_ct * sizeof(int16_t), vrec_len_ptr))) { |
| 2180 |
return 1; |
| 2181 |
} |
| 2182 |
pwcp->fwrite_bufp = memcpyua(pwcp->fwrite_bufp, dosage_main, dosage_ct * sizeof(int16_t)); |
| 2183 |
return 0; |
| 2184 |
} |
| 2185 |
|
| 2186 |
// ok if dosage_present trailing bits set |
| 2187 |
BoolErr PwcAppendBiallelicGenovecDosage16(const uintptr_t* __restrict genovec, const uintptr_t* __restrict dosage_present, const uint16_t* dosage_main, uint32_t dosage_ct, PgenWriterCommon* pwcp) { |
| 2188 |
// safe to call this even when entire file has no phase/dosage info |
| 2189 |
const uint32_t vidx = pwcp->vidx; |
| 2190 |
unsigned char vrtype; |
| 2191 |
uint32_t vrec_len = PwcAppendBiallelicGenovecMain(genovec, vidx, pwcp, nullptr, nullptr, &vrtype); |
| 2192 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 2193 |
pwcp->vidx += 1; |
| 2194 |
unsigned char* vrec_len_dest = &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct]); |
| 2195 |
if (dosage_ct) { |
| 2196 |
if (unlikely(AppendDosage16(dosage_present, dosage_main, dosage_ct, 0, pwcp, &vrtype, &vrec_len))) { |
| 2197 |
return 1; |
| 2198 |
} |
| 2199 |
} |
| 2200 |
SubU32Store(vrec_len, vrec_len_byte_ct, vrec_len_dest); |
| 2201 |
if (!pwcp->phase_dosage_gflags) { |
| 2202 |
pwcp->vrtype_buf[vidx / kBitsPerWordD4] |= S_CAST(uintptr_t, vrtype) << (4 * (vidx % kBitsPerWordD4)); |
| 2203 |
} else { |
| 2204 |
DowncastToUc(pwcp->vrtype_buf)[vidx] = vrtype; |
| 2205 |
} |
| 2206 |
return 0; |
| 2207 |
} |
| 2208 |
|
| 2209 |
// NOT ok if phasepresent trailing bits set, but ok for dosage_present |
| 2210 |
BoolErr PwcAppendBiallelicGenovecHphaseDosage16(const uintptr_t* __restrict genovec, const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict phaseinfo, const uintptr_t* __restrict dosage_present, const uint16_t* dosage_main, uint32_t dosage_ct, PgenWriterCommon* pwcp) { |
| 2211 |
// assumes there is phase and/or dosage data in output file, otherwise |
| 2212 |
// vrtype_dest needs to be replaced |
| 2213 |
|
| 2214 |
// this mostly overlaps with PwcAppendBiallelicGenovecHphase(); probably |
| 2215 |
// get rid of the latter |
| 2216 |
const uint32_t vidx = pwcp->vidx; |
| 2217 |
unsigned char* vrtype_dest = &(DowncastToUc(pwcp->vrtype_buf)[vidx]); |
| 2218 |
uint32_t het_ct; |
| 2219 |
uint32_t vrec_len = PwcAppendBiallelicGenovecMain(genovec, vidx, pwcp, &het_ct, nullptr, vrtype_dest); |
| 2220 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 2221 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 2222 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 2223 |
pwcp->vidx += 1; |
| 2224 |
unsigned char* vrec_len_dest = &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct]); |
| 2225 |
const uint32_t phasepresent_ct = phasepresent? PopcountWords(phasepresent, sample_ctl) : het_ct; |
| 2226 |
if (phasepresent_ct) { |
| 2227 |
AppendHphase(genovec, phasepresent, phaseinfo, het_ct, phasepresent_ct, pwcp, vrtype_dest, &vrec_len); |
| 2228 |
} |
| 2229 |
if (dosage_ct) { |
| 2230 |
if (unlikely(AppendDosage16(dosage_present, dosage_main, dosage_ct, 0, pwcp, vrtype_dest, &vrec_len))) { |
| 2231 |
return 1; |
| 2232 |
} |
| 2233 |
} |
| 2234 |
SubU32Store(vrec_len, vrec_len_byte_ct, vrec_len_dest); |
| 2235 |
return 0; |
| 2236 |
} |
| 2237 |
|
| 2238 |
BoolErr AppendDphase16(const uintptr_t* __restrict dosage_present, const uintptr_t* __restrict dphase_present, const int16_t* dphase_delta, uint32_t dosage_ct, uint32_t dphase_ct, PgenWriterCommon* pwcp, unsigned char* vrtype_ptr, uint32_t* vrec_len_ptr) { |
| 2239 |
assert(dphase_ct); |
| 2240 |
*vrtype_ptr += 0x80; |
| 2241 |
if (dphase_ct != pwcp->sample_ct) { |
| 2242 |
// bugfix (9 Dec 2018): forgot to separate fixed-width phased-dosage case |
| 2243 |
// bugfix (12 Feb 2019): double-added dphase_ct * sizeof(int16_t) |
| 2244 |
const uint32_t dphase_present_byte_ct = DivUp(dosage_ct, CHAR_BIT); |
| 2245 |
if (unlikely(CheckedVrecLenIncr(dphase_present_byte_ct, vrec_len_ptr))) { |
| 2246 |
return 1; |
| 2247 |
} |
| 2248 |
CopyBitarrSubsetToUnaligned(dphase_present, dosage_present, dosage_ct, pwcp->fwrite_bufp); |
| 2249 |
pwcp->fwrite_bufp = &(pwcp->fwrite_bufp[dphase_present_byte_ct]); |
| 2250 |
} |
| 2251 |
// bugfix (2 Jan 2019): forgot to update vrec_len here |
| 2252 |
if (unlikely(CheckedVrecLenIncr(dphase_ct * sizeof(int16_t), vrec_len_ptr))) { |
| 2253 |
return 1; |
| 2254 |
} |
| 2255 |
pwcp->fwrite_bufp = memcpyua(pwcp->fwrite_bufp, dphase_delta, dphase_ct * sizeof(int16_t)); |
| 2256 |
return 0; |
| 2257 |
} |
| 2258 |
|
| 2259 |
BoolErr PwcAppendBiallelicGenovecDphase16(const uintptr_t* __restrict genovec, const uintptr_t* __restrict phasepresent, const uintptr_t* __restrict phaseinfo, const uintptr_t* __restrict dosage_present, const uintptr_t* __restrict dphase_present, const uint16_t* dosage_main, const int16_t* dphase_delta, uint32_t dosage_ct, uint32_t dphase_ct, PgenWriterCommon* pwcp) { |
| 2260 |
// assumes there is phase and/or dosage data in output file, otherwise |
| 2261 |
// vrtype_dest needs to be replaced |
| 2262 |
const uint32_t vidx = pwcp->vidx; |
| 2263 |
unsigned char* vrtype_dest = &(DowncastToUc(pwcp->vrtype_buf)[vidx]); |
| 2264 |
uint32_t het_ct; |
| 2265 |
uint32_t vrec_len = PwcAppendBiallelicGenovecMain(genovec, vidx, pwcp, &het_ct, nullptr, vrtype_dest); |
| 2266 |
const uintptr_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 2267 |
const uint32_t sample_ct = pwcp->sample_ct; |
| 2268 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 2269 |
pwcp->vidx += 1; |
| 2270 |
unsigned char* vrec_len_dest = &(pwcp->vrec_len_buf[vidx * vrec_len_byte_ct]); |
| 2271 |
const uint32_t phasepresent_ct = phasepresent? PopcountWords(phasepresent, sample_ctl) : het_ct; |
| 2272 |
if (phasepresent_ct) { |
| 2273 |
AppendHphase(genovec, phasepresent, phaseinfo, het_ct, phasepresent_ct, pwcp, vrtype_dest, &vrec_len); |
| 2274 |
} |
| 2275 |
if (dosage_ct) { |
| 2276 |
if (unlikely(AppendDosage16(dosage_present, dosage_main, dosage_ct, dphase_ct, pwcp, vrtype_dest, &vrec_len))) { |
| 2277 |
return 1; |
| 2278 |
} |
| 2279 |
if (dphase_ct) { |
| 2280 |
if (unlikely(AppendDphase16(dosage_present, dphase_present, dphase_delta, dosage_ct, dphase_ct, pwcp, vrtype_dest, &vrec_len))) { |
| 2281 |
return 1; |
| 2282 |
} |
| 2283 |
} |
| 2284 |
} |
| 2285 |
SubU32Store(vrec_len, vrec_len_byte_ct, vrec_len_dest); |
| 2286 |
return 0; |
| 2287 |
} |
| 2288 |
|
| 2289 |
uint32_t PhaseOrDosagePresent(const uintptr_t* vrtype_buf, uint32_t variant_ct) { |
| 2290 |
// Assumes trailing bits of vrtype_buf are zeroed out. (This happens during |
| 2291 |
// vrtype_buf initialization.) |
| 2292 |
const uint32_t word_ct = DivUp(variant_ct, kBytesPerWord); |
| 2293 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 2294 |
if (vrtype_buf[widx] & (kMask0101 * 0xf0)) { |
| 2295 |
return 1; |
| 2296 |
} |
| 2297 |
} |
| 2298 |
return 0; |
| 2299 |
} |
| 2300 |
|
| 2301 |
// ext_iter == nullptr ok |
| 2302 |
IntErr AppendExtVarint(const PgenExtensionLl* ext_iter, FILE* pgen) { |
| 2303 |
int32_t cur_outbyte = 0; |
| 2304 |
uint32_t flushed_byte_ct = 0; |
| 2305 |
while (ext_iter) { |
| 2306 |
const uint32_t cur_type_idx = ext_iter->type_idx; |
| 2307 |
const uint32_t cur_type_idx_div7 = cur_type_idx / 7; |
| 2308 |
const uint32_t bytes_to_flush = cur_type_idx_div7 - flushed_byte_ct; |
| 2309 |
if (bytes_to_flush) { |
| 2310 |
putc_unlocked(cur_outbyte | 128, pgen); |
| 2311 |
for (uint32_t uii = 1; uii != bytes_to_flush; ++uii) { |
| 2312 |
putc_unlocked(128, pgen); |
| 2313 |
} |
| 2314 |
cur_outbyte = 0; |
| 2315 |
flushed_byte_ct = cur_type_idx_div7; |
| 2316 |
} |
| 2317 |
cur_outbyte |= 1 << (cur_type_idx % 7); |
| 2318 |
|
| 2319 |
ext_iter = ext_iter->next; |
| 2320 |
} |
| 2321 |
return putc_checked(cur_outbyte, pgen); |
| 2322 |
} |
| 2323 |
|
| 2324 |
PglErr AppendExtSizesAndContents(const PgenExtensionLl* exts, FILE* pgen) { |
| 2325 |
const PgenExtensionLl* exts_iter = exts; |
| 2326 |
do { |
| 2327 |
const uint64_t size = exts_iter->size; |
| 2328 |
if (unlikely(size >= (1LLU << (kBitsPerWord - 1)))) { |
| 2329 |
return kPglRetImproperFunctionCall; |
| 2330 |
} |
| 2331 |
FPutVint64(size, pgen); |
| 2332 |
exts_iter = exts_iter->next; |
| 2333 |
} while (exts_iter); |
| 2334 |
exts_iter = exts; |
| 2335 |
do { |
| 2336 |
if (unlikely(fwrite_checked(exts_iter->contents, exts_iter->size, pgen))) { |
| 2337 |
return kPglRetWriteFail; |
| 2338 |
} |
| 2339 |
exts_iter = exts_iter->next; |
| 2340 |
} while (exts_iter); |
| 2341 |
return kPglRetSuccess; |
| 2342 |
} |
| 2343 |
|
| 2344 |
PglErr PwcFinish(PgenWriterCommon* pwcp, FILE** pgen_outfile_ptr, FILE** pgi_or_final_pgen_outfile_ptr, char** fname_buf_ptr) { |
| 2345 |
uint64_t footer_fpos = 0; |
| 2346 |
if (pwcp->footer_exts) { |
| 2347 |
footer_fpos = ftello(*pgen_outfile_ptr); |
| 2348 |
if (!(*fname_buf_ptr)) { |
| 2349 |
PglErr reterr = AppendExtSizesAndContents(pwcp->footer_exts, *pgen_outfile_ptr); |
| 2350 |
if (unlikely(reterr)) { |
| 2351 |
return reterr; |
| 2352 |
} |
| 2353 |
} |
| 2354 |
} |
| 2355 |
const uint32_t variant_ct = pwcp->vidx; |
| 2356 |
FILE** header_ff_ptr; |
| 2357 |
if (*pgi_or_final_pgen_outfile_ptr) { |
| 2358 |
// kPgenWriteSeparateIndex, kPgenWriteAndCopy |
| 2359 |
assert(variant_ct); |
| 2360 |
assert(pwcp->variant_ct_limit >= variant_ct); |
| 2361 |
if (pwcp->phase_dosage_gflags) { |
| 2362 |
// Check if there is at least one variant with a phase or dosage data |
| 2363 |
// track. |
| 2364 |
if (!PhaseOrDosagePresent(pwcp->vrtype_buf, variant_ct)) { |
| 2365 |
// If not, shrink the index. |
| 2366 |
Reduce8to4bitInplaceUnsafe(variant_ct, pwcp->vrtype_buf); |
| 2367 |
pwcp->phase_dosage_gflags = kfPgenGlobal0; |
| 2368 |
} |
| 2369 |
} |
| 2370 |
if (unlikely(fclose_null(pgen_outfile_ptr))) { |
| 2371 |
return kPglRetWriteFail; |
| 2372 |
} |
| 2373 |
header_ff_ptr = pgi_or_final_pgen_outfile_ptr; |
| 2374 |
if (*fname_buf_ptr) { |
| 2375 |
*pgen_outfile_ptr = fopen(*fname_buf_ptr, FOPEN_RB); |
| 2376 |
if (unlikely(!(*pgen_outfile_ptr))) { |
| 2377 |
return kPglRetOpenFail; |
| 2378 |
} |
| 2379 |
} |
| 2380 |
} else { |
| 2381 |
// kPgenWriteBackwardSeek |
| 2382 |
assert(pwcp->variant_ct_limit == variant_ct); |
| 2383 |
header_ff_ptr = pgen_outfile_ptr; |
| 2384 |
if (unlikely(fseeko(*header_ff_ptr, 3, SEEK_SET))) { |
| 2385 |
return kPglRetWriteFail; |
| 2386 |
} |
| 2387 |
} |
| 2388 |
FILE* header_ff = *header_ff_ptr; |
| 2389 |
const PgenGlobalFlags phase_dosage_gflags = pwcp->phase_dosage_gflags; |
| 2390 |
fwrite_unlocked(&variant_ct, sizeof(int32_t), 1, header_ff); |
| 2391 |
fwrite_unlocked(&(pwcp->sample_ct), sizeof(int32_t), 1, header_ff); |
| 2392 |
|
| 2393 |
const uint32_t vrec_len_byte_ct = pwcp->vrec_len_byte_ct; |
| 2394 |
const uint32_t control_byte = (vrec_len_byte_ct - 1) + (4 * (phase_dosage_gflags != 0)) + (pwcp->nonref_flags_storage << 6); |
| 2395 |
putc_unlocked(control_byte, header_ff); |
| 2396 |
|
| 2397 |
const uint32_t vblock_ct = DivUp(variant_ct, kPglVblockSize); |
| 2398 |
if (*fname_buf_ptr) { |
| 2399 |
// Current vblock_fpos values are with no index. Determine the size of the |
| 2400 |
// index and add it to all array entries. |
| 2401 |
|
| 2402 |
// variant_ct, sample_ct, control_byte, vblock_fpos itself |
| 2403 |
uintptr_t index_size = 9 + vblock_ct * sizeof(int64_t); |
| 2404 |
// vrtypes |
| 2405 |
if (phase_dosage_gflags != 0) { |
| 2406 |
index_size += variant_ct; |
| 2407 |
} else { |
| 2408 |
index_size += DivUp(variant_ct, 2); |
| 2409 |
} |
| 2410 |
// vrec_lens |
| 2411 |
index_size += vrec_len_byte_ct * S_CAST(uintptr_t, variant_ct); |
| 2412 |
// nonref_flags |
| 2413 |
if (pwcp->explicit_nonref_flags) { |
| 2414 |
index_size += DivUp(variant_ct, CHAR_BIT); |
| 2415 |
} |
| 2416 |
for (uint32_t vblock_idx = 0; vblock_idx != vblock_ct; ++vblock_idx) { |
| 2417 |
pwcp->vblock_fpos[vblock_idx] += index_size; |
| 2418 |
} |
| 2419 |
} |
| 2420 |
fwrite_unlocked(pwcp->vblock_fpos, vblock_ct * sizeof(int64_t), 1, header_ff); |
| 2421 |
const unsigned char* vrtype_buf_iter = DowncastToUc(pwcp->vrtype_buf); |
| 2422 |
const unsigned char* vrec_len_buf_iter = pwcp->vrec_len_buf; |
| 2423 |
uint32_t vrec_iter_incr = kPglVblockSize * vrec_len_byte_ct; |
| 2424 |
uint32_t vrtype_buf_iter_incr = phase_dosage_gflags? kPglVblockSize : (kPglVblockSize / 2); |
| 2425 |
uint32_t nonref_flags_write_byte_ct = kPglVblockSize / CHAR_BIT; |
| 2426 |
const unsigned char* vrec_len_buf_last = &(vrec_len_buf_iter[S_CAST(uintptr_t, vblock_ct - 1) * vrec_iter_incr]); |
| 2427 |
uintptr_t* explicit_nonref_flags = pwcp->explicit_nonref_flags; |
| 2428 |
uintptr_t* explicit_nonref_flags_iter = explicit_nonref_flags; |
| 2429 |
for (; ; vrec_len_buf_iter = &(vrec_len_buf_iter[vrec_iter_incr])) { |
| 2430 |
if (vrec_len_buf_iter >= vrec_len_buf_last) { |
| 2431 |
if (vrec_len_buf_iter > vrec_len_buf_last) { |
| 2432 |
break; |
| 2433 |
} |
| 2434 |
const uint32_t vblock_size = ModNz(variant_ct, kPglVblockSize); |
| 2435 |
vrtype_buf_iter_incr = phase_dosage_gflags? vblock_size : DivUp(vblock_size, 2); |
| 2436 |
vrec_iter_incr = vblock_size * vrec_len_byte_ct; |
| 2437 |
nonref_flags_write_byte_ct = DivUp(vblock_size, CHAR_BIT); |
| 2438 |
} |
| 2439 |
// 4b(i): array of 4-bit or 1-byte vrtypes |
| 2440 |
fwrite_unlocked(vrtype_buf_iter, vrtype_buf_iter_incr, 1, header_ff); |
| 2441 |
vrtype_buf_iter = &(vrtype_buf_iter[vrtype_buf_iter_incr]); |
| 2442 |
|
| 2443 |
// 4b(ii): array of variant record lengths |
| 2444 |
if (unlikely(fwrite_checked(vrec_len_buf_iter, vrec_iter_incr, header_ff))) { |
| 2445 |
return kPglRetWriteFail; |
| 2446 |
} |
| 2447 |
|
| 2448 |
// If we were writing allele_idx_offsets, that would happen here. |
| 2449 |
|
| 2450 |
// 4b(iii): explicit nonref flags |
| 2451 |
if (explicit_nonref_flags) { |
| 2452 |
if (unlikely(fwrite_checked(explicit_nonref_flags_iter, nonref_flags_write_byte_ct, header_ff))) { |
| 2453 |
return kPglRetWriteFail; |
| 2454 |
} |
| 2455 |
explicit_nonref_flags_iter = &(explicit_nonref_flags_iter[kPglVblockSize / kBitsPerWord]); |
| 2456 |
} |
| 2457 |
} |
| 2458 |
if (pwcp->header_exts || pwcp->footer_exts) { |
| 2459 |
if (unlikely(AppendExtVarint(pwcp->header_exts, header_ff) || |
| 2460 |
AppendExtVarint(pwcp->footer_exts, header_ff))) { |
| 2461 |
return kPglRetWriteFail; |
| 2462 |
} |
| 2463 |
if (pwcp->footer_exts) { |
| 2464 |
if (*fname_buf_ptr) { |
| 2465 |
// In kPgenWriteAndCopy mode, initial footer_fpos value is relative to |
| 2466 |
// the start of the .pgen body. We now need to add the header size. |
| 2467 |
footer_fpos += ftello(header_ff) + sizeof(int64_t); |
| 2468 |
const PgenExtensionLl* header_exts_iter = pwcp->header_exts; |
| 2469 |
while (header_exts_iter) { |
| 2470 |
const uintptr_t cur_size = header_exts_iter->size; |
| 2471 |
footer_fpos += cur_size + VintBytect(cur_size); |
| 2472 |
header_exts_iter = header_exts_iter->next; |
| 2473 |
} |
| 2474 |
} |
| 2475 |
if (unlikely(!fwrite_unlocked(&footer_fpos, sizeof(int64_t), 1, header_ff))) { |
| 2476 |
return kPglRetWriteFail; |
| 2477 |
} |
| 2478 |
} |
| 2479 |
if (pwcp->header_exts) { |
| 2480 |
PglErr reterr = AppendExtSizesAndContents(pwcp->header_exts, header_ff); |
| 2481 |
if (unlikely(reterr)) { |
| 2482 |
return reterr; |
| 2483 |
} |
| 2484 |
} |
| 2485 |
} |
| 2486 |
if (!(*fname_buf_ptr)) { |
| 2487 |
return fclose_null(header_ff_ptr)? kPglRetWriteFail : kPglRetSuccess; |
| 2488 |
} |
| 2489 |
// Append temporary-.pgen body (excluding the 3 bytes containing the leading |
| 2490 |
// magic number) to final output file. |
| 2491 |
unsigned char copybuf[kPglFwriteBlockSize + 3]; |
| 2492 |
uintptr_t nbyte = fread(copybuf, 1, kPglFwriteBlockSize + 3, *pgen_outfile_ptr); |
| 2493 |
if (unlikely((nbyte <= 3) || (!memequal_k(copybuf, "l\x1b", 2)))) { |
| 2494 |
return kPglRetRewindFail; |
| 2495 |
} |
| 2496 |
nbyte -= 3; |
| 2497 |
if (unlikely(!fwrite_unlocked(&(copybuf[3]), nbyte, 1, header_ff))) { |
| 2498 |
return kPglRetWriteFail; |
| 2499 |
} |
| 2500 |
while (1) { |
| 2501 |
nbyte = fread(copybuf, 1, kPglFwriteBlockSize, *pgen_outfile_ptr); |
| 2502 |
if (!nbyte) { |
| 2503 |
break; |
| 2504 |
} |
| 2505 |
if (unlikely(!fwrite_unlocked(copybuf, nbyte, 1, header_ff))) { |
| 2506 |
return kPglRetWriteFail; |
| 2507 |
} |
| 2508 |
} |
| 2509 |
if (pwcp->footer_exts) { |
| 2510 |
PglErr reterr = AppendExtSizesAndContents(pwcp->footer_exts, header_ff); |
| 2511 |
if (unlikely(reterr)) { |
| 2512 |
return kPglRetWriteFail; |
| 2513 |
} |
| 2514 |
} |
| 2515 |
if (unlikely(fclose_null(pgen_outfile_ptr) || |
| 2516 |
unlink(*fname_buf_ptr) || |
| 2517 |
fclose_null(header_ff_ptr))) { |
| 2518 |
return kPglRetWriteFail; |
| 2519 |
} |
| 2520 |
free(*fname_buf_ptr); |
| 2521 |
*fname_buf_ptr = nullptr; |
| 2522 |
return kPglRetSuccess; |
| 2523 |
} |
| 2524 |
|
| 2525 |
PglErr SpgwFinish(STPgenWriter* spgwp) { |
| 2526 |
PgenWriterCommon* pwcp = GetPwcp(spgwp); |
| 2527 |
FILE** pgen_outfilep = GetPgenOutfilep(spgwp); |
| 2528 |
if (unlikely(fwrite_checked(pwcp->fwrite_buf, pwcp->fwrite_bufp - pwcp->fwrite_buf, *pgen_outfilep))) { |
| 2529 |
return kPglRetWriteFail; |
| 2530 |
} |
| 2531 |
FILE** pgi_or_final_pgen_outfilep = GetPgiOrFinalPgenOutfilep(spgwp); |
| 2532 |
char** fname_bufp = GetFnameBufp(spgwp); |
| 2533 |
return PwcFinish(pwcp, pgen_outfilep, pgi_or_final_pgen_outfilep, fname_bufp); |
| 2534 |
} |
| 2535 |
|
| 2536 |
PglErr MpgwFlush(MTPgenWriter* mpgwp) { |
| 2537 |
PgenWriterCommon* pwcp = mpgwp->pwcs[0]; |
| 2538 |
uint32_t vidx = RoundDownPow2(pwcp->vidx - 1, kPglVblockSize); |
| 2539 |
uint32_t thread_ct = mpgwp->thread_ct; |
| 2540 |
const uint32_t variant_ct = pwcp->variant_ct_limit; |
| 2541 |
const uint32_t is_last_flush = ((vidx + thread_ct * kPglVblockSize) >= variant_ct); |
| 2542 |
if (is_last_flush) { |
| 2543 |
thread_ct = DivUp(variant_ct - vidx, kPglVblockSize); |
| 2544 |
} |
| 2545 |
uint64_t* vblock_fpos = pwcp->vblock_fpos; |
| 2546 |
FILE* pgen_outfile = mpgwp->pgen_outfile; |
| 2547 |
const uint32_t vidx_incr = (thread_ct - 1) * kPglVblockSize; |
| 2548 |
uint64_t cur_vblock_fpos = ftello(pgen_outfile); |
| 2549 |
for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) { |
| 2550 |
vblock_fpos[(vidx / kPglVblockSize) + tidx] = cur_vblock_fpos; |
| 2551 |
PgenWriterCommon* cur_pwcp = mpgwp->pwcs[tidx]; |
| 2552 |
uintptr_t cur_vblock_byte_ct = cur_pwcp->fwrite_bufp - cur_pwcp->fwrite_buf; |
| 2553 |
if (unlikely(fwrite_checked(cur_pwcp->fwrite_buf, cur_vblock_byte_ct, pgen_outfile))) { |
| 2554 |
return kPglRetWriteFail; |
| 2555 |
} |
| 2556 |
cur_pwcp->vidx += vidx_incr; |
| 2557 |
cur_pwcp->fwrite_bufp = cur_pwcp->fwrite_buf; |
| 2558 |
cur_vblock_fpos += cur_vblock_byte_ct; |
| 2559 |
} |
| 2560 |
if (!is_last_flush) { |
| 2561 |
return kPglRetSuccess; |
| 2562 |
} |
| 2563 |
pwcp->vidx = variant_ct; |
| 2564 |
return PwcFinish(pwcp, &(mpgwp->pgen_outfile), &(mpgwp->pgi_or_final_pgen_outfile), &(mpgwp->fname_buf)); |
| 2565 |
} |
| 2566 |
|
| 2567 |
BoolErr CleanupSpgw(STPgenWriter* spgwp, PglErr* reterrp) { |
| 2568 |
// assume file is open if spgw.pgen_outfile is not null |
| 2569 |
// memory is the responsibility of the caller for now |
| 2570 |
FILE** pgen_outfilep = GetPgenOutfilep(spgwp); |
| 2571 |
FILE** pgi_or_final_pgen_outfilep = GetPgiOrFinalPgenOutfilep(spgwp); |
| 2572 |
char** fname_bufp = GetFnameBufp(spgwp); |
| 2573 |
BoolErr fclose_err = 0; |
| 2574 |
if (*pgi_or_final_pgen_outfilep) { |
| 2575 |
fclose_err = fclose_null(pgi_or_final_pgen_outfilep); |
| 2576 |
} |
| 2577 |
if (*pgen_outfilep) { |
| 2578 |
if (fclose_null(pgen_outfilep)) { |
| 2579 |
fclose_err = 1; |
| 2580 |
} |
| 2581 |
} |
| 2582 |
if (*fname_bufp) { |
| 2583 |
free(*fname_bufp); |
| 2584 |
*fname_bufp = nullptr; |
| 2585 |
} |
| 2586 |
if (unlikely(fclose_err && (*reterrp == kPglRetSuccess))) { |
| 2587 |
*reterrp = kPglRetWriteFail; |
| 2588 |
} |
| 2589 |
return fclose_err; |
| 2590 |
} |
| 2591 |
|
| 2592 |
BoolErr CleanupMpgw(MTPgenWriter* mpgwp, PglErr* reterrp) { |
| 2593 |
if (!mpgwp) { |
| 2594 |
return 0; |
| 2595 |
} |
| 2596 |
FILE** pgen_outfilep = &(mpgwp->pgen_outfile); |
| 2597 |
FILE** pgi_or_final_pgen_outfilep = &(mpgwp->pgi_or_final_pgen_outfile); |
| 2598 |
char** fname_bufp = &(mpgwp->fname_buf); |
| 2599 |
BoolErr fclose_err = 0; |
| 2600 |
if (*pgi_or_final_pgen_outfilep) { |
| 2601 |
fclose_err = fclose_null(pgi_or_final_pgen_outfilep); |
| 2602 |
} |
| 2603 |
if (*pgen_outfilep) { |
| 2604 |
if (fclose_null(pgen_outfilep)) { |
| 2605 |
fclose_err = 1; |
| 2606 |
} |
| 2607 |
} |
| 2608 |
if (*fname_bufp) { |
| 2609 |
free(*fname_bufp); |
| 2610 |
*fname_bufp = nullptr; |
| 2611 |
} |
| 2612 |
if (unlikely(fclose_err && (*reterrp == kPglRetSuccess))) { |
| 2613 |
*reterrp = kPglRetWriteFail; |
| 2614 |
} |
| 2615 |
return fclose_err; |
| 2616 |
} |
| 2617 |
|
| 2618 |
#ifdef __cplusplus |
| 2619 |
} // namespace plink2 |
| 2620 |
#endif |