Debian Codegraph @

plink2_adjust.cc

raw
1 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option)
7 // any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 #include "include/plink2_stats.h"
18 #include "plink2_adjust.h"
19 #include "plink2_compress_stream.h"
20
21 #ifdef __cplusplus
22 namespace plink2 {
23 #endif
24
25 void InitAdjust(AdjustInfo* adjust_info_ptr, AdjustFileInfo* adjust_file_info_ptr) {
26 adjust_info_ptr->flags = kfAdjust0;
27 adjust_info_ptr->lambda = 0.0;
28 adjust_file_info_ptr->base.flags = kfAdjust0;
29 adjust_file_info_ptr->base.lambda = 0.0;
30 adjust_file_info_ptr->fname = nullptr;
31 adjust_file_info_ptr->test_name = nullptr;
32 adjust_file_info_ptr->chr_field = nullptr;
33 adjust_file_info_ptr->pos_field = nullptr;
34 adjust_file_info_ptr->id_field = nullptr;
35 adjust_file_info_ptr->ref_field = nullptr;
36 adjust_file_info_ptr->alt_field = nullptr;
37 adjust_file_info_ptr->provref_field = nullptr;
38 adjust_file_info_ptr->a1_field = nullptr;
39 adjust_file_info_ptr->test_field = nullptr;
40 adjust_file_info_ptr->p_field = nullptr;
41 }
42
43 void CleanupAdjust(AdjustFileInfo* adjust_file_info_ptr) {
44 free_cond(adjust_file_info_ptr->a1_field);
45 free_cond(adjust_file_info_ptr->alt_field);
46 free_cond(adjust_file_info_ptr->chr_field);
47 if (adjust_file_info_ptr->fname) {
48 free(adjust_file_info_ptr->fname);
49 free_cond(adjust_file_info_ptr->pos_field);
50 free_cond(adjust_file_info_ptr->id_field);
51 free_cond(adjust_file_info_ptr->ref_field);
52 free_cond(adjust_file_info_ptr->provref_field);
53 free_cond(adjust_file_info_ptr->test_field);
54 free_cond(adjust_file_info_ptr->p_field);
55 }
56 }
57
58 typedef struct AdjAssocResultStruct {
59 double ln_pval;
60 double chisq; // do we really need this?...
61 uint32_t variant_uidx;
62 uint32_t allele_idx;
63 #ifdef __cplusplus
64 bool operator<(const struct AdjAssocResultStruct& rhs) const {
65 return ln_pval < rhs.ln_pval;
66 }
67 #endif
68 } AdjAssocResult;
69
70 static inline void adjust_print_ln(const char* output_min_p_str, double ln_pval, double output_min_ln, uint32_t output_min_p_slen, uint32_t is_neglog10, char** bufpp) {
71 **bufpp = '\t';
72 *bufpp += 1;
73 if (ln_pval <= output_min_ln) {
74 *bufpp = memcpya(*bufpp, output_min_p_str, output_min_p_slen);
75 } else {
76 if (!is_neglog10) {
77 *bufpp = lntoa_g(ln_pval, *bufpp);
78 } else {
79 *bufpp = dtoa_g(ln_pval * (-1.0 / kLn10), *bufpp);
80 }
81 }
82 }
83
84 // Now based around ln_pvals, to allow useful comparisons < 2.23e-308.
85 PglErr Multcomp(const uintptr_t* variant_include, const ChrInfo* cip, const char* const* chr_ids, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_include, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const char* const* loaded_a1, const AdjustInfo* adjust_info_ptr, const double* ln_pvals, const double* chisqs, uint32_t raw_variant_ct, uintptr_t orig_allele_ct, uint32_t max_allele_slen, PgenGlobalFlags gflags, double ln_pfilter, double output_min_ln, uint32_t skip_gc, uint32_t max_thread_ct, char* outname, char* outname_end) {
86 unsigned char* bigstack_mark = g_bigstack_base;
87 char* cswritep = nullptr;
88 CompressStreamState css;
89 PglErr reterr = kPglRetSuccess;
90 PreinitCstream(&css);
91 {
92 AdjAssocResult* sortbuf;
93 if (unlikely(BIGSTACK_ALLOC_X(AdjAssocResult, orig_allele_ct, &sortbuf))) {
94 goto Multcomp_ret_NOMEM;
95 }
96 uintptr_t valid_allele_ct = 0;
97 uintptr_t allele_uidx_base = 0;
98 uintptr_t allele_include_bits = allele_include[0];
99 if (!allele_idx_offsets) {
100 if (chisqs) {
101 if (ln_pvals) {
102 for (uintptr_t aidx = 0; aidx != orig_allele_ct; ++aidx) {
103 const uintptr_t allele_uidx = BitIter1(allele_include, &allele_uidx_base, &allele_include_bits);
104 const double cur_chisq = chisqs[aidx];
105 if (cur_chisq >= 0.0) {
106 sortbuf[valid_allele_ct].chisq = cur_chisq;
107 sortbuf[valid_allele_ct].ln_pval = ln_pvals[aidx];
108 sortbuf[valid_allele_ct].variant_uidx = allele_uidx / 2;
109 sortbuf[valid_allele_ct].allele_idx = allele_uidx % 2;
110 ++valid_allele_ct;
111 }
112 }
113 } else {
114 for (uintptr_t aidx = 0; aidx != orig_allele_ct; ++aidx) {
115 const uintptr_t allele_uidx = BitIter1(allele_include, &allele_uidx_base, &allele_include_bits);
116 const double cur_chisq = chisqs[aidx];
117 if (cur_chisq >= 0.0) {
118 sortbuf[valid_allele_ct].chisq = cur_chisq;
119 sortbuf[valid_allele_ct].ln_pval = ChisqToLnP(cur_chisq, 1);
120 sortbuf[valid_allele_ct].variant_uidx = allele_uidx / 2;
121 sortbuf[valid_allele_ct].allele_idx = allele_uidx % 2;
122 ++valid_allele_ct;
123 }
124 }
125 }
126 } else {
127 for (uintptr_t aidx = 0; aidx != orig_allele_ct; ++aidx) {
128 const uintptr_t allele_uidx = BitIter1(allele_include, &allele_uidx_base, &allele_include_bits);
129 const double cur_ln_pval = ln_pvals[aidx];
130 if (cur_ln_pval <= 0.0) {
131 sortbuf[valid_allele_ct].chisq = LnPToChisq(cur_ln_pval);
132 sortbuf[valid_allele_ct].ln_pval = cur_ln_pval;
133 sortbuf[valid_allele_ct].variant_uidx = allele_uidx / 2;
134 sortbuf[valid_allele_ct].allele_idx = allele_uidx % 2;
135 ++valid_allele_ct;
136 }
137 }
138 }
139 } else {
140 uintptr_t variant_uidx_base = 0;
141 uintptr_t variant_include_bits = variant_include[0];
142 uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
143 uintptr_t allele_idx_offset_start = allele_idx_offsets[variant_uidx];
144 uintptr_t allele_idx_offset_end = allele_idx_offsets[variant_uidx + 1];
145 if (chisqs) {
146 if (ln_pvals) {
147 for (uintptr_t aidx = 0; aidx != orig_allele_ct; ++aidx) {
148 const uintptr_t allele_uidx = BitIter1(allele_include, &allele_uidx_base, &allele_include_bits);
149 if (allele_uidx >= allele_idx_offset_end) {
150 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
151 allele_idx_offset_start = allele_idx_offsets[variant_uidx];
152 allele_idx_offset_end = allele_idx_offsets[variant_uidx + 1];
153 }
154 const double cur_chisq = chisqs[aidx];
155 if (cur_chisq >= 0.0) {
156 sortbuf[valid_allele_ct].chisq = cur_chisq;
157 sortbuf[valid_allele_ct].ln_pval = ln_pvals[aidx];
158 sortbuf[valid_allele_ct].variant_uidx = variant_uidx;
159 sortbuf[valid_allele_ct].allele_idx = allele_uidx - allele_idx_offset_start;
160 ++valid_allele_ct;
161 }
162 }
163 } else {
164 for (uintptr_t aidx = 0; aidx != orig_allele_ct; ++aidx) {
165 const uintptr_t allele_uidx = BitIter1(allele_include, &allele_uidx_base, &allele_include_bits);
166 if (allele_uidx >= allele_idx_offset_end) {
167 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
168 allele_idx_offset_start = allele_idx_offsets[variant_uidx];
169 allele_idx_offset_end = allele_idx_offsets[variant_uidx + 1];
170 }
171 const double cur_chisq = chisqs[aidx];
172 if (cur_chisq >= 0.0) {
173 sortbuf[valid_allele_ct].chisq = cur_chisq;
174 sortbuf[valid_allele_ct].ln_pval = ChisqToLnP(cur_chisq, 1);
175 sortbuf[valid_allele_ct].variant_uidx = variant_uidx;
176 sortbuf[valid_allele_ct].allele_idx = allele_uidx - allele_idx_offset_start;
177 ++valid_allele_ct;
178 }
179 }
180 }
181 } else {
182 for (uintptr_t aidx = 0; aidx != orig_allele_ct; ++aidx) {
183 const uintptr_t allele_uidx = BitIter1(allele_include, &allele_uidx_base, &allele_include_bits);
184 if (allele_uidx >= allele_idx_offset_end) {
185 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
186 allele_idx_offset_start = allele_idx_offsets[variant_uidx];
187 allele_idx_offset_end = allele_idx_offsets[variant_uidx + 1];
188 }
189 const double cur_ln_pval = ln_pvals[aidx];
190 if (cur_ln_pval <= 0.0) {
191 sortbuf[valid_allele_ct].chisq = LnPToChisq(cur_ln_pval);
192 sortbuf[valid_allele_ct].ln_pval = cur_ln_pval;
193 sortbuf[valid_allele_ct].variant_uidx = variant_uidx;
194 sortbuf[valid_allele_ct].allele_idx = allele_uidx - allele_idx_offset_start;
195 ++valid_allele_ct;
196 }
197 }
198 }
199 }
200 if (!valid_allele_ct) {
201 logputs("Zero valid tests; --adjust skipped.\n");
202 goto Multcomp_ret_1;
203 }
204 BigstackShrinkTop(sortbuf, valid_allele_ct * sizeof(AdjAssocResult));
205
206 const uintptr_t overflow_buf_size = kCompressStreamBlock + 2 * kMaxIdSlen + 512 + 2 * max_allele_slen;
207 const AdjustFlags flags = adjust_info_ptr->flags;
208 const uint32_t output_zst = flags & kfAdjustZs;
209 OutnameZstSet(".adjusted", output_zst, outname_end);
210 reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
211 if (unlikely(reterr)) {
212 goto Multcomp_ret_1;
213 }
214 *cswritep++ = '#';
215 const uint32_t chr_col = flags & kfAdjustColChrom;
216 if (chr_col) {
217 cswritep = strcpya_k(cswritep, "CHROM\t");
218 }
219 if (flags & kfAdjustColPos) {
220 cswritep = strcpya_k(cswritep, "POS\t");
221 } else {
222 variant_bps = nullptr;
223 }
224 cswritep = strcpya_k(cswritep, "ID\t");
225 const uint32_t ref_col = flags & kfAdjustColRef;
226 if (ref_col) {
227 cswritep = strcpya_k(cswritep, "REF\t");
228 }
229 const uint32_t alt1_col = flags & kfAdjustColAlt1;
230 if (alt1_col) {
231 cswritep = strcpya_k(cswritep, "ALT1\t");
232 }
233 const uint32_t alt_col = flags & kfAdjustColAlt;
234 if (alt_col) {
235 cswritep = strcpya_k(cswritep, "ALT\t");
236 }
237 const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
238 const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, flags / kfAdjustColMaybeprovref, raw_variant_ct, all_nonref);
239 if (provref_col) {
240 cswritep = strcpya_k(cswritep, "PROVISIONAL_REF?\t");
241 }
242 const uint32_t a1_col = (flags & kfAdjustColA1) && (loaded_a1 || cip);
243 if (a1_col) {
244 cswritep = strcpya_k(cswritep, "A1\t");
245 }
246 const uint32_t is_neglog10 = flags & kfAdjustLog10;
247 const uint32_t unadj_col = flags & kfAdjustColUnadj;
248 if (unadj_col) {
249 if (is_neglog10) {
250 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
251 }
252 cswritep = strcpya_k(cswritep, "UNADJ\t");
253 }
254 const uint32_t gc_col = (flags & kfAdjustColGc) && (!skip_gc);
255 if (gc_col) {
256 if (is_neglog10) {
257 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
258 }
259 cswritep = strcpya_k(cswritep, "GC\t");
260 }
261 const uint32_t qq_col = flags & kfAdjustColQq;
262 if (qq_col) {
263 cswritep = strcpya_k(cswritep, "QQ\t");
264 }
265 const uint32_t bonf_col = flags & kfAdjustColBonf;
266 if (bonf_col) {
267 if (is_neglog10) {
268 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
269 }
270 cswritep = strcpya_k(cswritep, "BONF\t");
271 }
272 const uint32_t holm_col = flags & kfAdjustColHolm;
273 if (holm_col) {
274 if (is_neglog10) {
275 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
276 }
277 cswritep = strcpya_k(cswritep, "HOLM\t");
278 }
279 const uint32_t sidakss_col = flags & kfAdjustColSidakss;
280 if (sidakss_col) {
281 if (is_neglog10) {
282 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
283 }
284 cswritep = strcpya_k(cswritep, "SIDAK_SS\t");
285 }
286 const uint32_t sidaksd_col = flags & kfAdjustColSidaksd;
287 if (sidaksd_col) {
288 if (is_neglog10) {
289 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
290 }
291 cswritep = strcpya_k(cswritep, "SIDAK_SD\t");
292 }
293 const uint32_t fdrbh_col = flags & kfAdjustColFdrbh;
294 if (fdrbh_col) {
295 if (is_neglog10) {
296 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
297 }
298 cswritep = strcpya_k(cswritep, "FDR_BH\t");
299 }
300 double* ln_pv_by = nullptr;
301 if (flags & kfAdjustColFdrby) {
302 if (unlikely(bigstack_alloc_d(valid_allele_ct, &ln_pv_by))) {
303 goto Multcomp_ret_NOMEM;
304 }
305 if (is_neglog10) {
306 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
307 }
308 cswritep = strcpya_k(cswritep, "FDR_BY\t");
309 }
310 DecrAppendBinaryEoln(&cswritep);
311
312 // reverse-order calculations
313 double* ln_pv_bh;
314 double* ln_pv_gc;
315 double* unadj_sorted_ln_pvals;
316 if (unlikely(bigstack_alloc_d(valid_allele_ct, &ln_pv_bh) ||
317 bigstack_alloc_d(valid_allele_ct, &ln_pv_gc) ||
318 bigstack_alloc_d(valid_allele_ct, &unadj_sorted_ln_pvals))) {
319 goto Multcomp_ret_NOMEM;
320 }
321
322 STD_SORT_PAR_UNSEQ(valid_allele_ct, double_cmp, sortbuf);
323
324 double lambda_recip = 1.0;
325 if (!skip_gc) {
326 if (adjust_info_ptr->lambda != 0.0) {
327 lambda_recip = 1.0 / adjust_info_ptr->lambda;
328 } else {
329 const uintptr_t valid_allele_ct_d2 = valid_allele_ct / 2;
330 double lambda = sortbuf[valid_allele_ct_d2].chisq;
331 if (!(valid_allele_ct % 2)) {
332 lambda = (lambda + sortbuf[valid_allele_ct_d2 - 1].chisq) * 0.5;
333 }
334 lambda = lambda / 0.456;
335 logprintf("--adjust: Genomic inflation est. lambda (based on median chisq) = %g.\n", lambda);
336 if (lambda < 1.0) {
337 logprintf("(Treating lambda as 1 in GC-corrected p-value calculation.)\n");
338 lambda = 1.0;
339 }
340 lambda_recip = 1.0 / lambda;
341 }
342 }
343 double* sorted_ln_pvals = unadj_sorted_ln_pvals;
344 for (uintptr_t aidx = 0; aidx != valid_allele_ct; ++aidx) {
345 ln_pv_gc[aidx] = ChisqToLnP(sortbuf[aidx].chisq * lambda_recip, 1);
346 unadj_sorted_ln_pvals[aidx] = sortbuf[aidx].ln_pval;
347 }
348 if ((flags & kfAdjustGc) && (!skip_gc)) {
349 sorted_ln_pvals = ln_pv_gc;
350 }
351
352 const uint32_t valid_allele_ct_m1 = valid_allele_ct - 1;
353 const double valid_allele_ctd = swtod(valid_allele_ct);
354 const double ln_valid_allele_ct = log(valid_allele_ctd);
355 double bh_ln_pval_min = sorted_ln_pvals[valid_allele_ct_m1];
356 ln_pv_bh[valid_allele_ct_m1] = bh_ln_pval_min;
357 double harmonic_sum = 1.0;
358 for (uint32_t aidx = valid_allele_ct_m1; aidx; --aidx) {
359 const double harmonic_term = valid_allele_ctd / u31tod(aidx);
360 harmonic_sum += harmonic_term;
361 const double bh_ln_pval = sorted_ln_pvals[aidx - 1] + log(harmonic_term);
362 if (bh_ln_pval_min > bh_ln_pval) {
363 bh_ln_pval_min = bh_ln_pval;
364 }
365 ln_pv_bh[aidx - 1] = bh_ln_pval_min;
366 }
367
368 if (ln_pv_by) {
369 const double ln_harmonic_sum = log(harmonic_sum);
370 double by_ln_pval_min = sorted_ln_pvals[valid_allele_ct_m1] - ln_valid_allele_ct + ln_harmonic_sum;
371 if (by_ln_pval_min > 0.0) {
372 by_ln_pval_min = 0.0;
373 }
374 ln_pv_by[valid_allele_ct_m1] = by_ln_pval_min;
375 for (uint32_t aidx = valid_allele_ct_m1; aidx; --aidx) {
376 const double by_ln_pval = sorted_ln_pvals[aidx - 1] - log(u31tod(aidx)) + ln_harmonic_sum;
377 if (by_ln_pval_min > by_ln_pval) {
378 by_ln_pval_min = by_ln_pval;
379 }
380 ln_pv_by[aidx - 1] = by_ln_pval_min;
381 }
382 }
383
384 char output_min_p_buf[24];
385 uint32_t output_min_p_slen;
386 if (!is_neglog10) {
387 char* str_end = lntoa_g(output_min_ln, output_min_p_buf);
388 output_min_p_slen = str_end - output_min_p_buf;
389 } else {
390 // -log10(p) output ignores --output-min-p now.
391 // instead, set to maximum int32 to distinguish from plink 1.x's
392 // much-less-extreme 'inf'.
393 strcpy_k(output_min_p_buf, "2147483647");
394 output_min_p_slen = 10;
395 }
396 const double valid_allele_ct_recip = 1.0 / valid_allele_ctd;
397 double ln_pv_sidak_sd = -DBL_MAX;
398 double ln_pv_holm = -DBL_MAX;
399 uint32_t cur_allele_ct = 2;
400 uint32_t aidx = 0;
401 for (; aidx < valid_allele_ct; ++aidx) {
402 double ln_pval = sorted_ln_pvals[aidx];
403 if (ln_pval > ln_pfilter) {
404 break;
405 }
406 const uint32_t variant_uidx = sortbuf[aidx].variant_uidx;
407 if (chr_col) {
408 if (cip) {
409 cswritep = chrtoa(cip, GetVariantChr(cip, variant_uidx), cswritep);
410 } else {
411 cswritep = strcpya(cswritep, chr_ids[variant_uidx]);
412 }
413 *cswritep++ = '\t';
414 }
415 if (variant_bps) {
416 cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
417 }
418 cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
419 uintptr_t allele_idx_offset_base = variant_uidx * 2;
420 if (allele_idx_offsets) {
421 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
422 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
423 }
424 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
425 if (ref_col) {
426 *cswritep++ = '\t';
427 cswritep = strcpya(cswritep, cur_alleles[0]);
428 }
429 if (alt1_col) {
430 *cswritep++ = '\t';
431 cswritep = strcpya(cswritep, cur_alleles[1]);
432 }
433 if (alt_col) {
434 *cswritep++ = '\t';
435 for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) {
436 if (unlikely(Cswrite(&css, &cswritep))) {
437 goto Multcomp_ret_WRITE_FAIL;
438 }
439 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
440 }
441 --cswritep;
442 }
443 if (provref_col) {
444 *cswritep++ = '\t';
445 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
446 }
447 if (a1_col) {
448 *cswritep++ = '\t';
449 const char* cur_allele;
450 if (loaded_a1) {
451 // --adjust-file hack
452 cur_allele = loaded_a1[variant_uidx];
453 } else {
454 cur_allele = cur_alleles[sortbuf[aidx].allele_idx];
455 }
456 cswritep = strcpya(cswritep, cur_allele);
457 }
458 if (unadj_col) {
459 adjust_print_ln(output_min_p_buf, unadj_sorted_ln_pvals[aidx], output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
460 }
461 if (gc_col) {
462 adjust_print_ln(output_min_p_buf, ln_pv_gc[aidx], output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
463 }
464 const double aidx_d = swtod(aidx);
465 if (qq_col) {
466 *cswritep++ = '\t';
467 double qq_val = (aidx_d + 0.5) * valid_allele_ct_recip;
468 cswritep = dtoa_g(qq_val, cswritep);
469 }
470 if (bonf_col) {
471 double bonf_ln_pval = ln_pval + ln_valid_allele_ct;
472 if (bonf_ln_pval > 0.0) {
473 bonf_ln_pval = 0.0;
474 }
475 adjust_print_ln(output_min_p_buf, bonf_ln_pval, output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
476 }
477 if (holm_col) {
478 if (ln_pv_holm < 0.0) {
479 const double ln_pv_holm_new = ln_pval + log(u31tod(valid_allele_ct - aidx));
480 if (ln_pv_holm_new > 0.0) {
481 ln_pv_holm = 0.0;
482 } else if (ln_pv_holm < ln_pv_holm_new) {
483 ln_pv_holm = ln_pv_holm_new;
484 }
485 }
486 adjust_print_ln(output_min_p_buf, ln_pv_holm, output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
487 }
488 if (sidakss_col) {
489 // avoid catastrophic cancellation for small p-values
490 // 1 - (1-p)^c = 1 - e^{c log(1-p)}
491 // 2^{-7} threshold is arbitrary
492 // 2^{-90} corresponds to cp + (cp)^2/2! == cp in double-precision
493 // arithmetic, with several bits to spare
494 double ln_pv_sidak_ss;
495 if (ln_pval > -90 * kLn2) {
496 const double pval = exp(ln_pval);
497 double pv_sidak_ss;
498 if (ln_pval >= -7 * kLn2) {
499 pv_sidak_ss = 1 - pow(1 - pval, valid_allele_ctd);
500 } else {
501 pv_sidak_ss = 1 - exp(valid_allele_ctd * log1p(-pval));
502 }
503 ln_pv_sidak_ss = log(pv_sidak_ss);
504 } else {
505 // log(1-x) = -x - x^2/2 - x^3/3 + ...
506 // 1 - exp(x) = -x - x^2/2! - x^3/3! - ...
507 // if p <= 2^{-90},
508 // log(1-p) is -p
509 // 1 - e^{-cp} is cp
510 ln_pv_sidak_ss = ln_pval + ln_valid_allele_ct;
511 }
512 adjust_print_ln(output_min_p_buf, ln_pv_sidak_ss, output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
513 }
514 if (sidaksd_col) {
515 double ln_pv_sidak_sd_new;
516 if (ln_pval > -90 * kLn2) {
517 const double pval = exp(ln_pval);
518 double pv_sidak_sd_new;
519 if (ln_pval >= -7 * kLn2) {
520 pv_sidak_sd_new = 1 - pow(1 - pval, valid_allele_ctd - aidx_d);
521 } else {
522 const double cur_exp = valid_allele_ctd - aidx_d;
523 pv_sidak_sd_new = 1 - exp(cur_exp * log1p(-pval));
524 }
525 ln_pv_sidak_sd_new = log(pv_sidak_sd_new);
526 } else {
527 ln_pv_sidak_sd_new = ln_pval + log(valid_allele_ctd - aidx_d);
528 }
529 if (ln_pv_sidak_sd < ln_pv_sidak_sd_new) {
530 ln_pv_sidak_sd = ln_pv_sidak_sd_new;
531 }
532 adjust_print_ln(output_min_p_buf, ln_pv_sidak_sd, output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
533 }
534 if (fdrbh_col) {
535 adjust_print_ln(output_min_p_buf, ln_pv_bh[aidx], output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
536 }
537 if (ln_pv_by) {
538 adjust_print_ln(output_min_p_buf, ln_pv_by[aidx], output_min_ln, output_min_p_slen, is_neglog10, &cswritep);
539 }
540 AppendBinaryEoln(&cswritep);
541 if (unlikely(Cswrite(&css, &cswritep))) {
542 goto Multcomp_ret_WRITE_FAIL;
543 }
544 }
545 if (unlikely(CswriteCloseNull(&css, cswritep))) {
546 goto Multcomp_ret_WRITE_FAIL;
547 }
548 // don't use valid_allele_ct due to --pfilter
549 logprintfww("--adjust%s values (%" PRIuPTR " test%s) written to %s .\n", cip? "" : "-file", aidx, (aidx == 1)? "" : "s", outname);
550 }
551 while (0) {
552 Multcomp_ret_NOMEM:
553 reterr = kPglRetNomem;
554 break;
555 Multcomp_ret_WRITE_FAIL:
556 reterr = kPglRetWriteFail;
557 break;
558 }
559 Multcomp_ret_1:
560 CswriteCloseCond(&css, cswritep);
561 BigstackReset(bigstack_mark);
562 return reterr;
563 }
564
565 PglErr AdjustFile(const AdjustFileInfo* afip, double ln_pfilter, double output_min_ln, uint32_t max_thread_ct, char* outname, char* outname_end) {
566 unsigned char* bigstack_mark = g_bigstack_base;
567 unsigned char* bigstack_end_mark = g_bigstack_end;
568 const char* in_fname = afip->fname;
569 uintptr_t line_idx = 0;
570 PglErr reterr = kPglRetSuccess;
571 TextStream adjust_txs;
572 PreinitTextStream(&adjust_txs);
573 {
574 // Two-pass load.
575 // 1. Parse header line, count # of variants.
576 // intermission. Allocate top-level arrays.
577 // 2. Rewind and fill arrays.
578 // (some overlap with LoadPvar(), though that's one-pass.)
579 reterr = SizeAndInitTextStream(in_fname, bigstack_left() / 4, max_thread_ct, &adjust_txs);
580 if (unlikely(reterr)) {
581 goto AdjustFile_ret_TSTREAM_FAIL;
582 }
583
584 const char* header_start;
585 do {
586 ++line_idx;
587 header_start = TextGet(&adjust_txs);
588 if (unlikely(!header_start)) {
589 reterr = TextStreamRawErrcode(&adjust_txs);
590 if (reterr == kPglRetEof) {
591 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", in_fname);
592 goto AdjustFile_ret_MALFORMED_INPUT_WW;
593 }
594 goto AdjustFile_ret_TSTREAM_FAIL;
595 }
596 } while (strequal_k_unsafe(header_start, "##"));
597 if (*header_start == '#') {
598 ++header_start;
599 }
600
601 const AdjustFlags flags = afip->base.flags;
602 // [0] = CHROM
603 // [1] = POS
604 // [2] = ID (required)
605 // [3] = REF
606 // [4] = ALT
607 // [5] = PROVISIONAL_REF?
608 // [6] = A1
609 // [7] = TEST (always scan)
610 // [8] = P (required)
611 const char* col_search_order[9];
612 const uint32_t need_chr = (flags & kfAdjustColChrom);
613 const uint32_t need_pos = (flags & kfAdjustColPos);
614 const uint32_t need_ref = (flags & kfAdjustColRef);
615 const uint32_t need_alt = (flags & (kfAdjustColAlt1 | kfAdjustColAlt));
616 const uint32_t need_provref = (flags & (kfAdjustColMaybeprovref | kfAdjustColProvref));
617 uint32_t check_a1 = (flags & kfAdjustColA1);
618 const uint32_t alt_comma_truncate = (need_alt == kfAdjustColAlt1);
619 if (unlikely(need_alt == (kfAdjustColAlt1 | kfAdjustColAlt))) {
620 // Could theoretically support this later (allocate allele_idx_offsets
621 // and count # of multiallelic variants in first pass, etc.), but
622 // unlikely to be relevant.
623 // (For now, we abuse allele_storage by storing all comma-separated alt
624 // alleles in a single string, since Multcomp() is ok with that.)
625 logerrputs("Error: --adjust-file does not currently support simultaneous alt1 and alt\ncolumn output.\n");
626 goto AdjustFile_ret_INVALID_CMDLINE;
627 }
628 col_search_order[0] = need_chr? (afip->chr_field? afip->chr_field : "CHROM\0CHR\0") : "";
629 col_search_order[1] = need_pos? (afip->pos_field? afip->pos_field : "POS\0BP\0") : "";
630 col_search_order[2] = afip->id_field? afip->id_field : "ID\0SNP\0";
631 col_search_order[3] = need_ref? (afip->ref_field? afip->ref_field : "REF\0A2\0") : "";
632 col_search_order[4] = need_alt? (afip->alt_field? afip->alt_field : "ALT\0ALT1\0") : "";
633 col_search_order[5] = need_provref? (afip->provref_field? afip->provref_field : "PROVISIONAL_REF?\0") : "";
634 col_search_order[6] = check_a1? (afip->a1_field? afip->a1_field : "A1\0") : "";
635 col_search_order[7] = afip->test_field? afip->test_field : "TEST\0";
636 const uint32_t input_log10 = (flags & kfAdjustInputLog10);
637 col_search_order[8] = afip->p_field? afip->p_field : (input_log10? "LOG10_P\0NEG_LOG10_P\0LOG10_UNADJ\0NEG_LOG10_UNADJ\0P\0UNADJ\0" : "P\0UNADJ\0");
638
639 uint32_t col_skips[9];
640 uint32_t col_types[9];
641 uint32_t relevant_col_ct;
642 uint32_t found_type_bitset;
643 reterr = SearchHeaderLine(header_start, col_search_order, "--adjust-file", 9, &relevant_col_ct, &found_type_bitset, col_skips, col_types);
644 if (unlikely(reterr)) {
645 goto AdjustFile_ret_1;
646 }
647 if (unlikely((found_type_bitset & 0x104) != 0x104)) {
648 logerrputs("Error: --adjust-file requires ID and P columns.\n");
649 goto AdjustFile_ret_INCONSISTENT_INPUT;
650 }
651 const char* test_name = afip->test_name;
652 uint32_t test_name_slen = 0;
653 uint32_t test_col_idx = 0;
654 if (test_name) {
655 test_name_slen = strlen(test_name);
656 // this duplicates a bit of work done in SearchHeaderLine(), but not a
657 // big deal
658 for (uint32_t relevant_col_idx = 0; ; ++relevant_col_idx) {
659 test_col_idx += col_skips[relevant_col_idx];
660 if (col_types[relevant_col_idx] == 7) {
661 break;
662 }
663 }
664 } else if (unlikely(found_type_bitset & 0x80)) {
665 snprintf(g_logbuf, kLogbufSize, "Error: TEST column present in %s, but no test= parameter was provided to --adjust-file.\n", in_fname);
666 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
667 }
668 if (unlikely(need_chr && (!(found_type_bitset & 0x1)))) {
669 snprintf(g_logbuf, kLogbufSize, "Error: No chromosome column in %s.\n", in_fname);
670 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
671 }
672 if (unlikely(need_pos && (!(found_type_bitset & 0x2)))) {
673 snprintf(g_logbuf, kLogbufSize, "Error: No bp coordinate column in %s.\n", in_fname);
674 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
675 }
676 if (unlikely(need_ref && (!(found_type_bitset & 0x8)))) {
677 snprintf(g_logbuf, kLogbufSize, "Error: No REF column in %s.\n", in_fname);
678 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
679 }
680 if (unlikely(need_alt && (!(found_type_bitset & 0x10)))) {
681 snprintf(g_logbuf, kLogbufSize, "Error: No ALT column in %s.\n", in_fname);
682 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
683 }
684 if (unlikely(need_provref && (!(found_type_bitset & 0x20)))) {
685 snprintf(g_logbuf, kLogbufSize, "Error: No PROVISIONAL_REF? column in %s.\n", in_fname);
686 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
687 }
688 if (check_a1 && (!(found_type_bitset & 0x40))) {
689 snprintf(g_logbuf, kLogbufSize, "Warning: No A1 column in %s. Omitting from output.\n", in_fname);
690 check_a1 = 0;
691 }
692
693 uintptr_t entry_ct = 0;
694 while (1) {
695 ++line_idx;
696 const char* line_start = TextGet(&adjust_txs);
697 if (!line_start) {
698 if (likely(!TextStreamErrcode2(&adjust_txs, &reterr))) {
699 break;
700 }
701 goto AdjustFile_ret_TSTREAM_FAIL;
702 }
703 if (test_name) {
704 // Don't count different-test entries.
705 const char* test_name_start = NextTokenMult0(line_start, test_col_idx);
706 if (unlikely(!test_name_start)) {
707 goto AdjustFile_ret_MISSING_TOKENS;
708 }
709 const uint32_t cur_test_slen = strlen_se(test_name_start);
710 if ((cur_test_slen != test_name_slen) || (!memequal(test_name_start, test_name, test_name_slen))) {
711 continue;
712 }
713 }
714 ++entry_ct;
715 }
716 #ifdef __LP64__
717 // probably want to permit this soon
718 if (entry_ct > 0xffffffffU) {
719 logerrputs("Error: Too many entries for --adjust-file.\n");
720 reterr = kPglRetNotYetSupported;
721 goto AdjustFile_ret_1;
722 }
723 #endif
724
725 reterr = TextRewind(&adjust_txs);
726 if (unlikely(reterr)) {
727 goto AdjustFile_ret_TSTREAM_FAIL;
728 }
729 const uintptr_t line_ct = line_idx - 1;
730 line_idx = 0;
731 do {
732 ++line_idx;
733 reterr = TextNextLineLstripK(&adjust_txs, &header_start);
734 if (unlikely(reterr)) {
735 goto AdjustFile_ret_TSTREAM_REWIND_FAIL;
736 }
737 } while (strequal_k_unsafe(header_start, "##"));
738
739 const uintptr_t entry_ctl = BitCtToWordCt(entry_ct);
740 const uintptr_t entry_ctl2 = NypCtToWordCt(entry_ct);
741 uintptr_t* variant_include_dummy;
742 uintptr_t* allele_include_dummy;
743 if (unlikely(bigstack_alloc_w(entry_ctl, &variant_include_dummy) ||
744 bigstack_alloc_w(entry_ctl2, &allele_include_dummy))) {
745 goto AdjustFile_ret_NOMEM;
746 }
747 SetAllBits(entry_ct, variant_include_dummy);
748 for (uintptr_t ulii = 0; ulii != entry_ct / kBitsPerWordD2; ++ulii) {
749 allele_include_dummy[ulii] = kMaskAAAA;
750 }
751 const uint32_t remainder = entry_ct % kBitsPerWordD2;
752 if (remainder) {
753 allele_include_dummy[entry_ct / kBitsPerWordD2] = kMaskAAAA >> (2 * (kBitsPerWordD2 - remainder));
754 }
755 char** chr_ids;
756 if (need_chr) {
757 if (unlikely(bigstack_alloc_cp(entry_ct, &chr_ids))) {
758 goto AdjustFile_ret_NOMEM;
759 }
760 } else {
761 chr_ids = nullptr;
762 }
763 uint32_t* variant_bps;
764 if (need_pos) {
765 if (unlikely(bigstack_alloc_u32(entry_ct, &variant_bps))) {
766 goto AdjustFile_ret_NOMEM;
767 }
768 } else {
769 variant_bps = nullptr;
770 }
771 char** variant_ids;
772 double* ln_pvals;
773 if (unlikely(bigstack_alloc_cp(entry_ct, &variant_ids) ||
774 bigstack_alloc_d(entry_ct, &ln_pvals))) {
775 goto AdjustFile_ret_NOMEM;
776 }
777 char** allele_storage;
778 if (need_ref || need_alt) {
779 if (unlikely(bigstack_alloc_cp(entry_ct * 2, &allele_storage))) {
780 goto AdjustFile_ret_NOMEM;
781 }
782 } else {
783 allele_storage = nullptr;
784 }
785 uintptr_t* nonref_flags = nullptr;
786 if (need_provref) {
787 if (unlikely(bigstack_calloc_w(entry_ctl, &nonref_flags))) {
788 goto AdjustFile_ret_NOMEM;
789 }
790 }
791 char** a1_storage;
792 if (check_a1) {
793 if (unlikely(bigstack_alloc_cp(entry_ct, &a1_storage))) {
794 goto AdjustFile_ret_NOMEM;
795 }
796 } else {
797 a1_storage = nullptr;
798 }
799 unsigned char* tmp_alloc_base = g_bigstack_base;
800 unsigned char* tmp_alloc_end = BigstackEndRoundedDown();
801 uint32_t max_allele_slen = 1;
802 uintptr_t variant_idx = 0;
803 while (line_idx < line_ct) {
804 ++line_idx;
805 const char* line_start;
806 reterr = TextNextLineLstripK(&adjust_txs, &line_start);
807 if (unlikely(reterr)) {
808 goto AdjustFile_ret_TSTREAM_REWIND_FAIL;
809 }
810 const char* token_ptrs[9];
811 uint32_t token_slens[9];
812 if (unlikely(!TokenLexK0(line_start, col_types, col_skips, relevant_col_ct, token_ptrs, token_slens))) {
813 goto AdjustFile_ret_MISSING_TOKENS;
814 }
815 if (test_name) {
816 if ((token_slens[7] != test_name_slen) || (!memequal(token_ptrs[7], test_name, test_name_slen))) {
817 continue;
818 }
819 }
820 if (chr_ids) {
821 const uint32_t cur_slen = token_slens[0];
822 if (StoreStringAtBase(tmp_alloc_end, token_ptrs[0], cur_slen, &tmp_alloc_base, &(chr_ids[variant_idx]))) {
823 goto AdjustFile_ret_NOMEM;
824 }
825 }
826 if (variant_bps) {
827 if (unlikely(ScanUintDefcap(token_ptrs[1], &(variant_bps[variant_idx])))) {
828 snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx, in_fname);
829 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
830 }
831 }
832 const uint32_t id_slen = token_slens[2];
833 if (StoreStringAtBase(tmp_alloc_end, token_ptrs[2], id_slen, &tmp_alloc_base, &(variant_ids[variant_idx]))) {
834 goto AdjustFile_ret_NOMEM;
835 }
836 if (need_ref) {
837 const uint32_t cur_slen = token_slens[3];
838 if (StoreStringAtBase(tmp_alloc_end, token_ptrs[3], cur_slen, &tmp_alloc_base, &(allele_storage[2 * variant_idx]))) {
839 goto AdjustFile_ret_NOMEM;
840 }
841 }
842 if (need_alt) {
843 const char* alt_str = token_ptrs[4];
844 uint32_t cur_slen = token_slens[4];
845 if (alt_comma_truncate) {
846 const char* alt_comma = S_CAST(const char*, memchr(alt_str, ',', cur_slen));
847 if (alt_comma) {
848 cur_slen = alt_comma - alt_str;
849 }
850 }
851 if (StoreStringAtBase(tmp_alloc_end, alt_str, cur_slen, &tmp_alloc_base, &(allele_storage[2 * variant_idx + 1]))) {
852 goto AdjustFile_ret_NOMEM;
853 }
854 }
855 if (nonref_flags) {
856 const char provref_char = token_ptrs[5][0];
857 const uint32_t cur_slen = token_slens[5];
858 if ((provref_char == 'Y') && (cur_slen == 1)) {
859 SetBit(variant_idx, nonref_flags);
860 } else if (unlikely((provref_char != 'N') || (cur_slen != 1))) {
861 snprintf(g_logbuf, kLogbufSize, "Error: Invalid provref entry on line %" PRIuPTR " of %s.\n", line_idx, in_fname);
862 goto AdjustFile_ret_INCONSISTENT_INPUT_WW;
863 }
864 }
865 if (check_a1) {
866 const uint32_t cur_slen = token_slens[6];
867 if (StoreStringAtBase(tmp_alloc_end, token_ptrs[6], cur_slen, &tmp_alloc_base, &(a1_storage[variant_idx]))) {
868 goto AdjustFile_ret_NOMEM;
869 }
870 }
871 const char* pval_str = token_ptrs[8];
872 double ln_pval;
873 if (!input_log10) {
874 if (!ScantokLn(pval_str, &ln_pval)) {
875 uint32_t cur_slen;
876 AdjustFile_alphabetic_pval:
877 cur_slen = token_slens[8];
878 if (IsNanStr(pval_str, cur_slen)) {
879 ln_pval = kLnPvalError;
880 } else if (likely(strequal_k(pval_str, "INF", cur_slen) ||
881 (input_log10 && strequal_k(pval_str, "inf", cur_slen)))) {
882 // From plink 1.x, could be anything smaller than log(5e-324).
883 // Just fill with log(2.23e-308) for now.
884 ln_pval = kLnNormalMin;
885 } else {
886 goto AdjustFile_ret_INVALID_PVAL;
887 }
888 }
889 } else {
890 double neglog10_pval;
891 if (!ScantokDouble(pval_str, &neglog10_pval)) {
892 goto AdjustFile_alphabetic_pval;
893 }
894 ln_pval = neglog10_pval * (-kLn10);
895 if (unlikely(ln_pval > 0.0)) {
896 goto AdjustFile_ret_INVALID_PVAL;
897 }
898 }
899 ln_pvals[variant_idx] = ln_pval;
900 ++variant_idx;
901 }
902 BigstackEndReset(bigstack_end_mark);
903 BigstackBaseSet(tmp_alloc_base);
904 reterr = Multcomp(variant_include_dummy, nullptr, TO_CONSTCPCONSTP(chr_ids), variant_bps, TO_CONSTCPCONSTP(variant_ids), allele_include_dummy, nullptr, TO_CONSTCPCONSTP(allele_storage), nonref_flags, TO_CONSTCPCONSTP(a1_storage), &(afip->base), ln_pvals, nullptr, entry_ct, entry_ct, max_allele_slen, kfPgenGlobal0, ln_pfilter, output_min_ln, 0, max_thread_ct, outname, outname_end);
905 if (unlikely(reterr)) {
906 goto AdjustFile_ret_1;
907 }
908 }
909 while (0) {
910 AdjustFile_ret_NOMEM:
911 reterr = kPglRetNomem;
912 break;
913 AdjustFile_ret_TSTREAM_FAIL:
914 TextStreamErrPrint(in_fname, &adjust_txs);
915 break;
916 AdjustFile_ret_TSTREAM_REWIND_FAIL:
917 TextStreamErrPrintRewind(in_fname, &adjust_txs, &reterr);
918 break;
919 AdjustFile_ret_INVALID_CMDLINE:
920 reterr = kPglRetInvalidCmdline;
921 break;
922 AdjustFile_ret_MALFORMED_INPUT_WW:
923 WordWrapB(0);
924 logerrputsb();
925 reterr = kPglRetMalformedInput;
926 break;
927 AdjustFile_ret_MISSING_TOKENS:
928 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, in_fname);
929 AdjustFile_ret_INCONSISTENT_INPUT_WW:
930 WordWrapB(0);
931 logerrputsb();
932 AdjustFile_ret_INCONSISTENT_INPUT:
933 reterr = kPglRetInconsistentInput;
934 break;
935 AdjustFile_ret_INVALID_PVAL:
936 logerrprintfww("Error: Invalid p-value on line %" PRIuPTR " of %s.\n", line_idx, in_fname);
937 reterr = kPglRetInconsistentInput;
938 break;
939 }
940 AdjustFile_ret_1:
941 CleanupTextStream2(in_fname, &adjust_txs, &reterr);
942 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
943 return reterr;
944 }
945
946 #ifdef __cplusplus
947 } // namespace plink2
948 #endif