Debian Codegraph @

include/pgenlib_read.h

raw
1 #ifndef __PGENLIB_READ_H__
2 #define __PGENLIB_READ_H__
3
4 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
5 // Christopher Chang.
6 //
7 // This library is free software: you can redistribute it and/or modify it
8 // under the terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation; either version 3 of the License, or (at your
10 // option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this library. If not, see <http://www.gnu.org/licenses/>.
19
20
21 // pgenlib_read contains reader-specific code.
22
23 #include "pgenlib_misc.h"
24
25 #ifdef __cplusplus
26 namespace plink2 {
27 #endif
28
29 FLAGSET_DEF_START()
30 kfPgrLdcache0,
31 kfPgrLdcacheNyp = (1 << 0),
32 kfPgrLdcacheDifflist = (1 << 1),
33 kfPgrLdcacheRawNyp = (1 << 2),
34 // may also want RawDifflist
35 kfPgrLdcacheBasicGenocounts = (1 << 3)
36 FLAGSET_DEF_END(PgrLdcacheFlags);
37
38 // PgenFileInfo and PgenReader are the main exported "classes".
39 // Exported functions involving these data structure should all have
40 // "pgfi"/"pgr" in their names.
41
42 // Note that this can be default-copied.
43 typedef struct PgenFileInfoStruct {
44 // ----- Header information, constant after initialization -----
45 uint32_t raw_variant_ct;
46 uint32_t raw_sample_ct;
47
48 // 0 if variant records aren't all the same length.
49 // If they are (e.g. PLINK 1 encoding; or vrtype bits 0-5 unset), we just
50 // fseek to
51 // const_fpos_offset + const_vrec_width * ((uint64_t)variant_idx).
52 uint64_t const_fpos_offset;
53
54 uint32_t const_vrec_width;
55
56 // see below. positioned here instead of slightly later due to struct
57 // packing behavior.
58 uint32_t const_vrtype; // 256 for plink 1 encoding, UINT32_MAX for nonconst
59
60 // size (raw_variant_ct + 1), so that the number of bytes of (zero-based)
61 // variant n is var_fpos[n+1] - var_fpos[n]. nullptr if
62 // const_vrec_width is nonzero.
63 // It's not difficult to save some memory here (e.g. unless we're dealing
64 // with >256 TB files, it's trivial to go from 8 bytes down to 6 bytes per
65 // entry), but I doubt that's worth the trouble; let's worry about
66 // O(mn)-or-worse stuff, and on-disk stuff, first.
67 uint64_t* var_fpos;
68
69 // Variant record type codes.
70 // base pointer is null if mode is 0x01-0x04 (const_vrtype != UINT32_MAX).
71 // if not nullptr, required to be length >=
72 // max(raw_variant_ct + 1, RoundUpPow2(raw_variant_ct, kBytesPerWord))
73 unsigned char* vrtypes;
74
75 // alt allele counts.
76
77 // This can be nullptr if all alt allele counts are 1.
78 // (actually, we store the allele index offsets, so
79 // (allele_idx_offsets[n+1] - allele_idx_offsets[n]) is the number of alleles
80 // for variant n. Otherwise, we'd need another data structure to support
81 // fast allele name lookup.)
82 uintptr_t* allele_idx_offsets;
83
84 uintptr_t* nonref_flags;
85
86 // If pgr.nonref_flags is nullptr and kfPgenGlobalAllNonref is unset, all
87 // reference alleles are assumed to be correct.
88 PgenGlobalFlags gflags;
89
90 uint32_t max_allele_ct;
91 // uint32_t max_dosage_allele_ct; // might need this later
92
93 uint32_t extensions_present;
94
95 // if using per-variant fread(), this is non-null during PgenFileInfo
96 // initialization, but it's then "moved" to the first Pgen_reader and set to
97 // nullptr.
98 FILE* shared_ff;
99
100 // can only be non-null after PgfiInitPhase1 and before PgfiInitPhase2 /
101 // PgfiInitLoadExts, and only if the external-index-file representation is
102 // used.
103 FILE* pgi_ff;
104
105 const unsigned char* block_base; // nullptr if using per-variant fread()
106 uint64_t block_offset;
107 } PgenFileInfo;
108
109 typedef struct PgenReaderMainStruct {
110 MOVABLE_BUT_NONCOPYABLE(PgenReaderMainStruct);
111 // would like to make this const, but that makes initialization really
112 // annoying in C99
113 struct PgenFileInfoStruct fi;
114
115 // ----- Mutable state -----
116 // If we don't fseek, what's the next variant we'd read?
117 uint32_t fp_vidx;
118
119 // ** per-variant fread()-only **
120 FILE* ff;
121 unsigned char* fread_buf;
122 // ** end per-variant fread()-only **
123
124 // if LD compression is present, cache the last non-LD-compressed variant
125 uint32_t ldbase_vidx;
126
127 // flags indicating which base_variant buffers are populated
128 PgrLdcacheFlags ldbase_stypes;
129
130 uint32_t ldbase_difflist_len;
131
132 // these should be treated as private after initial allocation.
133 // not currently guaranteed to have trailing zeroes.
134 uintptr_t* ldbase_raw_genovec; // now allocated even with no LD compression
135 uintptr_t* ldbase_genovec;
136 uintptr_t* ldbase_raregeno;
137
138 // when ldbase_difflist_sample_ids[] is initialized, element
139 // [ldbase_difflist_len] must be set to sample_ct.
140 uint32_t* ldbase_difflist_sample_ids;
141
142 // common genotype can be looked up from vrtypes[]
143
144 STD_ARRAY_DECL(uint32_t, 4, ldbase_basic_genocounts);
145
146 // now only allocated if multiallelic variants, phase, and/or dosage present
147 // most commonly used for unsubsetted genovec; all_hets can be computed from
148 // this and patch_10_{set,vals}, and then aux2 can be interpreted.
149 // can also be used for other purposes after we're done processing aux2.
150 uintptr_t* workspace_vec;
151
152 // currently must hold (raw_sample_ct / kPglMaxDifflistLenDivisor)
153 // entries; may need to double the sizes later
154 // some top-level interface functions use these, so several lower-level
155 // functions cannot
156 uintptr_t* workspace_raregeno_vec;
157 uint32_t* workspace_difflist_sample_ids;
158
159 // must hold (raw_sample_ct / kPglMaxDifflistLenDivisor) entries
160 uintptr_t* workspace_raregeno_tmp_loadbuf;
161
162 uintptr_t* workspace_aux1x_present;
163 uint64_t* workspace_imp_r2; // needed in multiallelic case
164
165 uintptr_t* workspace_all_hets;
166 uintptr_t* workspace_subset; // currently used for hphase decoding
167
168 uintptr_t* workspace_dosage_present;
169 uintptr_t* workspace_dphase_present;
170
171 // phase set loading (footer track in mode 0x11) unimplemented for now;
172 // should be a sequence of (sample ID, [uint32_t phase set begin, set end),
173 // [set begin, set end), ...).
174 } PgenReaderMain;
175
176 typedef struct PgenReaderStruct {
177 #ifdef __cplusplus
178 PgenReaderMain& GET_PRIVATE_m() { return m; }
179 PgenReaderMain const& GET_PRIVATE_m() const { return m; }
180 private:
181 #endif
182 PgenReaderMain m;
183 } PgenReader;
184
185 CONSTI32(kPglVrtypePlink1, 256);
186
187 HEADER_INLINE uint32_t GetPgfiVrtype(const PgenFileInfo* pgfip, uint32_t vidx) {
188 if (pgfip->vrtypes) {
189 return pgfip->vrtypes[vidx];
190 }
191 return pgfip->const_vrtype;
192 }
193
194 HEADER_INLINE uint64_t GetPgfiFpos(const PgenFileInfo* pgfip, uintptr_t vidx) {
195 if (pgfip->var_fpos) {
196 return pgfip->var_fpos[vidx];
197 }
198 return pgfip->const_fpos_offset + pgfip->const_vrec_width * S_CAST(uint64_t, vidx);
199 }
200
201 HEADER_INLINE uint32_t GetPgfiVrecWidth(const PgenFileInfo* pgfip, uint32_t vidx) {
202 if (pgfip->var_fpos) {
203 return pgfip->var_fpos[vidx + 1] - pgfip->var_fpos[vidx];
204 }
205 return pgfip->const_vrec_width;
206 }
207
208 HEADER_INLINE uint32_t PgfiIsSimpleFormat(const PgenFileInfo* pgfip) {
209 return (pgfip->const_vrtype != UINT32_MAX);
210 }
211
212 HEADER_INLINE uint32_t VrtypeDifflist(uint32_t vrtype) {
213 return (vrtype & 4) && ((vrtype & 3) != 1);
214 }
215
216 HEADER_INLINE uint32_t VrtypeLdCompressed(uint32_t vrtype) {
217 return (vrtype & 6) == 2;
218 }
219
220 // Only checks for rarealt-containing hardcall. Multiallelic dosage may still
221 // be present when this returns zero.
222 HEADER_INLINE uint32_t VrtypeMultiallelicHc(uint32_t vrtype) {
223 return (vrtype & 8);
224 }
225
226 HEADER_INLINE uint32_t VrtypeHphase(uint32_t vrtype) {
227 return (vrtype & 0x10);
228 }
229
230 HEADER_INLINE uint32_t VrtypeAuxTracksPresent(uint32_t vrtype) {
231 return (vrtype & 0x78);
232 }
233
234 HEADER_INLINE uint32_t VrtypeVariableWidth(uint32_t vrtype) {
235 return (vrtype & 0x3e);
236 }
237
238 HEADER_INLINE uint32_t VrtypeDosage(uint32_t vrtype) {
239 return (vrtype & 0x60);
240 }
241
242 static_assert(kPglMaxAltAlleleCt <= 254, "GetAux1xAlleleEntryByteCt() needs to be updated.");
243 HEADER_INLINE uintptr_t GetAux1aAlleleEntryByteCt(uint32_t allele_ct, uint32_t rare01_ct) {
244 assert(allele_ct >= 3);
245 if (allele_ct == 3) {
246 return 0;
247 }
248 if (allele_ct == 4) {
249 return DivUp(rare01_ct, 8);
250 }
251 if (allele_ct <= 6) {
252 return DivUp(rare01_ct, 4);
253 }
254 if (allele_ct <= 18) {
255 return DivUp(rare01_ct, 2);
256 }
257 return rare01_ct;
258 }
259
260 HEADER_INLINE unsigned char* PgrGetFreadBuf(PgenReader* pgr_ptr) {
261 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
262 return pgrp->fread_buf;
263 }
264
265 HEADER_INLINE unsigned char* PgrGetVrtypes(PgenReader* pgr_ptr) {
266 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
267 return pgrp->fi.vrtypes;
268 }
269
270 HEADER_INLINE uint32_t PgrGetVrtype(const PgenReader* pgr_ptr, uint32_t vidx) {
271 const PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
272 if (pgrp->fi.vrtypes) {
273 return pgrp->fi.vrtypes[vidx];
274 }
275 return pgrp->fi.const_vrtype;
276 }
277
278 HEADER_INLINE uintptr_t* PgrGetNonrefFlags(PgenReader* pgr_ptr) {
279 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
280 return pgrp->fi.nonref_flags;
281 }
282
283 HEADER_INLINE PgenGlobalFlags PgrGetGflags(const PgenReader* pgr_ptr) {
284 const PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
285 return pgrp->fi.gflags;
286 }
287
288 HEADER_INLINE uint32_t PgrGetMaxAlleleCt(const PgenReader* pgr_ptr) {
289 const PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
290 return pgrp->fi.max_allele_ct;
291 }
292
293 HEADER_INLINE void PgrSetFreadBuf(unsigned char* fread_buf, PgenReader* pgr_ptr) {
294 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
295 pgrp->fread_buf = fread_buf;
296 }
297
298 HEADER_INLINE void PgrCopyBaseAndOffset(const PgenFileInfo* pgfip, uint32_t thread_ct, PgenReader** pgr_ptr_arr) {
299 for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
300 PgenReaderMain* pgrp = &GET_PRIVATE(*(pgr_ptr_arr[tidx]), m);
301 pgrp->fi.block_base = pgfip->block_base;
302 pgrp->fi.block_offset = pgfip->block_offset;
303 }
304 }
305
306 // This is necessary when changing sample_include, unless the new query is
307 // iterating from the first variant. (Which can almost never be assumed in
308 // plink2 since variant_include[] may not include the first variant.)
309 HEADER_INLINE void PgrClearLdCache(PgenReader* pgr_ptr) {
310 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
311 pgrp->ldbase_stypes &= kfPgrLdcacheRawNyp;
312
313 // bugfix, LdLoadNecessary() was otherwise claiming that reload wasn't
314 // necessary in certain cases
315 pgrp->ldbase_vidx = 0x80000000U;
316 }
317
318 // Design change (30 Nov 2019): It is easy to forget to call PgrClearLdCache
319 // when changing sample_include. However, each sample_include change must be
320 // accompanied by a sample_include_cumulative_popcounts update. So, if we
321 // define a sample_include_cumulative_popcounts wrapper-type which can only be
322 // initialized by a function that also clears a PgenReader LD cache, and modify
323 // all PgrGet... functions to require this wrapper-type, the frequency of
324 // foot-shooting should go down.
325 //
326 // The key usage rule is: only use this as a local variable type, and define
327 // only one of these per function (unless you're using multiple PgenReaders
328 // simultaneously, anyway). If you're changing the sample-subset when entering
329 // and exiting chrY, call PgrSetSampleSubsetIndex on your single
330 // PgrSampleSubsetIndex at the time you're crossing a chrY boundary. Don't
331 // define two preinitialized PgrSetSampleSubsetIndexes...
332 // (possible todo: if compiling as C++ and NDEBUG isn't defined, add a counter
333 // field to PgenReader which is initialized to zero, asserted to be zero and
334 // then incremented by PgrSetSampleSubsetIndex, and decremented by the
335 // PgrSampleSubsetIndex destructor.)
336 typedef struct PgrSampleSubsetIndexStruct {
337 #ifdef __cplusplus
338 const uint32_t*& GET_PRIVATE_cumulative_popcounts() { return cumulative_popcounts; }
339 const uint32_t* const& GET_PRIVATE_cumulative_popcounts() const { return cumulative_popcounts; }
340 private:
341 #endif
342 const uint32_t* cumulative_popcounts;
343 } PgrSampleSubsetIndex;
344
345 HEADER_INLINE void PgrSetSampleSubsetIndex(const uint32_t* sample_include_cumulative_popcounts, PgenReader* pgr_ptr, PgrSampleSubsetIndex* pssi_ptr) {
346 GET_PRIVATE(*pssi_ptr, cumulative_popcounts) = sample_include_cumulative_popcounts;
347 PgrClearLdCache(pgr_ptr);
348 }
349
350 HEADER_INLINE void PgrClearSampleSubsetIndex(PgenReader* pgr_ptr, PgrSampleSubsetIndex* pssi_ptr) {
351 GET_PRIVATE(*pssi_ptr, cumulative_popcounts) = nullptr;
352 if (pgr_ptr) {
353 PgrClearLdCache(pgr_ptr);
354 }
355 }
356
357 HEADER_INLINE void PgrSetBaseAndOffset0(unsigned char* block_base, uint32_t thread_ct, PgenReader** pgr_ptr_arr) {
358 for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
359 PgenReader* pgr_ptr = pgr_ptr_arr[tidx];
360 PgrClearLdCache(pgr_ptr);
361 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
362 pgrp->fi.block_base = block_base;
363 pgrp->fi.block_offset = 0;
364 }
365 }
366
367 // PgenFileInfo initialization is split into two phases, to decouple
368 // plink2's arena allocator from this library. (obvious todo: provide a simple
369 // malloc-using PgenReader constructor for anyone who doesn't want to worry
370 // about these details.)
371 //
372 // Phase 1: Open the .pgen (and .pgen.pgi, if relevant); verify that the
373 // initial bytes are consistent with the file format; load/verify sample and
374 // variant counts, initialize pgfi.const_vrtype, pgfi.const_vrec_width, and
375 // pgfi.const_fpos_offset; determine initial memory allocation requirement.
376 // pgfi_alloc_cacheline_ct does not include allele counts and nonref flags,
377 // since it may be more appropriate to allocate those arrays earlier (during
378 // loading of a .bim-like file).
379 //
380 // pgfi.var_fpos is set to nullptr if pgfi.const_vrec_width is nonzero.
381 // pgfi.vrtypes/var_allele_cts are set to nullptr in the plink1-format case.
382 //
383 // raw_sample_ct and raw_variant_ct should be UINT32_MAX if not previously
384 // known.
385 //
386 // Intermission: Caller obtains a block of pgfi_alloc_cacheline_ct * 64 bytes,
387 // 64-byte aligned. The cachealigned_malloc() function can be used for this
388 // purpose. If necessary, pgfi.allele_idx_offsets and pgfi.nonref_flags
389 // should be pointed at already-loaded data, or allocated so they can be
390 // loaded during phase 2.
391 //
392 // Phase 2: Initialize most pointers in the PgenReader struct to appropriate
393 // positions in first_alloc. For modes 0x10-0x11, load pgfi.var_fpos and
394 // pgfi.vrtypes, load/validate pgfi.allele_idx_offsets and pgfi.nonref_flags
395 // if appropriate, and initialize pgfi.gflags, pgfi.max_allele_ct, and
396 // pgfi.max_dosage_allele_ct.
397 //
398 // Finally, if block-fread mode is being used, pgfi.block_base must be
399 // initialized to point to a memory large enough to handle the largest
400 // pgfi_block_read() operation that will be attempted.
401 // pgfi_blockload_get_cacheline_req() can be used to determine the necessary
402 // buffer size.
403
404 // This type may change if we introduce a more read-optimized format in the
405 // future. Right now it just tracks the presence/absence of two optional
406 // pieces of information: allele counts and nonref flags.
407 typedef uint32_t PgenHeaderCtrl;
408
409 void PreinitPgfi(PgenFileInfo* pgfip);
410
411 // There are two modes of operation:
412 // 1. fread block-load. Block-load operations are single-threaded, while
413 // decompression/counting is multithreaded. Appropriate for whole-genome
414 // queries, since even with a SSD, reading from multiple parts of a file
415 // simultaneously doesn't work well.
416 // 2. fread single-variant-at-a-time. Simpler interface than block-load, and
417 // doesn't share its inability to handle multiple queries at a time, but
418 // less performant for CPU-heavy operations on the whole genome.
419 // First mode corresponds to use_blockload == 1 in phase2, and second mode
420 // corresponds to use_blockload == 0.
421 //
422 // There was originally a third mmap-based mode, which was removed on 14 Mar
423 // 2022. If you are interested in building e.g. a webserver backend that can
424 // address multiple queries in parallel, refer to plink-ng commit c470317,
425 // which captures the state of the codebase immediately preceding removal of
426 // the mmap mode.
427 //
428 // Other notes:
429 // - If pgi_fname is nullptr but the .pgen has an external index file, the
430 // index file name is assumed to be the .pgen filename with .pgi appended.
431 // - pgi_fname is ignored if the .pgen does not have an external index file.
432 // - raw_variant_ct must be in [1, 2^31 - 3], and raw_sample_ct must be in [1,
433 // 2^31 - 2].
434 PglErr PgfiInitPhase1(const char* fname, const char* pgi_fname, uint32_t raw_variant_ct, uint32_t raw_sample_ct, PgenHeaderCtrl* header_ctrl_ptr, PgenFileInfo* pgfip, uintptr_t* pgfi_alloc_cacheline_ct_ptr, char* errstr_buf);
435
436 // If allele_cts_already_loaded is set, but they're present in the file,
437 // they'll be validated; similarly for nonref_flags_already_loaded.
438 //
439 // If caller is interested in extensions, they should pass in header_exts
440 // and/or footer_exts entries with type_idx set to those of the extensions of
441 // interest, and type_idx values in increasing order. On return, .size values
442 // of each entry will be filled when the extension is present, and set to ~0LLU
443 // when the extension is absent.
444 PglErr PgfiInitPhase2Ex(PgenHeaderCtrl header_ctrl, uint32_t allele_cts_already_loaded, uint32_t nonref_flags_already_loaded, uint32_t use_blockload, uint32_t vblock_idx_start, uint32_t vidx_end, uint32_t* max_vrec_width_ptr, PgenFileInfo* pgfip, unsigned char* pgfi_alloc, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, uintptr_t* pgr_alloc_cacheline_ct_ptr, char* errstr_buf);
445
446 HEADER_INLINE PglErr PgfiInitPhase2(PgenHeaderCtrl header_ctrl, uint32_t allele_cts_already_loaded, uint32_t nonref_flags_already_loaded, uint32_t use_blockload, uint32_t vblock_idx_start, uint32_t vidx_end, uint32_t* max_vrec_width_ptr, PgenFileInfo* pgfip, unsigned char* pgfi_alloc, uintptr_t* pgr_alloc_cacheline_ct_ptr, char* errstr_buf) {
447 return PgfiInitPhase2Ex(header_ctrl, allele_cts_already_loaded, nonref_flags_already_loaded, use_blockload, vblock_idx_start, vidx_end, max_vrec_width_ptr, pgfip, pgfi_alloc, nullptr, nullptr, pgr_alloc_cacheline_ct_ptr, errstr_buf);
448 }
449
450 // Expected to be called right after PgfiInitPhase2Ex(), after memory buffers
451 // are provided for header_exts / footer_exts entries.
452 PglErr PgfiInitLoadExts(PgenHeaderCtrl header_ctrl, PgenFileInfo* pgfip, PgenExtensionLl* header_exts, PgenExtensionLl* footer_exts, char* errstr_buf);
453
454 uint64_t GetPgfiLdbaseFpos(const PgenFileInfo* pgfip, uintptr_t vidx);
455
456 uint64_t PgfiMultireadGetCachelineReq(const uintptr_t* variant_include, const PgenFileInfo* pgfip, uint32_t variant_ct, uint32_t block_size);
457
458 // variant_include can be nullptr; in that case, we simply load all the
459 // variants (load_variant_ct must be variant_uidx_end - variant_uidx_start).)
460 // IMPORTANT: pgfi.block_offset must be manually copied to each reader for now.
461 // (todo: probably replace pgr.fi with a pointer. when doing that, need to
462 // ensure multiple per-variant readers still works.)
463 PglErr PgfiMultiread(const uintptr_t* variant_include, uint32_t variant_uidx_start, uint32_t variant_uidx_end, uint32_t load_variant_ct, PgenFileInfo* pgfip);
464
465
466 void PreinitPgr(PgenReader* pgr_ptr);
467
468 // Before PgrInit() is called, the caller must obtain a block of
469 // pgr_alloc_cacheline_ct * 64 bytes (this value is returned by
470 // pgfi_init_phase2), 64-byte aligned; this is the pgr_alloc parameter.
471 //
472 // There's also a modal usage difference:
473 //
474 // * Mode 1 (block-fread): There is one PgenFileInfo per file which doesn't
475 // belong to any reader. After it's initialized, multiple PgenReaders can be
476 // based off of it. When the PgenFileInfo is destroyed, those PgenReaders
477 // are invalidated and should be destroyed if that hasn't already happened.
478 //
479 // fname parameter must be nullptr.
480 //
481 // * Mode 2 (per-variant fread): Destruction of the original PgenFileInfo
482 // struct does not invalidate any extant PgenReader instances (at least
483 // from pgenlib_read's perspective). Instead, destruction of the
484 // corresponding memory block or allele_idx_offsets/nonref_flags invalidates
485 // the associated PgenReaders.
486 //
487 // The only difference between the first reader and later readers of the same
488 // file is that the first reader steals the shared_ff used to read the
489 // header.
490 //
491 // fname parameter must be non-null.
492
493 // max_vrec_width ignored when using mode 1.
494 PglErr PgrInit(const char* fname, uint32_t max_vrec_width, PgenFileInfo* pgfip, PgenReader* pgr_ptr, unsigned char* pgr_alloc);
495
496 // practically all these functions require genovec to be allocated up to
497 // vector, not word, boundary
498 void PgrPlink1ToPlink2InplaceUnsafe(uint32_t sample_ct, uintptr_t* genovec);
499
500 void PgrPlink2ToPlink1InplaceUnsafe(uint32_t sample_ct, uintptr_t* genovec);
501
502 // Function names for the main reader functions were getting ridiculous.
503 // New naming scheme:
504 // * PgrGet() is the basic two-bit genovec loader. All ALT alleles are treated
505 // as equivalent. (00 = hom ref, 01 = het ref, 10 = two alt alleles, 11 =
506 // missing.)
507 // * PgrGetInv1() is similar, except that the allele index to treat as REF can
508 // be changed.
509 // * PgrGet1() only counts the specified allele. To minimize inversion costs,
510 // GetInv1() should be called on major alleles and Get1() should be called on
511 // minor ones.
512 // * PgrGetM() is the multiallelic loader which doesn't collapse multiple
513 // alleles into one. This retrieves a sparse form identical to what
514 // PwcAppendMultiallelicSparse takes.
515 // Multiallelic-dosage read functions (PgrReadRaw() included) will probably
516 // fill a 3-part data structure of the following form:
517 // 1. Bitarray indicating which samples have at least one rarealt dosage.
518 // 2. unsigned char array where, if bits a, b, and c are the only set ones in
519 // the first array, the first three elements of the second array are
520 // rarealt dosage counts (1..255) for those three samples. (Could also
521 // put those in positions [a], [b], and [c], but that produces worse
522 // memory access locality, and it makes sense to treat multiallelic
523 // dosages as fundamentally sparse.)
524 // 3. Let R := MINV(255, allele_ct - 2).
525 // a. Length-(sample_ct x R) array of AlleleCodes.
526 // b. Length-(sample_ct x R) array of uint16_t dosage (or int16_t dphase)
527 // values.
528 // Again we use the sparse representation, with payload values packed at
529 // the beginning.
530 // (--indiv-sort algorithm: initialize an array of uintptr_ts of length
531 // sample_ct where [k] has that sample's start index in the payload arrays.)
532 // * PgrGetDifflistOrGenovec() opportunistically returns the sparse genotype
533 // representation ('difflist'), for functions capable of taking advantage of
534 // it. See SampleCountsThread() in plink2_misc for a usage example.
535 // * PgrGetCounts() is equivalent to calling PgrGet() and then counting the
536 // number of 00s, 01s, 10s, and 11s, without the overhead of fully expanding
537 // the compressed data, etc.
538 // * P suffix = also returns hardcall-phase information.
539 // * D suffix = also returns dosage information.
540 // * Dp suffix = also returns hardcall-phase, dosage and phased-dosage
541 // information.
542 // * PgrGet2() and PgrGet2P() loads biallelic (possibly phased) hardcalls from
543 // a possibly-multiallelic variant. Any hardcall where either allele is not
544 // one of the specified two alleles is set to missing.
545 // There is no dosage-supporting version of this because rescaling sucks.
546
547 // This will normally extract only the genotype indexes corresponding to set
548 // bits in sample_include. Set sample_ct == raw_sample_ct if you don't want
549 // any subsetting to occur (in this case sample_include is ignored, can be
550 // nullptr).
551 // sample_ct cannot be zero. Trailing bits of genovec are not zeroed out.
552 // Ok if genovec only has space for sample_ct values.
553 PglErr PgrGet(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec);
554
555 // Loads the specified variant as a difflist if that's more efficient, setting
556 // difflist_common_geno to the common genotype value in that case. Otherwise,
557 // genovec is populated and difflist_common_geno is set to UINT32_MAX.
558 //
559 // max_simple_difflist_len must be smaller than sample_ct.
560 //
561 // Note that the returned difflist_len can be much larger than
562 // max_simple_difflist_len when the variant is LD-encoded; it's bounded by
563 // 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor).
564 // (probable todo: this interface has... rather sharp edges, even relative to
565 // the rest of this low-level library. Maybe it shouldn't be deleted, but it
566 // would be better if there was a function that took a max_difflist_len
567 // parameter, and it was safe for difflist_sample_ids to only be allocated up
568 // to that length.)
569 PglErr PgrGetDifflistOrGenovec(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t max_simple_difflist_len, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uint32_t* __restrict difflist_common_geno_ptr, uintptr_t* __restrict main_raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr);
570
571 // genocounts[0] = # hom ref, [1] = # het ref, [2] = two alts, [3] = missing
572 PglErr PgrGetCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts);
573
574 // genocounts[0] = # of hardcalls with two copies of specified allele
575 // genocounts[1] = # of hardcalls with exactly one copy of specified allele
576 // genocounts[2] = # of hardcalls with no copies
577 // genocounts[3] = missing
578 PglErr PgrGetInv1Counts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts);
579
580 PglErr IMPLPgrGet1(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_countvec);
581
582 // Loads a nypvec with counts of a single allele (allele_idx 0 corresponds to
583 // the reference allele, allele_idx 1 corresponds to alt1, etc.). 0b11 ==
584 // missing call.
585 // Note that calling this with allele_idx == 0 is similar to a plink1 load
586 // (except with missing == 0b11, of course).
587 // todo: provide a difflist interface once anyone wants it.
588 HEADER_INLINE PglErr PgrGet1(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_countvec) {
589 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
590 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
591 return IMPLPgrGet1(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_countvec);
592 }
593
594 PglErr IMPLPgrGetInv1(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_invcountvec);
595
596 HEADER_INLINE PglErr PgrGetInv1(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_invcountvec) {
597 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
598 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
599 return IMPLPgrGetInv1(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_invcountvec);
600 }
601
602 PglErr IMPLPgrGetInv1DifflistOrGenovec(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t max_simple_difflist_len, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_invcountvec, uint32_t* __restrict difflist_common_geno_ptr, uintptr_t* __restrict main_raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr);
603
604 HEADER_INLINE PglErr PgrGetInv1DifflistOrGenovec(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t max_simple_difflist_len, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_invcountvec, uint32_t* __restrict difflist_common_geno_ptr, uintptr_t* __restrict main_raregeno, uint32_t* __restrict difflist_sample_ids, uint32_t* __restrict difflist_len_ptr) {
605 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
606 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
607 return IMPLPgrGetInv1DifflistOrGenovec(sample_include, sample_include_cumulative_popcounts, sample_ct, max_simple_difflist_len, vidx, allele_idx, pgrp, allele_invcountvec, difflist_common_geno_ptr, main_raregeno, difflist_sample_ids, difflist_len_ptr);
608 }
609
610 PglErr IMPLPgrGet2(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx0, uint32_t allele_idx1, PgenReaderMain* pgrp, uintptr_t* __restrict genovec);
611
612 HEADER_INLINE PglErr PgrGet2(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx0, uint32_t allele_idx1, PgenReader* pgr_ptr, uintptr_t* __restrict genovec) {
613 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
614 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
615 return IMPLPgrGet2(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx0, allele_idx1, pgrp, genovec);
616 }
617
618 void PreinitPgv(PgenVariant* pgvp);
619
620 PglErr PgrGetM(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp);
621
622 // possible todo: add functions which directly support MAF-based queries. Note
623 // that when the difflist representation is used, we can disqualify some
624 // low-MAF variants without actually loading the genotype data, since the size
625 // of the record puts an upper bound on the alt allele frequency.
626
627 // requires trailing bits of genoarr to be zeroed out.
628 HEADER_INLINE void PgrDetectGenoarrHetsUnsafe(const uintptr_t*__restrict genoarr, uint32_t raw_sample_ctl2, uintptr_t* __restrict all_hets) {
629 PackWordsToHalfwordsInvmatch(genoarr, kMaskAAAA, raw_sample_ctl2, all_hets);
630 if (raw_sample_ctl2 % 2) {
631 Halfword* __attribute__((may_alias)) all_hets_alias = DowncastWToHW(all_hets);
632 all_hets_alias[raw_sample_ctl2] = 0;
633 }
634 }
635
636 HEADER_INLINE void PgrDetectGenoarrHets(const uintptr_t* __restrict genoarr, uint32_t raw_sample_ct, uintptr_t* __restrict all_hets) {
637 PackWordsToHalfwordsInvmatch(genoarr, kMaskAAAA, NypCtToWordCt(raw_sample_ct), all_hets);
638 ZeroTrailingBits(raw_sample_ct, all_hets);
639 }
640
641 // sample_ct > 0. ok for trailing bits of genoarr to not be zeroed out.
642 void PgrDetectGenoarrHetsMultiallelic(const uintptr_t* __restrict genoarr, const uintptr_t* __restrict patch_10_set, const AlleleCode* __restrict patch_10_vals, uint32_t raw_sample_ct, uintptr_t* __restrict all_hets);
643
644 // cannot assume phaseinfo bit is clear when phasepresent is clear.
645 PglErr PgrGetP(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr);
646
647 PglErr PgrGet1P(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_countvec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr);
648
649 PglErr IMPLPgrGetInv1P(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReaderMain* pgrp, uintptr_t* __restrict allele_invcountvec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr);
650
651 HEADER_INLINE PglErr PgrGetInv1P(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_invcountvec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr) {
652 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
653 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
654 return IMPLPgrGetInv1P(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, allele_idx, pgrp, allele_invcountvec, phasepresent, phaseinfo, phasepresent_ct_ptr);
655 }
656
657 PglErr PgrGet2P(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t allele_idx0, uint32_t allele_idx1, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uintptr_t* __restrict phasepresent, uintptr_t* __restrict phaseinfo, uint32_t* __restrict phasepresent_ct_ptr);
658
659 PglErr PgrGetMP(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp);
660
661 PglErr IMPLPgrGetD(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, uintptr_t* __restrict genovec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr);
662
663 // if dosage_present and dosage_main are nullptr, dosage data is ignored
664 HEADER_INLINE PglErr PgrGetD(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict genovec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr) {
665 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
666 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
667 return IMPLPgrGetD(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, genovec, dosage_present, dosage_main, dosage_ct_ptr);
668 }
669
670 PglErr PgrGet1D(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, AlleleCode allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_countvec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr);
671
672 PglErr PgrGetInv1D(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, AlleleCode allele_idx, PgenReader* pgr_ptr, uintptr_t* __restrict allele_invcountvec, uintptr_t* __restrict dosage_present, uint16_t* dosage_main, uint32_t* dosage_ct_ptr);
673
674 // When computing either form of imputation-r2, this function requires the
675 // variant to be biallelic; PgrGetMDCounts must be called in that multiallelic
676 // case.
677 // imp_r2_ptr must be non-null when is_minimac3_r2 is set.
678 PglErr PgrGetDCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t is_minimac3_r2, PgenReader* pgr_ptr, double* imp_r2_ptr, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* __restrict all_dosages);
679
680 PglErr PgrGetMDCounts(const uintptr_t* __restrict sample_include, const uintptr_t* __restrict sample_include_interleaved_vec, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, uint32_t is_minimac3_r2, PgenReader* pgr_ptr, double* __restrict imp_r2_ptr, uint32_t* __restrict het_ctp, STD_ARRAY_REF(uint32_t, 4) genocounts, uint64_t* __restrict all_dosages);
681
682 PglErr PgrGetMD(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp);
683
684 PglErr IMPLPgrGetDp(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, uint32_t sample_ct, uint32_t vidx, PgenReaderMain* pgrp, PgenVariant* pgvp);
685
686 // ok for both dosage_present and dosage_main to be nullptr when no dosage data
687 // is present
688 // ok for dphase_present/dphase_delta to be nullptr; dphase_ct always set to 0
689 // in that case
690 HEADER_INLINE PglErr PgrGetDp(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp) {
691 PgenReaderMain* pgrp = &GET_PRIVATE(*pgr_ptr, m);
692 const uint32_t* sample_include_cumulative_popcounts = GET_PRIVATE(pssi, cumulative_popcounts);
693 return IMPLPgrGetDp(sample_include, sample_include_cumulative_popcounts, sample_ct, vidx, pgrp, pgvp);
694 }
695
696 // pgvp->genovec filled with inverse-counts for specified allele
697 PglErr PgrGetInv1Dp(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, AlleleCode allele_idx, PgenReader* pgr_ptr, PgenVariant* pgvp);
698
699 PglErr PgrGetMDp(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, PgenVariant* pgvp);
700
701 // interface used by --make-pgen, just performs basic LD/difflist decompression
702 // to maximize parallelism
703 PglErr PgrGetRaw(uint32_t vidx, PgenGlobalFlags read_gflags, PgenReader* pgr_ptr, uintptr_t** loadbuf_iter_ptr, unsigned char* loaded_vrtype_ptr);
704
705 PglErr PgrValidate(PgenReader* pgr_ptr, uintptr_t* genovec_buf, char* errstr_buf);
706
707 // missingness bit is set iff hardcall is not present (even if dosage info *is*
708 // present)
709 PglErr PgrGetMissingness(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict missingness, uintptr_t* __restrict genovec_buf);
710
711 // either missingness_hc (hardcall) or missingness_dosage must be non-null for
712 // now
713 // missingness_dosage must be vector-aligned
714 PglErr PgrGetMissingnessD(const uintptr_t* __restrict sample_include, PgrSampleSubsetIndex pssi, uint32_t sample_ct, uint32_t vidx, PgenReader* pgr_ptr, uintptr_t* __restrict missingness_hc, uintptr_t* __restrict missingness_dosage, uintptr_t* __restrict hets, uintptr_t* __restrict genovec_buf);
715
716
717 // error-return iff reterr was success and was changed to kPglRetReadFail (i.e.
718 // an error message should be printed).
719 BoolErr CleanupPgfi(PgenFileInfo* pgfip, PglErr* reterrp);
720
721 BoolErr CleanupPgr(PgenReader* pgr_ptr, PglErr* reterrp);
722
723 #ifdef __cplusplus
724 } // namespace plink2
725 #endif
726
727 #endif // __PGENLIB_READ_H__