Debian Codegraph @

include/plink2_bitmap.cc

raw
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 "plink2_bitmap.h"
19
20 #include <errno.h>
21
22 #ifdef __cplusplus
23 namespace plink2 {
24 #endif
25
26 static inline BitmapReaderMain* GetBrp(BitmapReader* br_ptr) {
27 return &GET_PRIVATE(*br_ptr, m);
28 }
29
30 static inline const uint32_t* GetCicp(PgrColSubsetIndex pcsi) {
31 return GET_PRIVATE(pcsi, cumulative_popcounts);
32 }
33
34 static inline BitmapWriterMain* GetBwp(BitmapWriter* bw_ptr) {
35 return &GET_PRIVATE(*bw_ptr, m);
36 }
37
38 void PreinitBitmapReader(BitmapReader* br_ptr) {
39 BitmapReaderMain* brp = GetBrp(br_ptr);
40 brp->ff = nullptr;
41 }
42
43 void PreinitBitmapWriter(BitmapWriter* bw_ptr) {
44 BitmapWriterMain* bwp = GetBwp(bw_ptr);
45 bwp->ff = nullptr;
46 }
47
48 uintptr_t CountBrAllocCachelinesRequired(uint32_t row_ct, uint32_t col_ct) {
49 // row_fpos: sizeof(int64_t) * (row_ct + 1) bytes
50 // rrtype_nyparr: DivUp(row_ct + 1, 4) bytes
51 // fread_buf, prevdiff_base_raw_bitvec, prevdiff_base_bitvec:
52 // DivUp(col_ct, CHAR_BIT) bytes each
53
54 uintptr_t cachelines_required = DivUp(row_ct + 1, kInt64PerCacheline);
55 cachelines_required += DivUp(row_ct + 1, kNypsPerCacheline);
56 cachelines_required += 3 * DivUp(col_ct, kBitsPerCacheline);
57 return cachelines_required;
58 }
59
60 PglErr BitmapReaderInitPhase1(const char* fname, BitmapReader* br_ptr, uintptr_t* br_alloc_cacheline_ct_ptr, char* errstr_buf) {
61 // Open the bitmap; verify that the initial bytes are consistent with the
62 // file format; load row/column counts; determine initial memory allocation
63 // requirement.
64 BitmapReaderMain* brp = GetBrp(br_ptr);
65 FILE* ff = fopen(fname, FOPEN_RB);
66 brp->ff = ff;
67 if (unlikely(!ff)) {
68 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Failed to open %s : %s.\n", fname, strerror(errno));
69 return kPglRetOpenFail;
70 }
71 unsigned char small_readbuf[10];
72 if (unlikely(!fread_unlocked(small_readbuf, 10, 1, ff))) {
73 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s read failure: %s.\n", fname, strerror(errno));
74 return kPglRetReadFail;
75 }
76 if (unlikely(!memequal_k(small_readbuf, "l\x1c", 2))) {
77 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: %s is not a plink-bitmap (first two bytes don't match the magic number).\n", fname);
78 return kPglRetMalformedInput;
79 }
80 memcpy(&(brp->row_ct), &(small_readbuf[2]), sizeof(int32_t));
81 memcpy(&(brp->col_ct), &(small_readbuf[6]), sizeof(int32_t));
82
83 *br_alloc_cacheline_ct_ptr = CountBrAllocCachelinesRequired(brp->row_ct, brp->col_ct);
84 return kPglRetSuccess;
85 }
86
87 void FillBrReadErrstrFromNzErrno(char* errstr_buf) {
88 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: plink-bitmap read failure: %s.\n", strerror(errno));
89 }
90
91 void FillBrReadErrstrFromErrno(char* errstr_buf) {
92 if (errno) {
93 FillBrReadErrstrFromNzErrno(errstr_buf);
94 } else {
95 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: plink-bitmap read failure: File appears to be corrupted.\n");
96 }
97 }
98
99 void FillBrReadErrstr(FILE* ff, char* errstr_buf) {
100 if (feof_unlocked(ff)) {
101 errno = 0;
102 }
103 FillBrReadErrstrFromErrno(errstr_buf);
104 }
105
106 PglErr BitmapReaderInitPhase2(BitmapReader* br_ptr, unsigned char* br_alloc, char* errstr_buf) {
107 BitmapReaderMain* brp = GetBrp(br_ptr);
108 const uintptr_t row_ct = brp->row_ct;
109 const uintptr_t col_ct = brp->col_ct;
110 // Allocate data structures from the br_alloc workspace.
111 unsigned char* br_alloc_iter = br_alloc;
112 brp->row_fpos = S_CAST(uint64_t*, arena_alloc_raw_rd((row_ct + 1) * sizeof(int64_t), &br_alloc_iter));
113 brp->rrtype_nyparr = S_CAST(uintptr_t*, arena_alloc_raw((1 + (row_ct / kNypsPerCacheline)) * kCacheline, &br_alloc_iter));
114 const uintptr_t bitvec_byte_ct = DivUp(col_ct, kBitsPerCacheline) * kCacheline;
115 brp->fread_buf = S_CAST(unsigned char*, arena_alloc_raw(bitvec_byte_ct, &br_alloc_iter));
116 const uint32_t raw_byte_ct = DivUp(col_ct, CHAR_BIT);
117 memset(&(brp->fread_buf[raw_byte_ct]), 0, (-raw_byte_ct) & (kBytesPerWord - 1));
118 brp->prevdiff_base_raw_bitvec = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_byte_ct, &br_alloc_iter));
119 if (col_ct % kBitsPerWord) {
120 brp->prevdiff_base_raw_bitvec[(col_ct - 1) / kBitsPerWord] = 0;
121 }
122 brp->prevdiff_base_bitvec = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_byte_ct, &br_alloc_iter));
123
124 brp->fp_ridx = 0;
125 brp->prevdiff_ridx = UINT32_MAX;
126 brp->prevdiff_stypes = kfPgrPrevdiffCache0;
127
128 FILE* ff = brp->ff;
129 if (!row_ct) {
130 // Don't need to make this an error for now.
131 // (Advance file position to end of header so that fp_ridx is still
132 // accurate.)
133 if (unlikely(fseeko(ff, 1, SEEK_CUR))) {
134 FillBrReadErrstrFromNzErrno(errstr_buf);
135 return kPglRetReadFail;
136 }
137 return kPglRetSuccess;
138 }
139
140 // Note that this is a rather hefty stack allocation.
141 unsigned char loadbuf[kPglRblockSize * 4];
142
143 if (unlikely(!fread_unlocked(&(loadbuf[0]), 9, 1, ff))) {
144 FillBrReadErrstr(ff, errstr_buf);
145 return kPglRetReadFail;
146 }
147 const uint32_t row_record_byte_length = loadbuf[0];
148 if (unlikely((row_record_byte_length - 1) >= 4)) {
149 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid plink-bitmap header.\n");
150 return kPglRetMalformedInput;
151 }
152
153 uint64_t cur_fpos;
154 memcpy(&cur_fpos, &(loadbuf[1]), sizeof(int64_t));
155 const uint32_t rblock_ct_m1 = (row_ct - 1) / kPglRblockSize;
156 // Don't need to load the other row block offsets, they're just present to
157 // support cheaper random access.
158 if (unlikely(fseeko(ff, rblock_ct_m1 * sizeof(int64_t), SEEK_CUR))) {
159 FillBrReadErrstrFromNzErrno(errstr_buf);
160 return kPglRetReadFail;
161 }
162 uintptr_t* rrtype_nyparr_iter = brp->rrtype_nyparr;
163 // Must guarantee a trailing zero for is_prevdiff check to work.
164 rrtype_nyparr_iter[row_ct / kBitsPerWordD2] = 0;
165 uint64_t* row_fpos_iter = brp->row_fpos;
166 uint32_t cur_rblock_row_ct = kPglRblockSize;
167 for (uint32_t rblock_idx = 0; ; ++rblock_idx) {
168 if (rblock_idx >= rblock_ct_m1) {
169 if (rblock_idx > rblock_ct_m1) {
170 break;
171 }
172 cur_rblock_row_ct = ModNz(row_ct, kPglRblockSize);
173 }
174 // Load row record types (2 bits each, 4 entries packed per byte)
175 uint32_t cur_byte_ct = DivUp(cur_rblock_row_ct, 4);
176 if (unlikely(!fread_unlocked(rrtype_nyparr_iter, cur_byte_ct, 1, ff))) {
177 FillBrReadErrstr(ff, errstr_buf);
178 return kPglRetReadFail;
179 }
180 rrtype_nyparr_iter = &(rrtype_nyparr_iter[cur_rblock_row_ct / kBitsPerWordD2]);
181
182 // Load row record lengths.
183 cur_byte_ct = cur_rblock_row_ct * row_record_byte_length;
184 if (unlikely(!fread_unlocked(loadbuf, cur_byte_ct, 1, ff))) {
185 FillBrReadErrstr(ff, errstr_buf);
186 return kPglRetReadFail;
187 }
188
189 // Identical to fpos-array-filling code in PgfiInitPhase2().
190 if (row_record_byte_length == 1) {
191 for (uint32_t cur_rblock_ridx = 0; cur_rblock_ridx != cur_rblock_row_ct; ++cur_rblock_ridx) {
192 row_fpos_iter[cur_rblock_ridx] = cur_fpos;
193 uint32_t cur_rrec_len = loadbuf[cur_rblock_ridx];
194 cur_fpos += cur_rrec_len;
195 }
196 } else if (row_record_byte_length == 2) {
197 for (uint32_t cur_rblock_ridx = 0; cur_rblock_ridx != cur_rblock_row_ct; ++cur_rblock_ridx) {
198 row_fpos_iter[cur_rblock_ridx] = cur_fpos;
199 uint16_t cur_rrec_len;
200 memcpy_k(&cur_rrec_len, &(loadbuf[cur_rblock_ridx * 2]), 2);
201 cur_fpos += cur_rrec_len;
202 }
203 } else if (row_record_byte_length == 3) {
204 for (uint32_t cur_rblock_ridx = 0; cur_rblock_ridx != cur_rblock_row_ct; ++cur_rblock_ridx) {
205 row_fpos_iter[cur_rblock_ridx] = cur_fpos;
206 uint32_t cur_rrec_len;
207 // safe to read a byte past the end, since that's in loadbuf
208 memcpy(&cur_rrec_len, &(loadbuf[cur_rblock_ridx * 3]), sizeof(int32_t));
209 cur_rrec_len &= 0xffffff;
210 cur_fpos += cur_rrec_len;
211 }
212 } else {
213 for (uint32_t cur_rblock_ridx = 0; cur_rblock_ridx != cur_rblock_row_ct; ++cur_rblock_ridx) {
214 row_fpos_iter[cur_rblock_ridx] = cur_fpos;
215 uint32_t cur_rrec_len;
216 memcpy(&cur_rrec_len, &(loadbuf[cur_rblock_ridx * 4]), 4);
217 cur_fpos += cur_rrec_len;
218 if (unlikely(cur_rrec_len > kPglMaxBitmapBytesPerRow)) {
219 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid plink-bitmap header.\n");
220 return kPglRetMalformedInput;
221 }
222 }
223 }
224 row_fpos_iter = &(row_fpos_iter[cur_rblock_row_ct]);
225 }
226
227 if (unlikely(S_CAST(uint64_t, ftello(ff)) > brp->row_fpos[0])) {
228 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid plink-bitmap header.\n");
229 return kPglRetMalformedInput;
230 }
231
232 const uint64_t actual_fpos = ftello(ff);
233 if (actual_fpos != brp->row_fpos[0]) {
234 if (unlikely(actual_fpos > brp->row_fpos[0])) {
235 snprintf(errstr_buf, kPglErrstrBufBlen, "Error: Invalid plink-bitmap header.\n");
236 return kPglRetMalformedInput;
237 }
238 if (unlikely(fseeko(ff, brp->row_fpos[0], SEEK_SET))) {
239 FillBrReadErrstrFromNzErrno(errstr_buf);
240 return kPglRetReadFail;
241 }
242 }
243 brp->row_fpos[row_ct] = cur_fpos;
244 return kPglRetSuccess;
245 }
246
247 uint32_t GetPrevdiffRidx(const uintptr_t* rrtype_nyparr, uint32_t cur_ridx) {
248 // Assuming the current row is prevdiff-encoded, this function determines
249 // the index of the base row by looking backward in rrtype_nyparr.
250 // More precisely, we find the first preceding nyp where either the low bit
251 // is unset, or the high bit is set.
252 uint32_t widx = (cur_ridx - 1) / kBitsPerWordD2;
253 uintptr_t cur_word = rrtype_nyparr[widx];
254 uintptr_t non_01 = ((cur_word >> 1) | (~cur_word)) & kMask5555;
255 // On the first iteration, we need to mask out high bits corresponding to
256 // indexes >= cur_ridx.
257 const uint32_t neg_remainder = (-cur_ridx) & (kBitsPerWordD2 - 1);
258 non_01 = non_01 & ((~k0LU) >> (2 * neg_remainder));
259 while (!non_01) {
260 cur_word = rrtype_nyparr[--widx];
261 non_01 = ((cur_word >> 1) | (~cur_word)) & kMask5555;
262 }
263 return (widx * kBitsPerWordD2) + (bsrw(non_01) / 2);
264 }
265
266 uint32_t PrevdiffLoadNecessary(uint32_t cur_ridx, BitmapReaderMain* brp) {
267 // Assuming the current row is prevdiff-encoded, this function determines
268 // whether the base row also needs to be loaded.
269 // Important: this updates brp->prevdiff_ridx when necessary, as a side
270 // effect.
271
272 // If the last row we read was (cur_ridx - 1), and the cache contains a row,
273 // it must be the correct row.
274 if (brp->prevdiff_stypes && (cur_ridx == brp->fp_ridx)) {
275 assert(brp->prevdiff_stypes & (kfPgrPrevdiffCacheBit | kfPgrPrevdiffCacheRawBit));
276 return 0;
277 }
278
279 // Ok, we need to compute the index of the base row, and compare it to
280 // brp->prevdiff_ridx.
281 const uint32_t old_prevdiff_ridx = brp->prevdiff_ridx;
282 brp->prevdiff_ridx = GetPrevdiffRidx(brp->rrtype_nyparr, cur_ridx);
283 return (brp->prevdiff_ridx != old_prevdiff_ridx);
284 }
285
286 BoolErr ReadRawBitmapRow(uint32_t ridx, BitmapReaderMain* brp, uint32_t* rrec_width_ptr) {
287 // Fills brp->fread_buf.
288 if (brp->fp_ridx != ridx) {
289 if (unlikely(fseeko(brp->ff, GetBrpFpos(brp, ridx), SEEK_SET))) {
290 return 1;
291 }
292 }
293 const uint32_t rrec_width = GetBrpRrecWidth(brp, ridx);
294 if (unlikely(!fread_unlocked(brp->fread_buf, rrec_width, 1, brp->ff))) {
295 if (feof_unlocked(brp->ff)) {
296 errno = 0;
297 }
298 return 1;
299 }
300 *rrec_width_ptr = rrec_width;
301 brp->fp_ridx = ridx + 1;
302 return 0;
303 }
304
305 PglErr ParseBitmapDifflistHeader(const unsigned char* fread_end, uint32_t raw_col_ct, const unsigned char** fread_pp, const unsigned char** difflist_group_info_ptr, uint32_t* difflist_len_ptr) {
306 // Identical to ParseDifflistHeader with raregeno_buf == nullptr, except for
307 // divisor constant.
308 const uint32_t difflist_len = GetVint31(fread_end, fread_pp);
309 // moved here to address maybe-uninitialized warnings
310 *difflist_group_info_ptr = *fread_pp;
311 *difflist_len_ptr = difflist_len;
312 if (!difflist_len) {
313 return kPglRetSuccess;
314 }
315 if (unlikely(difflist_len > raw_col_ct / kPglMaxBitmapDifflistLenDivisor)) {
316 // automatically catches GetVint31() failure
317 return kPglRetMalformedInput;
318 }
319 const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize);
320 const uint32_t col_id_byte_ct = BytesToRepresentNzU32(raw_col_ct);
321 const uint32_t difflist_index_byte_ct = group_ct * (col_id_byte_ct + 1) - 1;
322 if (PtrAddCk(fread_end, difflist_index_byte_ct, fread_pp)) {
323 return kPglRetMalformedInput;
324 }
325 return kPglRetSuccess;
326 }
327
328 // dst is in/out
329 PglErr ParseAndApplyBitmapDifflist(uint32_t rrec_width, BitmapReaderMain* brp, uintptr_t* dst) {
330 // Cannot occur after bitvec subsetting since the difflist sample indexes
331 // will be incorrect.
332 const uint32_t raw_col_ct = brp->col_ct;
333 const unsigned char* fread_ptr = brp->fread_buf;
334 const unsigned char* fread_end = &(fread_ptr[rrec_width]);
335 const unsigned char* group_info_iter;
336 uint32_t difflist_len;
337 PglErr reterr = ParseBitmapDifflistHeader(fread_end, raw_col_ct, &fread_ptr, &group_info_iter, &difflist_len);
338 if (reterr || (!difflist_len)) {
339 return reterr;
340 }
341 const uint32_t col_id_byte_ct = BytesToRepresentNzU32(raw_col_ct);
342 const uint32_t subgroup_idx_last = (difflist_len - 1) / kPglDifflistGroupSize;
343 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
344 uint32_t remaining_deltas_in_subgroup = kPglDifflistGroupSize - 1;
345 if (subgroup_idx >= subgroup_idx_last) {
346 if (subgroup_idx > subgroup_idx_last) {
347 break;
348 }
349 remaining_deltas_in_subgroup &= difflist_len - 1;
350 }
351 uint32_t raw_col_idx = SubU32Load(group_info_iter, col_id_byte_ct);
352 group_info_iter = &(group_info_iter[col_id_byte_ct]);
353 for (; ; --remaining_deltas_in_subgroup) {
354 // always check, since otherwise subsequent assignment can mutate
355 // arbitrary memory
356 if (unlikely(raw_col_idx >= raw_col_ct)) {
357 return kPglRetMalformedInput;
358 }
359 dst[raw_col_idx / kBitsPerWord] ^= k1LU << (raw_col_idx % kBitsPerWord);
360 if (!remaining_deltas_in_subgroup) {
361 break;
362 }
363 raw_col_idx += GetVint31(fread_end, &fread_ptr);
364 }
365 }
366 return kPglRetSuccess;
367 }
368
369 // dst is in/out
370 PglErr ParseAndApplyBitmapDifflistSubset(const uintptr_t* __restrict col_include, const uint32_t* __restrict col_include_cumulative_popcounts, uint32_t rrec_width, uint32_t col_ct, BitmapReaderMain* brp, uintptr_t* __restrict dst) {
371 const uint32_t raw_col_ct = brp->col_ct;
372 if (col_ct == raw_col_ct) {
373 return ParseAndApplyBitmapDifflist(rrec_width, brp, dst);
374 }
375 const unsigned char* fread_ptr = brp->fread_buf;
376 const unsigned char* fread_end = &(fread_ptr[rrec_width]);
377 const unsigned char* group_info_iter;
378 uint32_t difflist_len;
379 PglErr reterr = ParseBitmapDifflistHeader(fread_end, raw_col_ct, &fread_ptr, &group_info_iter, &difflist_len);
380 if (reterr || (!difflist_len)) {
381 return reterr;
382 }
383 const uint32_t col_id_byte_ct = BytesToRepresentNzU32(raw_col_ct);
384 const uint32_t subgroup_idx_last = (difflist_len - 1) / kPglDifflistGroupSize;
385 for (uint32_t subgroup_idx = 0; ; ++subgroup_idx) {
386 uint32_t remaining_deltas_in_subgroup = kPglDifflistGroupSize - 1;
387 if (subgroup_idx >= subgroup_idx_last) {
388 if (subgroup_idx > subgroup_idx_last) {
389 break;
390 }
391 remaining_deltas_in_subgroup &= difflist_len - 1;
392 }
393 uint32_t raw_col_idx = SubU32Load(group_info_iter, col_id_byte_ct);
394 group_info_iter = &(group_info_iter[col_id_byte_ct]);
395 for (; ; --remaining_deltas_in_subgroup) {
396 // always check, since otherwise subsequent assignment can mutate
397 // arbitrary memory
398 if (unlikely(raw_col_idx >= raw_col_ct)) {
399 return kPglRetMalformedInput;
400 }
401 if (IsSet(col_include, raw_col_idx)) {
402 const uint32_t col_idx = RawToSubsettedPos(col_include, col_include_cumulative_popcounts, raw_col_idx);
403 dst[col_idx / kBitsPerWord] ^= k1LU << (col_idx % kBitsPerWord);
404 }
405 if (!remaining_deltas_in_subgroup) {
406 break;
407 }
408 raw_col_idx += GetVint31(fread_end, &fread_ptr);
409 }
410 }
411 return kPglRetSuccess;
412 }
413
414 PglErr ParseNonPrevdiffBitvecSubset(const uintptr_t* __restrict col_include, const uint32_t* __restrict col_include_cumulative_popcounts, uint32_t rrec_width, uint32_t col_ct, uint32_t rrtype, BitmapReaderMain* brp, uintptr_t* __restrict dst) {
415 // Fills brp->prevdiff_base_raw_bitvec iff rrtype == 0 and
416 // subsetting_required.
417 // (Does not update prevdiff_stypes, caller's responsibility to care)
418 const uint32_t raw_col_ct = brp->col_ct;
419 if (!rrtype) {
420 // Uncompressed storage.
421 // assert(rrec_width == DivUp(raw_col_ct, CHAR_BIT));
422 const uintptr_t* raw_bitvec = R_CAST(const uintptr_t*, brp->fread_buf);
423 if (col_ct == raw_col_ct) {
424 // No subsetting required.
425 CopyBitarr(raw_bitvec, col_ct, dst);
426 } else {
427 CopyBitarr(raw_bitvec, raw_col_ct, brp->prevdiff_base_raw_bitvec);
428 CopyBitarrSubset(raw_bitvec, col_include, col_ct, dst);
429 }
430 return kPglRetSuccess;
431 }
432 if (rrtype == 2) {
433 ZeroWArr(BitCtToWordCt(col_ct), dst);
434 } else {
435 SetAllBits(col_ct, dst);
436 }
437 return ParseAndApplyBitmapDifflistSubset(col_include, col_include_cumulative_popcounts, rrec_width, col_ct, brp, dst);
438 }
439
440 PglErr PrevdiffLoadAndCopyBitvecSubset(const uintptr_t* __restrict col_include, const uint32_t* __restrict col_include_cumulative_popcounts, uint32_t col_ct, uint32_t ridx, BitmapReaderMain* brp, uintptr_t* __restrict dst) {
441 const uint32_t raw_col_ct = brp->col_ct;
442 if (PrevdiffLoadNecessary(ridx, brp)) {
443 const uint32_t prevdiff_ridx = brp->prevdiff_ridx;
444 uint32_t rrec_width;
445 if (unlikely(ReadRawBitmapRow(prevdiff_ridx, brp, &rrec_width))) {
446 return kPglRetReadFail;
447 }
448 const uint32_t rrtype = GetRrtype(brp, prevdiff_ridx);
449 PglErr reterr = ParseNonPrevdiffBitvecSubset(col_include, col_include_cumulative_popcounts, rrec_width, col_ct, rrtype, brp, dst);
450 brp->prevdiff_stypes = ((col_ct != raw_col_ct) && (rrtype == 0))? (kfPgrPrevdiffCacheBit | kfPgrPrevdiffCacheRawBit) : kfPgrPrevdiffCacheBit;
451 CopyBitarr(dst, col_ct, brp->prevdiff_base_bitvec);
452 return reterr;
453 }
454 if (brp->prevdiff_stypes & kfPgrPrevdiffCacheBit) {
455 CopyBitarr(brp->prevdiff_base_bitvec, col_ct, dst);
456 } else {
457 assert(brp->prevdiff_stypes & kfPgrPrevdiffCacheRawBit);
458 if (col_ct == raw_col_ct) {
459 CopyBitarr(brp->prevdiff_base_bitvec, col_ct, dst);
460 } else {
461 CopyBitarrSubset(brp->prevdiff_base_raw_bitvec, col_include, col_ct, dst);
462 CopyBitarr(dst, col_ct, brp->prevdiff_base_bitvec);
463 brp->prevdiff_stypes |= kfPgrPrevdiffCacheBit;
464 }
465 }
466 return kPglRetSuccess;
467 }
468
469 PglErr BitmapGet(const uintptr_t* __restrict col_include, PgrColSubsetIndex pcsi, uint32_t col_ct, uint32_t ridx, BitmapReader* br_ptr, uintptr_t* __restrict dst) {
470 if (!col_ct) {
471 return kPglRetSuccess;
472 }
473 BitmapReaderMain* brp = GetBrp(br_ptr);
474 assert(ridx < brp->row_ct);
475 const uint32_t* col_include_cumulative_popcounts = GetCicp(pcsi);
476
477 const uint32_t rrtype = GetRrtype(brp, ridx);
478 if (RrtypeIsPrevdiff(rrtype)) {
479 PglErr reterr = PrevdiffLoadAndCopyBitvecSubset(col_include, col_include_cumulative_popcounts, col_ct, ridx, brp, dst);
480 if (unlikely(reterr)) {
481 return reterr;
482 }
483 uint32_t rrec_width;
484 if (unlikely(ReadRawBitmapRow(ridx, brp, &rrec_width))) {
485 return kPglRetReadFail;
486 }
487 return ParseAndApplyBitmapDifflistSubset(col_include, col_include_cumulative_popcounts, rrec_width, col_ct, brp, dst);
488 }
489 uint32_t rrec_width;
490 if (unlikely(ReadRawBitmapRow(ridx, brp, &rrec_width))) {
491 return kPglRetReadFail;
492 }
493 PglErr reterr = ParseNonPrevdiffBitvecSubset(col_include, col_include_cumulative_popcounts, rrec_width, col_ct, rrtype, brp, dst);
494 if (unlikely(reterr)) {
495 return reterr;
496 }
497 const uint32_t is_prevdiff_base = RrtypeIsPrevdiff(GetRrtype(brp, ridx + 1));
498 const uint32_t prevdiff_raw_bitvec_saved = (col_ct != brp->col_ct) && (rrtype == 0);
499 if (is_prevdiff_base) {
500 CopyBitarr(dst, col_ct, brp->prevdiff_base_bitvec);
501 brp->prevdiff_ridx = ridx;
502 brp->prevdiff_stypes = prevdiff_raw_bitvec_saved? (kfPgrPrevdiffCacheBit | kfPgrPrevdiffCacheRawBit) : kfPgrPrevdiffCacheBit;
503 } else if (prevdiff_raw_bitvec_saved) {
504 // we just clobbered the cache
505 brp->prevdiff_stypes &= ~kfPgrPrevdiffCacheRawBit;
506 }
507 return kPglRetSuccess;
508 }
509
510 uintptr_t CountBwAllocCachelinesRequired(uint32_t row_ct, uint32_t col_ct) {
511 // rblock_fpos
512 const uint32_t rblock_ct = DivUp(row_ct, kPglRblockSize);
513 uintptr_t cachelines_required = Int64CtToCachelineCt(rblock_ct);
514
515 // rrec_len_buf
516 const uint32_t max_rrec_len = DivUp(col_ct, CHAR_BIT);
517 const uintptr_t rrec_len_byte_ct = BytesToRepresentNzU32(max_rrec_len);
518 cachelines_required += DivUp(row_ct * rrec_len_byte_ct, kCacheline);
519
520 // rrtype_buf
521 cachelines_required += NypCtToCachelineCt(row_ct);
522
523 // difflist_bitvec_buf, prevdiff_base_bitvec
524 cachelines_required += 2 * BitCtToCachelineCt(col_ct);
525
526 // fwrite_buf
527 cachelines_required += DivUp(max_rrec_len + kPglFwriteBlockSize, kCacheline);
528 return cachelines_required;
529 }
530
531 PglErr BitmapWriterInitPhase1(const char* fname, uint32_t row_ct, uint32_t col_ct, BitmapWriter* bw_ptr, uintptr_t* bw_alloc_cacheline_ct_ptr) {
532 assert(row_ct);
533 assert(col_ct);
534 BitmapWriterMain* bwp = GetBwp(bw_ptr);
535
536 bwp->row_ct = row_ct;
537 bwp->col_ct = col_ct;
538 #ifndef NDEBUG
539 bwp->rblock_fpos = nullptr;
540 bwp->rrec_len_buf = nullptr;
541 bwp->rrtype_buf = nullptr;
542 bwp->difflist_bitvec_buf = nullptr;
543 bwp->prevdiff_base_bitvec = nullptr;
544 bwp->fwrite_buf = nullptr;
545 bwp->fwrite_bufp = nullptr;
546 #endif
547 bwp->ridx = 0;
548
549 FILE* ff = fopen(fname, FOPEN_WB);
550 bwp->ff = ff;
551 if (unlikely(!ff)) {
552 return kPglRetOpenFail;
553 }
554 fwrite_unlocked("l\x1c", 2, 1, ff);
555 fwrite_unlocked(&row_ct, sizeof(int32_t), 1, ff);
556 fwrite_unlocked(&col_ct, sizeof(int32_t), 1, ff);
557 const uint32_t max_rrec_len = DivUp(col_ct, CHAR_BIT);
558 const unsigned char rrec_len_byte_ct = BytesToRepresentNzU32(max_rrec_len);
559 bwp->rrec_len_byte_ct = rrec_len_byte_ct;
560 if (unlikely(putc_checked(rrec_len_byte_ct, ff))) {
561 return kPglRetWriteFail;
562 }
563 const uint32_t rblock_ct = DivUp(row_ct, kPglRblockSize);
564 uintptr_t header_bytes_left = rblock_ct * sizeof(int64_t) + row_ct * S_CAST(uintptr_t, rrec_len_byte_ct) + DivUp(row_ct, 4);
565 // this should be the position of the first row
566 bwp->rblock_fpos_offset = 11 + header_bytes_left;
567
568 uintptr_t zeroed_cachelines_needed = DivUp(header_bytes_left, kCacheline);
569 if (zeroed_cachelines_needed > (kPglFwriteBlockSize / kCacheline)) {
570 zeroed_cachelines_needed = kPglFwriteBlockSize / kCacheline;
571 }
572 // could wait until fwrite_buf is allocated, and make sure it's aligned?
573 unsigned char zerobuf[kPglFwriteBlockSize];
574 memset(zerobuf, 0, zeroed_cachelines_needed * kCacheline);
575 while (header_bytes_left > kPglFwriteBlockSize) {
576 fwrite_unlocked(zerobuf, kPglFwriteBlockSize, 1, ff);
577 header_bytes_left -= kPglFwriteBlockSize;
578 }
579 if (unlikely(fwrite_checked(zerobuf, header_bytes_left, ff))) {
580 return kPglRetWriteFail;
581 }
582
583 *bw_alloc_cacheline_ct_ptr = CountBwAllocCachelinesRequired(row_ct, col_ct);
584 return kPglRetSuccess;
585 }
586
587 PglErr BitmapWriterInitPhase2(BitmapWriter* bw_ptr, unsigned char* bw_alloc) {
588 BitmapWriterMain* bwp = GetBwp(bw_ptr);
589 const uint32_t row_ct = bwp->row_ct;
590 unsigned char* alloc_iter = bw_alloc;
591 const uint32_t rblock_ct = DivUp(row_ct, kPglRblockSize);
592 const uint32_t rrtype_buf_byte_ct = NypCtToCachelineCt(row_ct) * kCacheline;
593 bwp->rblock_fpos = S_CAST(uint64_t*, arena_alloc_raw_rd(rblock_ct * sizeof(int64_t), &alloc_iter));
594 bwp->rrec_len_buf = S_CAST(unsigned char*, arena_alloc_raw_rd(row_ct * bwp->rrec_len_byte_ct, &alloc_iter));
595 bwp->rrtype_buf = S_CAST(uintptr_t*, arena_alloc_raw(rrtype_buf_byte_ct, &alloc_iter));
596 // the BwAppend... functions assume these bytes are zeroed out
597 memset(bwp->rrtype_buf, 0, rrtype_buf_byte_ct);
598
599 const uint32_t col_ct = bwp->col_ct;
600 const uint32_t bitvec_byte_alloc = BitCtToCachelineCt(col_ct) * kCacheline;
601 bwp->difflist_bitvec_buf = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_byte_alloc, &alloc_iter));
602 bwp->prevdiff_base_bitvec = S_CAST(uintptr_t*, arena_alloc_raw(bitvec_byte_alloc, &alloc_iter));
603 bwp->fwrite_buf = alloc_iter;
604 bwp->fwrite_bufp = alloc_iter;
605 // alloc_iter = &(alloc_iter[fwrite_cacheline_ct * kCacheline]);
606 return kPglRetSuccess;
607 }
608
609 uint32_t SaveBitvecDifflist(const uintptr_t* bitvec, uint32_t difflist_len, BitmapWriterMain* bwp) {
610 unsigned char* fwrite_bufp = bwp->fwrite_bufp;
611 if (!difflist_len) {
612 *fwrite_bufp = 0;
613 bwp->fwrite_bufp = &(fwrite_bufp[1]);
614 return 1;
615 }
616 unsigned char* fwrite_bufp_start = fwrite_bufp;
617 fwrite_bufp = Vint32Append(difflist_len, fwrite_bufp);
618 const uint32_t col_id_byte_ct = BytesToRepresentNzU32(bwp->col_ct);
619 const uint32_t group_ct = DivUp(difflist_len, kPglDifflistGroupSize);
620 unsigned char* group_first_sample_ids_iter = fwrite_bufp;
621 unsigned char* extra_byte_cts_iter = &(fwrite_bufp[group_ct * col_id_byte_ct]);
622 fwrite_bufp = &(extra_byte_cts_iter[group_ct - 1]);
623 unsigned char* last_group_vint_start = fwrite_bufp;
624 uint32_t last_col_idx = 0;
625 uint32_t difflist_idx = 0;
626 for (uint32_t widx = 0; ; ++widx) {
627 // probable todo: benchmark against SaveLdDifflist()'s strategy on typical
628 // workloads.
629 uintptr_t xor_word = bitvec[widx];
630 if (!xor_word) {
631 continue;
632 }
633 const uint32_t col_idx_base = widx * kBitsPerWord;
634 do {
635 const uint32_t col_idx_lowbits = ctzw(xor_word);
636 const uint32_t new_col_idx = col_idx_base + col_idx_lowbits;
637 if (!(difflist_idx % kPglDifflistGroupSize)) {
638 group_first_sample_ids_iter = memcpyua(group_first_sample_ids_iter, &new_col_idx, col_id_byte_ct);
639 if (difflist_idx) {
640 *extra_byte_cts_iter++ = S_CAST(uintptr_t, fwrite_bufp - last_group_vint_start) - (kPglDifflistGroupSize - 1);
641 }
642 last_group_vint_start = fwrite_bufp;
643 } else {
644 assert(new_col_idx >= last_col_idx + 1);
645 fwrite_bufp = Vint32Append(new_col_idx - last_col_idx, fwrite_bufp);
646 }
647 ++difflist_idx;
648 last_col_idx = new_col_idx;
649 if (difflist_idx == difflist_len) {
650 bwp->fwrite_bufp = fwrite_bufp;
651 return fwrite_bufp - fwrite_bufp_start;
652 }
653 xor_word &= xor_word - 1;
654 } while (xor_word);
655 }
656 }
657
658 PglErr BitmapAppend(const uintptr_t* bitvec, BitmapWriter* bw_ptr) {
659 BitmapWriterMain* bwp = GetBwp(bw_ptr);
660
661 if (bwp->fwrite_bufp >= &(bwp->fwrite_buf[kPglFwriteBlockSize])) {
662 const uintptr_t cur_byte_ct = bwp->fwrite_bufp - bwp->fwrite_buf;
663 if (unlikely(fwrite_checked(bwp->fwrite_buf, cur_byte_ct, bwp->ff))) {
664 return kPglRetWriteFail;
665 }
666 bwp->rblock_fpos_offset += cur_byte_ct;
667 bwp->fwrite_bufp = bwp->fwrite_buf;
668 }
669
670 const uint32_t ridx = bwp->ridx;
671 const uint32_t col_ct = bwp->col_ct;
672 const uint32_t word_ct = DivUp(col_ct, kBitsPerWord);
673 assert((!(col_ct % kBitsPerWord)) || (!(bitvec[word_ct - 1] >> (col_ct % kBitsPerWord))));
674 const uint32_t set_bit_ct = PopcountWords(bitvec, word_ct);
675 const uint32_t unset_bit_ct = col_ct - set_bit_ct;
676 uint32_t difflist_len = set_bit_ct;
677 uint32_t common_bit = 0;
678 if (set_bit_ct > unset_bit_ct) {
679 difflist_len = unset_bit_ct;
680 common_bit = 1;
681 }
682 const uint32_t max_difflist_len = col_ct / kPglMaxBitmapDifflistLenDivisor;
683 const uint32_t difflist_viable = (difflist_len <= max_difflist_len);
684
685 uintptr_t* prevdiff_base_bitvec = bwp->prevdiff_base_bitvec;
686 const uint32_t prevdiff_base_set_bit_ct = bwp->prevdiff_base_set_bit_ct;
687 uintptr_t rrtype;
688 uint32_t rrec_len;
689 if (!(ridx % kPglRblockSize)) {
690 // beginning of a row block. save raw fpos in header; prevdiff compression
691 // prohibited.
692 bwp->rblock_fpos[ridx / kPglRblockSize] = bwp->rblock_fpos_offset + S_CAST(uintptr_t, bwp->fwrite_bufp - bwp->fwrite_buf);
693 } else {
694 const uint32_t col_ctd64 = col_ct / 64;
695 if (difflist_len > col_ctd64) {
696 // do not use prevdiff compression if there are at least this many
697 // differences. could tune this threshold in the future.
698 const uint32_t prevdiff_threshold = difflist_viable? (difflist_len - col_ctd64) : max_difflist_len;
699 if (abs_i32(prevdiff_base_set_bit_ct - set_bit_ct) < prevdiff_threshold) {
700 // possible todo: benchmark against a single BitvecXorCopyAndCount
701 // function on typical workloads, if we don't switch to
702 // SaveLdDifflist's strategy of avoiding this array-write
703 const uint32_t diff_bit_ct = PopcountWordsXor(prevdiff_base_bitvec, bitvec, word_ct);
704 if (diff_bit_ct < prevdiff_threshold) {
705 BitvecXorCopy(prevdiff_base_bitvec, bitvec, word_ct, bwp->difflist_bitvec_buf);
706 rrec_len = SaveBitvecDifflist(bwp->difflist_bitvec_buf, diff_bit_ct, bwp);
707 rrtype = 1;
708 goto BitmapAppend_finish;
709 }
710 }
711 }
712 }
713 {
714 memcpy(prevdiff_base_bitvec, bitvec, word_ct * sizeof(intptr_t));
715 if (difflist_viable) {
716 const uintptr_t* difflist_bitvec = bitvec;
717 if (common_bit) {
718 BitvecInvertCopy(bitvec, word_ct, bwp->difflist_bitvec_buf);
719 difflist_bitvec = bwp->difflist_bitvec_buf;
720 }
721 rrec_len = SaveBitvecDifflist(difflist_bitvec, difflist_len, bwp);
722 rrtype = 2 + common_bit;
723 } else {
724 rrec_len = DivUp(col_ct, CHAR_BIT);
725 bwp->fwrite_bufp = memcpyua(bwp->fwrite_bufp, bitvec, rrec_len);
726 rrtype = 0;
727 }
728 }
729 BitmapAppend_finish:
730 ; // needed for pure-C compiler
731 const uintptr_t rrec_len_byte_ct = bwp->rrec_len_byte_ct;
732 SubU32Store(rrec_len, rrec_len_byte_ct, &(bwp->rrec_len_buf[ridx * rrec_len_byte_ct]));
733 bwp->prevdiff_base_set_bit_ct = set_bit_ct;
734 bwp->rrtype_buf[ridx / kBitsPerWordD2] |= rrtype << (2 * (ridx % kBitsPerWordD2));
735 bwp->ridx = ridx + 1;
736 return kPglRetSuccess;
737 }
738
739 PglErr BitmapWriterFinish(BitmapWriter* bw_ptr) {
740 BitmapWriterMain* bwp = GetBwp(bw_ptr);
741 const uint32_t row_ct = bwp->row_ct;
742 assert(bwp->ridx == row_ct);
743 FILE* ff = bwp->ff;
744 if (unlikely(fwrite_checked(bwp->fwrite_buf, bwp->fwrite_bufp - bwp->fwrite_buf, ff) ||
745 fseeko(ff, 11, SEEK_SET))) {
746 return kPglRetWriteFail;
747 }
748 const uint32_t rblock_ct = DivUp(row_ct, kPglRblockSize);
749 fwrite_unlocked(bwp->rblock_fpos, rblock_ct * sizeof(int64_t), 1, ff);
750 const unsigned char* rrtype_buf_iter = DowncastToUc(bwp->rrtype_buf);
751 const uint32_t rrec_len_byte_ct = bwp->rrec_len_byte_ct;
752 const unsigned char* rrec_len_buf_iter = bwp->rrec_len_buf;
753 uint32_t rrec_iter_incr = kPglRblockSize * rrec_len_byte_ct;
754 uint32_t rrtype_buf_iter_incr = (kPglRblockSize / 4);
755 const unsigned char* rrec_len_buf_last = &(rrec_len_buf_iter[S_CAST(uintptr_t, rblock_ct - 1) * rrec_iter_incr]);
756 for (; ; rrec_len_buf_iter = &(rrec_len_buf_iter[rrec_iter_incr])) {
757 if (rrec_len_buf_iter >= rrec_len_buf_last) {
758 if (rrec_len_buf_iter > rrec_len_buf_last) {
759 break;
760 }
761 const uint32_t rblock_size = ModNz(row_ct, kPglRblockSize);
762 rrtype_buf_iter_incr = DivUp(rblock_size, 4);
763 rrec_iter_incr = rblock_size * rrec_len_byte_ct;
764 }
765 fwrite_unlocked(rrtype_buf_iter, rrtype_buf_iter_incr, 1, ff);
766 rrtype_buf_iter = &(rrtype_buf_iter[rrtype_buf_iter_incr]);
767
768 if (unlikely(fwrite_checked(rrec_len_buf_iter, rrec_iter_incr, ff))) {
769 return kPglRetWriteFail;
770 }
771 }
772 return fclose_null(&(bwp->ff))? kPglRetWriteFail : kPglRetSuccess;
773 }
774
775
776 BoolErr CleanupBitmapReader(BitmapReader* br_ptr, PglErr* reterrp) {
777 BitmapReaderMain* brp = GetBrp(br_ptr);
778 if (!brp->ff) {
779 return 0;
780 }
781 if (!fclose_null(&brp->ff)) {
782 return 0;
783 }
784 if (*reterrp != kPglRetSuccess) {
785 return 0;
786 }
787 *reterrp = kPglRetReadFail;
788 return 1;
789 }
790
791 BoolErr CleanupBitmapWriter(BitmapWriter* bw_ptr, PglErr* reterrp) {
792 BitmapWriterMain* bwp = GetBwp(bw_ptr);
793 if (!bwp->ff) {
794 return 0;
795 }
796 if (!fclose_null(&bwp->ff)) {
797 return 0;
798 }
799 if (*reterrp != kPglRetSuccess) {
800 return 0;
801 }
802 *reterrp = kPglRetReadFail;
803 return 1;
804 }
805
806 #ifdef __cplusplus
807 } // namespace plink2
808 #endif