-
Notifications
You must be signed in to change notification settings - Fork 8
/
pgs.c
2515 lines (2308 loc) · 107 KB
/
pgs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* The MIT License
Copyright (C) 2022-2024 Giulio Genovese
Author: Giulio Genovese <giulio.genovese@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <float.h>
#include <time.h>
#include <unistd.h>
#include <htslib/ksort.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/vcf.h>
#include "bcftools.h"
#include "filter.h"
#include "cholmod.h"
#define PGS_VERSION "2024-09-27"
#define AVERAGE_LD_SCORE_DFLT 72.6
#define EXPECTED_RATIO_DFLT 0.6
#define MEDIAN_CHISQ 0.45493642311957283031 // qchisq(.5,1)
// this plugin is based on cholmod_updown whose documentation can be found at:
// http://github.com/DrTimothyAldenDavis/SuiteSparse/blob/dev/CHOLMOD/Modify/cholmod_updown.c
// cholmod_analyze has time complexity O(nnz(A))
// cholmod_factor has time complexity O(nnz(L))
// cholmod_updown has time complexity O(nnz(Lnew-L))
// cholmod_solve CHOLMOD_A has time complexity 4nnz(L) when simplicial
// cholmod_solve CHOLMOD_L/CHOLMOD_DLt has time complexity 2nnz(L) when simplicial
static const char *ordering_str[] = {"NATURAL", "GIVEN", "AMD", "METIS", "NESDIS", "COLAMD"};
static const char *factorization_str[] = {"simplicial", "supernodal"};
typedef struct {
int selected; // ordering methods selected
size_t fl; // flop count to perform factorization
size_t lnz; // nonzero elements in L
size_t anz; // nonzero elements in A
int is_super;
double no_effects;
double analyze_time;
double factorize_time;
double updown_solve_time;
double solve_time;
double update_bf_time;
double gemm_time;
double syrk_time;
double trsm_time;
double potrf_time;
} stats_t;
// Logic of the filters: include or exclude sites which match the filters?
#define FLT_INCLUDE 1
#define FLT_EXCLUDE 2
// http://github.com/MRCIEU/gwas-vcf-specification
#define NS 0
#define EZ 1
#define NC 2
#define ES 3
#define SE 4
#define LP 5
#define NE 6
#define GW 7
#define SIZE 8
static const char *id_str[SIZE] = {"NS", "EZ", "NC", "ES", "SE", "LP", "NE", "GW"};
static const char *desc_str[SIZE] = {
"Variant-specific number of samples/individuals with called genotypes used to test association with specified "
"trait", // NS
"Z-score provided if it was used to derive the ES and SE fields", // EZ
"Variant-specific number of cases used to estimate genetic effect (binary traits only)", // NC
"Effect size estimate relative to the alternative allele", // ES
"Standard error of effect size estimate", // SE
"-log10 p-value for effect estimate", // LP
"Variant-specific effective sample size", // NE
"Gibbs sampler weight"}; // GW
/****************************************
* FUNCTION TO COMPUTE Z FROM LOG P *
****************************************/
#define M_2PI 6.283185307179586476925286766559 /* 2*pi */
// Wichura, M. J. Algorithm AS 241: The Percentage Points of the Normal Distribution. Applied Statistics 37, 477 (1988).
// http://doi.org/10.2307/2347330 PPND16 function (algorithm AS241) http://lib.stat.cmu.edu/apstat/241
// see qnorm5() in http://github.com/wch/r-source/blob/trunk/src/nmath/qnorm.c
// see ninv() in http://github.com/statgen/METAL/blob/master/libsrc/MathStats.cpp
// this function is equivalent to qnorm(log_p, log.p = TRUE)
static double inv_log_ndist(double log_p) {
const double a0 = 3.3871328727963666080E0;
const double a1 = 1.3314166789178437745E2;
const double a2 = 1.9715909503065514427E3;
const double a3 = 1.3731693765509461125E4;
const double a4 = 4.5921953931549871457E4;
const double a5 = 6.7265770927008700853E4;
const double a6 = 3.3430575583588128105E4;
const double a7 = 2.5090809287301226727E3;
const double b1 = 4.2313330701600911252E1;
const double b2 = 6.8718700749205790830E2;
const double b3 = 5.3941960214247511077E3;
const double b4 = 2.1213794301586595867E4;
const double b5 = 3.9307895800092710610E4;
const double b6 = 2.8729085735721942674E4;
const double b7 = 5.2264952788528545610E3;
const double c0 = 1.42343711074968357734E0;
const double c1 = 4.63033784615654529590E0;
const double c2 = 5.76949722146069140550E0;
const double c3 = 3.64784832476320460504E0;
const double c4 = 1.27045825245236838258E0;
const double c5 = 2.41780725177450611770E-1;
const double c6 = 2.27238449892691845833E-2;
const double c7 = 7.74545014278341407640E-4;
const double d1 = 2.05319162663775882187E0;
const double d2 = 1.67638483018380384940E0;
const double d3 = 6.89767334985100004550E-1;
const double d4 = 1.48103976427480074590E-1;
const double d5 = 1.51986665636164571966E-2;
const double d6 = 5.47593808499534494600E-4;
const double d7 = 1.05075007164441684324E-9;
const double e0 = 6.65790464350110377720E0;
const double e1 = 5.46378491116411436990E0;
const double e2 = 1.78482653991729133580E0;
const double e3 = 2.96560571828504891230E-1;
const double e4 = 2.65321895265761230930E-2;
const double e5 = 1.24266094738807843860E-3;
const double e6 = 2.71155556874348757815E-5;
const double e7 = 2.01033439929228813265E-7;
const double f1 = 5.99832206555887937690E-1;
const double f2 = 1.36929880922735805310E-1;
const double f3 = 1.48753612908506148525E-2;
const double f4 = 7.86869131145613259100E-4;
const double f5 = 1.84631831751005468180E-5;
const double f6 = 1.42151175831644588870E-7;
const double f7 = 2.04426310338993978564E-15;
double p, q, r, x;
p = exp(log_p);
q = p - 0.5;
if (fabs(q) <= 0.425) {
r = 0.180625 - q * q;
return q * (((((((a7 * r + a6) * r + a5) * r + a4) * r + a3) * r + a2) * r + a1) * r + a0)
/ (((((((b7 * r + b6) * r + b5) * r + b4) * r + b3) * r + b2) * r + b1) * r + 1.0);
}
r = q < 0 ? sqrt(-log_p) : sqrt(-log(1.0 - p));
if (r <= 5.0) { // for p >= 1.389e−11
r -= 1.6;
x = (((((((c7 * r + c6) * r + c5) * r + c4) * r + c3) * r + c2) * r + c1) * r + c0)
/ (((((((d7 * r + d6) * r + d5) * r + d4) * r + d3) * r + d2) * r + d1) * r + 1.0);
} else if (r <= 27) { // for p >= 2.51e-317
r -= 5.0;
x = (((((((e7 * r + e6) * r + e5) * r + e4) * r + e3) * r + e2) * r + e1) * r + e0)
/ (((((((f7 * r + f6) * r + f5) * r + f4) * r + f3) * r + f2) * r + f1) * r + 1.0);
} else if (r < 6.4e8) { // improvement from Martin Maechler
double s2 = -2 * log_p; // = -2*lp = 2s
double x2 = s2 - log(M_2PI * s2); // = xs_1
if (r < 36000) {
x2 = s2 - log(M_2PI * x2) - 2 / (2 + x2); // == xs_2
if (r < 840) { // 27 < r < 840
x2 = s2 - log(M_2PI * x2) + 2 * log1p(-(1 - 1 / (4 + x2)) / (2 + x2)); // == xs_3
if (r < 109) { // 27 < r < 109
x2 = s2 - log(M_2PI * x2) + 2 * log1p(-(1 - (1 - 5 / (6 + x2)) / (4 + x2)) / (2 + x2)); // == xs_4
if (r < 55) { // 27 < r < 55
x2 = s2 - log(M_2PI * x2)
+ 2 * log1p(-(1 - (1 - (5 - 9 / (8 + x2)) / (6 + x2)) / (4 + x2)) / (2 + x2)); // == xs_5
}
}
}
}
x = sqrt(x2);
} else {
return r * M_SQRT2;
}
return q < 0 ? -x : x;
}
// this macro from ksort.h defines the function
// double ks_ksmall_double(size_t n, double arr[], size_t kk);
KSORT_INIT_GENERIC(double)
// compute the median of a vector using the ksort library (with iterator)
double get_median(const double *v, int n, int shift) {
if (n == 0) return NAN;
double *w = (double *)malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) w[i] = v[i * shift];
double ret = ks_ksmall_double((size_t)n, w, (size_t)n / 2);
if (n % 2 == 0) ret = (ret + w[n / 2 - 1]) * 0.5f;
free(w);
return ret;
}
// compute the median of a vector using the ksort library (with iterator)
double get_median2(const double *v, int n, int shift) {
if (n == 0) return NAN;
double *w = (double *)malloc(n * sizeof(double));
int i;
for (i = 0; i < n; i++) w[i] = v[i * shift] * v[i * shift];
double ret = ks_ksmall_double((size_t)n, w, (size_t)n / 2);
if (n % 2 == 0) ret = (ret + w[n / 2 - 1]) * 0.5f;
free(w);
return ret;
}
/****************************************
* BASIC SPARSE MATRIX MANIPULATION *
****************************************/
// A sparse matrix in COOrdinate format
// see http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html
typedef struct {
int i;
int j;
double x;
} coo_cell_t;
typedef struct {
int nrow;
int nnz;
int m_d;
double *d; // elements on the diagonal
int m;
coo_cell_t *cell;
} coo_matrix_t;
// Compressed Sparse Row matrix structure
// see http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html
typedef struct {
int nrow; // number of rows
double *d; // elements on the diagonal
int *p; // ptr to the row starts, length n+1
int *j; // column index, length j[nrow]
double *x; // cell values, length j[nrow]
} csr_matrix_t;
static void coo_clear(coo_matrix_t *coo) {
coo->nrow = 0;
coo->nnz = 0;
memset((void *)coo->d, 0, sizeof(double) * coo->m_d);
}
static void coo_destroy(coo_matrix_t *coo) {
free(coo->d);
free(coo->cell);
}
static void csr_destroy(csr_matrix_t *csr) {
free(csr->d);
free(csr->p);
free(csr->j);
free(csr->x);
}
static inline void append_diag(int i, double x, coo_matrix_t *coo) {
hts_expand0(double, i + 1, coo->m_d, coo->d);
coo->d[i] = x;
}
static inline void append_nnz(int i, int j, double x, coo_matrix_t *coo) {
coo->nnz++;
hts_expand(coo_cell_t, coo->nnz, coo->m, coo->cell);
coo_cell_t *cell = &coo->cell[coo->nnz - 1];
cell->i = i;
cell->j = j;
cell->x = x;
}
// see http://github.com/rgl-epfl/cholespy/blob/main/src/cholesky_solver.cpp
static inline void coo_to_csr(const coo_matrix_t *coo, csr_matrix_t *csr) {
int k;
csr->nrow = coo->nrow;
csr->d = csr->nrow ? (double *)calloc(sizeof(double), csr->nrow) : NULL;
memcpy(csr->d, coo->d, sizeof(double) * (coo->nrow > coo->m_d ? coo->m_d : coo->nrow));
csr->p = (int *)calloc(sizeof(int), csr->nrow + 1);
csr->j = (int *)malloc(sizeof(int) * coo->nnz);
csr->x = (double *)malloc(sizeof(double) * coo->nnz);
for (k = 0; k < coo->nnz; k++) csr->p[coo->cell[k].i + 1]++;
csr->p[0] = 0;
for (k = 0; k < csr->nrow; k++) csr->p[k + 1] += csr->p[k];
for (k = 0; k < coo->nnz; k++) {
int row = coo->cell[k].i;
int dst = csr->p[row];
csr->j[dst] = coo->cell[k].j;
csr->x[dst] = coo->cell[k].x;
csr->p[row]++;
}
for (k = csr->nrow; k > 0; k--) csr->p[k] = csr->p[k - 1];
csr->p[0] = 0;
}
/****************************************
* MATRIX MULTIPLICATION AND DIVISION *
****************************************/
// return P += S
static inline void add_matrix(const coo_matrix_t *S, coo_matrix_t *P) {
if (S->nrow != P->nrow) error("Error: Sigma and Precision matrix have different dimensions\n");
// add diagonal elements
int k, n = S->nrow > S->m_d ? S->m_d : S->nrow;
hts_expand0(double, n, P->m_d, P->d);
for (k = 0; k < n; k++) P->d[k] += S->d[k];
// add non-diagonal elements
for (k = 0; k < S->nnz; k++) append_nnz(S->cell[k].i, S->cell[k].j, S->cell[k].x, P);
}
// return A ./ x
static inline void matdiv(coo_matrix_t *A, double x) {
int k, n = A->nrow > A->m_d ? A->m_d : A->nrow;
for (k = 0; k < n; k++) A->d[k] /= x;
for (k = 0; k < A->nnz; k++) A->cell[k].x /= x;
}
// return A * x for square matrices with diagonal elements
static inline void sdmult(const csr_matrix_t *A, const double *x, double *y) {
int i, j;
for (i = 0; i < A->nrow; i++) {
y[i] = A->d[i] * x[i];
for (j = A->p[i]; j < A->p[i + 1]; j++) y[i] += A->x[j] * x[A->j[j]];
}
}
// return A * x for rectangular matrices without diagonal elements
static inline void rect_sdmult(const csr_matrix_t *A, const double *x, double *y) {
int i, j;
for (i = 0; i < A->nrow; i++) {
y[i] = 0.0;
for (j = A->p[i]; j < A->p[i + 1]; j++) y[i] += A->x[j] * x[A->j[j]];
}
}
// return x' * y
static inline double dot(const double *x, const double *y, int n) {
double ret = 0.0;
int i;
for (i = 0; i < n; i++) ret += x[i] * y[i];
return ret;
}
// conjugate gradient method with Jacobi preconditioner
// http://en.wikipedia.org/wiki/Conjugate_gradient_method#Example_code_in_MATLAB_/_GNU_Octave
// http://en.wikipedia.org/wiki/Preconditioner#Jacobi_(or_diagonal)_preconditioner
// http://en.wikipedia.org/wiki/Conjugate_gradient_method#The_preconditioned_conjugate_gradient_method
// alternative approach to http://github.com/awohns/ldgm/blob/main/MATLAB/precisionDivide.m
static int pcg(const csr_matrix_t *A, double *x, double tol, int jacobi) {
int i, iter, n = A->nrow;
double rsold, rsnew, tol2 = tol * tol;
double *p = (double *)malloc(sizeof(double) * n);
double *r = (double *)malloc(sizeof(double) * n);
double *Ap = (double *)malloc(sizeof(double) * n);
double *z = jacobi ? (double *)malloc(sizeof(double) * n) : r;
sdmult(A, x, Ap);
for (i = 0; i < n; i++) r[i] = x[i] - Ap[i];
if (jacobi)
for (i = 0; i < n; i++) z[i] = r[i] / A->d[i]; // Jacobi preconditioning
for (i = 0; i < n; i++) p[i] = z[i];
rsold = dot(r, z, n);
for (iter = 0; iter < n; iter++) {
sdmult(A, p, Ap);
double alpha = rsold / dot(p, Ap, n);
for (i = 0; i < n; i++) x[i] += alpha * p[i];
for (i = 0; i < n; i++) r[i] -= alpha * Ap[i];
if (jacobi)
for (i = 0; i < n; i++) z[i] = r[i] / A->d[i]; // Jacobi preconditioning
rsnew = dot(r, z, n);
if (rsnew < tol2) break;
double beta = rsnew / rsold;
for (i = 0; i < n; i++) p[i] = z[i] + beta * p[i];
rsold = rsnew;
}
free(p);
free(r);
free(Ap);
if (jacobi) free(z);
return iter;
}
// see http://github.com/awohns/ldgm/blob/main/MATLAB/precisionMultiply.m
// computes x = (P/P00)y where P = [P00, P01; P10, P11] and P/P00 is the Schur complement
// http://en.wikipedia.org/wiki/Schur_complement
static int precision_multiply(csr_matrix_t schur[][2], const double *y1, double tol, int jacobi, double *x1) {
int n0 = schur[0][0].nrow;
int n1 = schur[1][1].nrow;
double *tmp = (double *)malloc(sizeof(double) * (n0 > n1 ? n0 : n1));
rect_sdmult(&schur[0][1], y1, tmp);
int i, n_iter = pcg(&schur[0][0], tmp, tol, jacobi);
rect_sdmult(&schur[1][0], tmp, x1);
sdmult(&schur[1][1], y1, tmp);
for (i = 0; i < n1; i++) x1[i] = tmp[i] - x1[i];
free(tmp);
return n_iter;
}
/****************************************
* LDGM-VCF ROUTINES *
****************************************/
// LDGM-VCF fields
typedef struct {
int ld_node;
int n_line; // map to the location of the corresponding GWAS-VCF line, if found
double ez_deriv;
double sqrt_het; // sqrt(2pq)
double sd; // SE(beta) = 1 / (2pq) / N_eff
double ne; // effective sample size
float gw; // Gibbs weight
} row_t;
// GWAS-VCF fields
typedef struct {
int ld_node;
int aa;
bcf1_t *line;
} line_t;
typedef struct {
int imap; // map to the summary statistic sample number in the GWAS-VCF file
const char *seqname;
int ld_block;
double neff;
double mean_neff;
int row_ptr;
int n_missing;
int n_iter; // number of iterations required to perform precisionMultiply()
row_t *rows;
int m_rows;
int *node2row; // map to the location of the LDGM-VCF fields, if found
int n_node2row;
int m_node2row;
coo_matrix_t coo;
coo_matrix_t coo_schur[2][2];
int m_schur_imap;
int *schur_imap;
// statistics relevant across multiple LD blocks
double all_trace_inf;
double all_trace_non_inf;
double all_n_selected_effects;
int all_n_missing;
int all_n_non_missing;
double all_max_alpha_hat2;
double all_sum_alpha_hat2;
} ld_block_t;
static inline void ld_block_clear(ld_block_t *block) {
block->n_missing = 0;
block->n_node2row = 0;
memset((void *)block->node2row, 0, sizeof(int) * block->m_node2row);
coo_clear(&block->coo);
int k;
for (k = 0; k < 4; k++) coo_clear(&block->coo_schur[k / 2][k % 2]);
}
static inline void ld_block_destroy(ld_block_t *block) {
free(block->rows);
free(block->node2row);
coo_destroy(&block->coo);
int k;
for (k = 0; k < 4; k++) coo_destroy(&block->coo_schur[k / 2][k % 2]);
free(block->schur_imap);
}
// adapted from Petr Danecek's implementation of remove_format() in bcftools/vcfannotate.c
static void bcf_remove_format(bcf1_t *line) {
// remove all FORMAT fields
if (!(line->unpacked & BCF_UN_FMT)) bcf_unpack(line, BCF_UN_FMT);
int i;
for (i = 0; i < line->n_fmt; i++) {
bcf_fmt_t *fmt = &line->d.fmt[i];
if (fmt->p_free) {
free(fmt->p - fmt->p_off);
fmt->p_free = 0;
}
line->d.indiv_dirty = 1;
fmt->p = NULL;
}
}
// verify the GWAS-VCF file has sufficient information to compute Z-score using one of the following strategies:
// use EZ if available
// use ES/SE if available
// use -qnorm(10^-LP/2) * sign(ES) if available
// verify the GWAS-VCF file has sufficient information to compute the effective population size:
// use --sample-sizes if available
// use NE if available
// use NS/NC if available
// use NS if available
static inline void check_gwas(bcf_hdr_t *hdr, int n_sample_sizes) {
int idx, id[SIZE];
for (idx = 0; idx < SIZE; idx++) {
id[idx] = bcf_hdr_id2int(hdr, BCF_DT_ID, id_str[idx]);
if (!bcf_hdr_idinfo_exists(hdr, BCF_HL_FMT, id[idx])) id[idx] = -1;
}
if (id[EZ] < 0 && (id[ES] < 0 || (id[SE] < 0 && id[LP] < 0)))
error(
"Error: Either the FORMAT field EZ, or ES and SE, or ES and LP must be defined in the header of the "
"GWAS-VCF summary statistics file\n");
if (!n_sample_sizes && id[NE] < 0 && id[NS] < 0)
error(
"Error: Either the FORMAT field NE or NS must be defined in the header of the GWAS-VCF summary statistics "
"file\nor else effective sample sizes must be input with the --sample-sizes option\n");
}
// verify a LDGM-VCF file header is compliant
static inline void check_ldgm(bcf_hdr_t *hdr) {
static const char *info[] = {"AA", "AF", "LD_block", "LD_node", "LD_diagonal", "LD_neighbors", "LD_weights"};
int i;
for (i = 0; i < sizeof(info) / sizeof(char *); i++)
if (!bcf_hdr_idinfo_exists(hdr, BCF_HL_INFO, bcf_hdr_id2int(hdr, BCF_DT_ID, info[i])))
error("Error: The INFO field %s is not defined in the header of the LDGM-VCF precision matrix file\n",
info[i]);
}
static inline int filter_test_with_logic(filter_t *filter, bcf1_t *line, uint8_t **smpl_pass, int filter_logic) {
if (!filter) return 1;
int i, pass = filter_test(filter, line, (const uint8_t **)smpl_pass);
if (filter_logic & FLT_EXCLUDE) {
if (pass) {
pass = 0;
if (!(*smpl_pass)) return pass;
for (i = 0; i < line->n_sample; i++)
if ((*smpl_pass)[i])
(*smpl_pass)[i] = 0;
else {
(*smpl_pass)[i] = 1;
pass = 1;
}
} else {
pass = 1;
if ((*smpl_pass))
for (i = 0; i < line->n_sample; i++) (*smpl_pass)[i] = 1;
}
}
return pass;
}
static int read_ld_block(bcf_srs_t *sr, ld_block_t *blocks, int n_pops, double alpha_param, line_t **lines,
int *n_lines, int *m_lines, filter_t *filter, int filter_logic) {
int pop, idx, i, k;
int *int_arr = (int *)calloc(sizeof(int), 1);
int n_int_arr, m_int_arr = 1;
float *float_arr = NULL;
int n_float_arr, m_float_arr = 0;
bcf1_t *line = NULL;
bcf_hdr_t *hdr = NULL;
double *ez = (double *)malloc(sizeof(double) * n_pops);
double *lp = (double *)malloc(sizeof(double) * n_pops);
double *ne = (double *)malloc(sizeof(double) * n_pops);
int aa, ld_block, ld_node;
float ld_diagonal;
double af;
int block_started = 1;
int block_ended = 0;
int curr_ld_block = -1;
int ret = bcf_sr_has_line(sr, 0);
for (pop = 0; pop < n_pops; pop++) {
ret += bcf_sr_has_line(sr, 1 + pop);
ld_block_clear(&blocks[pop]);
}
do {
// populate GWAS-VCF data in temporary structures if data available
int pass = 0;
uint8_t *smpl_pass = NULL;
if (bcf_sr_has_line(sr, 0)) {
line = bcf_sr_get_line(sr, 0);
hdr = bcf_sr_get_header(sr, 0);
pass = filter_test_with_logic(filter, line, &smpl_pass, filter_logic);
}
if (pass) {
// check if the VCF line has enough information to compute the Z-score
bcf_fmt_t *fmt[SIZE];
for (idx = 0; idx < SIZE; idx++) fmt[idx] = bcf_get_fmt(hdr, line, id_str[idx]);
for (pop = 0; pop < n_pops; pop++) {
int pop_ind = blocks[pop].imap;
int ind_pass = !smpl_pass || smpl_pass[pop_ind];
double val[SIZE];
for (idx = 0; idx < SIZE; idx++)
if (ind_pass && fmt[idx] && !bcf_float_is_missing(((float *)fmt[idx]->p)[pop_ind])
&& !bcf_float_is_vector_end(((float *)fmt[idx]->p)[pop_ind]))
val[idx] = (double)((float *)fmt[idx]->p)[pop_ind];
else
val[idx] = NAN;
if (isnan(val[EZ]) && !isnan(val[ES])) {
if (!isnan(val[SE])) {
val[EZ] = val[ES] / val[SE];
} else if (!isnan(val[LP])) {
val[EZ] = -inv_log_ndist(-val[LP] * M_LN10 - M_LN2);
if (val[ES] < 0) val[EZ] = -val[EZ];
}
}
if (blocks[pop].neff) { // force effective sample size regardless of what found in the GWAS-VCF
val[NE] = blocks[pop].neff;
} else if (isnan(val[NE]) && !isnan(val[NS])) {
// compute effective sample size for binary traits
val[NE] = isnan(val[NC]) ? val[NS] : 4.0 * (val[NS] - val[NC]) * val[NC] / val[NS];
}
ez[pop] = val[EZ];
lp[pop] = val[LP];
ne[pop] = val[NE];
}
} else {
for (pop = 0; pop < n_pops; pop++) {
ez[pop] = NAN;
lp[pop] = NAN;
ne[pop] = NAN;
}
}
// load LDGM-VCF data
int save_line = 0;
for (pop = 0; pop < n_pops; pop++) {
if (!bcf_sr_has_line(sr, 1 + pop)) continue; // no line in the LDGM-VCF file
line = bcf_sr_get_line(sr, 1 + pop);
hdr = bcf_sr_get_header(sr, 1 + pop);
// load data for the VCF record while verifying compliancy with the LDGM-VCF specification
n_int_arr = bcf_get_info_int32(hdr, line, "AA", &int_arr, &m_int_arr);
if (n_int_arr != 1 || (int_arr[0] != 0 && int_arr[0] != 1))
error("Error: AA INFO field from file %s is nonconformal at %s:%" PRId64 "\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
aa = int_arr[0];
n_float_arr = bcf_get_info_float(hdr, line, "AF", &float_arr, &m_float_arr);
if (n_float_arr != 1)
error("Error: AF INFO field from file %s is nonconformal at %s:%" PRId64 "\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
af = (double)float_arr[0];
n_int_arr = bcf_get_info_int32(hdr, line, "LD_block", &int_arr, &m_int_arr);
if (n_int_arr != 1)
error("Error: LD_block INFO field from file %s is nonconformal at %s:%" PRId64 "\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
ld_block = int_arr[0];
n_int_arr = bcf_get_info_int32(hdr, line, "LD_node", &int_arr, &m_int_arr);
if (n_int_arr != 1 || int_arr[0] < 0)
error("Error: LD_node INFO field from file %s is nonconformal at %s:%" PRId64 "\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
ld_node = int_arr[0];
n_float_arr = bcf_get_info_float(hdr, line, "LD_diagonal", &float_arr, &m_float_arr);
if (n_float_arr != 1 || float_arr[0] < 1.0f)
error("Error: LD_diagonal INFO field from file %s is nonconformal at %s:%" PRId64 "\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
ld_diagonal = float_arr[0];
n_int_arr = bcf_get_info_int32(hdr, line, "LD_neighbors", &int_arr, &m_int_arr);
for (i = 0; i < n_int_arr; i++)
if (int_arr[i] <= ld_node)
error("Error: LD_neighbors INFO field from file %s is nonconformal at %s:%" PRId64 "\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
n_float_arr = bcf_get_info_float(hdr, line, "LD_weights", &float_arr, &m_float_arr);
// this currently happens, though really it should not
// for (i=0; i<n_float_arr; i++)
// if (float_arr[i] == 0.0f)
// error("Error: LD_weights INFO field is nonconformal at %s:%"PRId64"\n", bcf_seqname(hdr, line),
// (int64_t)line->pos+1);
if (n_int_arr != n_float_arr)
error("Error: arrays LD_neighbors and LD_weights from file %s have different lengths at %s:%" PRId64
"\n",
(bcf_sr_get_reader(sr, 1 + pop))->fname, bcf_seqname(hdr, line), (int64_t)line->pos + 1);
if (block_started && blocks[pop].ld_block == ld_block)
continue; // skip first line if the reader is still stuck on the previous LDGM
// skip line if the reader reached the next LDGM and stop reading more lines
if (!block_started && curr_ld_block != ld_block) {
block_ended = 1;
continue;
}
curr_ld_block = ld_block;
ld_block_t *block = &blocks[pop];
if (ld_node >= block->n_node2row) block->n_node2row = ld_node + 1;
hts_expand0(int, block->n_node2row, block->m_node2row, block->node2row);
// if not already loaded, add LDGM-VCF entry
row_t *row;
if (block->node2row[ld_node] == 0) {
hts_expand(row_t, block->coo.nrow + 1, block->m_rows, block->rows);
block->node2row[ld_node] = block->coo.nrow + 1;
row = &block->rows[block->coo.nrow];
row->ld_node = ld_node;
// flip the allele frequency if the alternate allele is the ancestral allele
row->sqrt_het = sqrt(2.0 * (double)af * (1.0 - (double)af));
row->sd = alpha_param == 0.0 ? row->sqrt_het : pow(row->sqrt_het, alpha_param + 1.0);
if (bcf_sr_has_line(sr, 0) && !isnan(ez[pop])) {
row->n_line = *n_lines + 1;
save_line = 1;
// flip the Z-score if the alternate allele is the ancestral allele
row->ez_deriv = aa ? -ez[pop] : ez[pop];
row->ne = ne[pop];
} else {
row->n_line = 0;
row->ez_deriv = NAN;
row->ne = NAN;
}
append_diag(block->coo.nrow, (double)ld_diagonal, &block->coo);
for (i = 0; i < n_int_arr; i++) {
if (float_arr[i] == 0.0f)
continue; // there should not be need for this check once they fix the LDGM precision matrices
append_nnz(ld_node, int_arr[i], (double)float_arr[i], &block->coo);
append_nnz(int_arr[i], ld_node, (double)float_arr[i], &block->coo);
}
block->coo.nrow++;
} else {
row = &block->rows[block->node2row[ld_node] - 1];
if (!row->n_line && bcf_sr_has_line(sr, 0) && !isnan(ez[pop])) {
row->n_line = *n_lines + 1;
save_line = 1;
// flip the Z-score if the alternate allele is the ancestral allele
row->ez_deriv = aa ? -ez[pop] : ez[pop];
row->ne = ne[pop];
}
}
}
if (ret > bcf_sr_has_line(sr, 0)) {
block_started = 0;
for (pop = 0; pop < n_pops; pop++) {
blocks[pop].seqname = bcf_hdr_id2name(hdr, line->rid);
blocks[pop].ld_block = curr_ld_block;
}
}
// load GWAS-VCF data if it is references in any of the LDGM-VCF structures
if (save_line) {
hts_expand0(line_t, *n_lines + 1, *m_lines, *lines);
line_t *curr_line = &(*lines)[*n_lines];
curr_line->ld_node = ld_node;
curr_line->aa = aa;
line = bcf_sr_get_line(sr, 0);
curr_line->line = bcf_dup(line);
// remove all format fields from the line
bcf_remove_format(curr_line->line);
(*n_lines)++;
}
} while (!block_ended && (ret = bcf_sr_next_line(sr)));
for (pop = 0; pop < n_pops; pop++) {
ld_block_t *block = &blocks[pop];
block->row_ptr = pop == 0 ? 0 : blocks[pop - 1].row_ptr + blocks[pop - 1].coo.nrow;
// compute number of missing rows from the summary statistics and average sample size
block->mean_neff = 0.0;
int l = 0;
for (k = 0; k < block->coo.nrow; k++) {
row_t *row = &block->rows[k];
if (row->n_line == 0)
block->n_missing++;
else if (!isnan(row->ne)) {
block->mean_neff += row->ne;
l++;
}
}
block->mean_neff /= l;
block->all_n_missing += block->n_missing;
block->all_n_non_missing += block->coo.nrow - block->n_missing;
// compress all LDGM edges so that they refer to rows rather than LD nodes
for (k = 0; k < block->coo.nnz; k++) {
coo_cell_t *cell = &block->coo.cell[k];
if (cell->j >= block->n_node2row || block->node2row[cell->j] == 0)
error(
"Error: LDGM node %d in LD_block %d from file %s lists neighbor node %d which was not observed in "
"the LDGM\n",
cell->i, block->ld_block, (bcf_sr_get_reader(sr, 1 + pop))->fname, cell->j);
cell->i = block->node2row[cell->i] - 1;
cell->j = block->node2row[cell->j] - 1;
}
}
free(int_arr);
free(float_arr);
free(ez);
free(lp);
free(ne);
return ret;
}
static void schur_split(ld_block_t *block, csr_matrix_t schur[][2]) {
int k, n0 = 0, n1 = 0;
const coo_matrix_t *coo = &block->coo;
hts_expand(int, coo->nrow, block->m_schur_imap, block->schur_imap);
// computes the sizes of P00 and P11 and add diagonal elements
for (k = 0; k < coo->nrow; k++) {
block->schur_imap[k] = block->rows[k].n_line ? n1++ : n0++;
if (k >= coo->m_d) break;
int kk = block->rows[k].n_line > 0;
append_diag(block->schur_imap[k], coo->d[k], &block->coo_schur[kk][kk]);
}
// add non-diagonal elements to P00, P01, P10, and P11
for (k = 0; k < coo->nnz; k++) {
int i = coo->cell[k].i;
int j = coo->cell[k].j;
int ii = block->rows[i].n_line > 0;
int jj = block->rows[j].n_line > 0;
append_nnz(block->schur_imap[i], block->schur_imap[j], coo->cell[k].x, &block->coo_schur[ii][jj]);
}
// convert P00, P01, P10, and P11 from COO to CSR representation
for (k = 0; k < 4; k++) {
block->coo_schur[k / 2][k % 2].nrow = k < 2 ? n0 : n1;
coo_to_csr(&block->coo_schur[k / 2][k % 2], &schur[k / 2][k % 2]);
}
}
typedef struct {
int n; // number of LD nodes available across all populations
int *ld_nodes; // list of LD nodes available across all populations
int m_ld_nodes;
int *n_pops; // number of populations with a given LD node
int m_n_pops;
int *ind2pop; // n x n_pops matrix with indexes for each LD node
int m_ind2pop;
int *ind2row; // n x n_pops matrix with indexes for each LD node
int m_ind2row;
} map_t;
static void update_map(ld_block_t *blocks, int n_pops, map_t *map) {
int pop, ld_node, max_ld_nodes = 0;
for (pop = 0; pop < n_pops; pop++) {
ld_block_t *block = &blocks[pop];
if (block->n_node2row > max_ld_nodes) max_ld_nodes = block->n_node2row;
}
map->n = 0;
for (ld_node = 0; ld_node < max_ld_nodes; ld_node++) {
int count = 0;
for (pop = 0; pop < n_pops; pop++) {
ld_block_t *block = &blocks[pop];
if (ld_node < block->n_node2row && block->node2row[ld_node]
&& block->rows[block->node2row[ld_node] - 1].n_line)
count++;
}
if (count) {
hts_expand(int, map->n + 1, map->m_ld_nodes, map->ld_nodes);
hts_expand(int, map->n + 1, map->m_n_pops, map->n_pops);
hts_expand(int, n_pops *(map->n + 1), map->m_ind2pop, map->ind2pop);
hts_expand(int, n_pops *(map->n + 1), map->m_ind2row, map->ind2row);
map->ld_nodes[map->n] = ld_node;
map->n_pops[map->n] = count;
count = 0;
for (pop = 0; pop < n_pops; pop++) {
ld_block_t *block = &blocks[pop];
if (ld_node < block->n_node2row && block->node2row[ld_node]
&& block->rows[block->node2row[ld_node] - 1].n_line) {
map->ind2pop[n_pops * map->n + count] = pop;
map->ind2row[n_pops * map->n + count] = block->row_ptr + block->node2row[ld_node] - 1;
count++;
}
}
map->n++;
}
}
}
static void make_sigma(int nrow, const map_t *map, int n_pops, const double *sd_arr, double beta_cov, double cross_corr,
coo_matrix_t *out) {
coo_clear(out);
out->nrow = nrow;
int ind, pop1, pop2;
for (ind = 0; ind < map->n; ind++) {
for (pop1 = 0; pop1 < map->n_pops[ind]; pop1++) {
int i = map->ind2row[n_pops * ind + pop1];
assert(sd_arr[i] > 0.0);
append_diag(i, beta_cov * sd_arr[i] * sd_arr[i], out);
for (pop2 = pop1 + 1; pop2 < map->n_pops[ind]; pop2++) {
int j = map->ind2row[n_pops * ind + pop2];
assert(sd_arr[j] > 0.0);
append_nnz(i, j, cross_corr * beta_cov * sd_arr[i] * sd_arr[j], out);
append_nnz(j, i, cross_corr * beta_cov * sd_arr[i] * sd_arr[j], out);
}
}
}
}
static void concatenate(const ld_block_t *blocks, int n_pops, coo_matrix_t *out) {
coo_clear(out);
out->nrow = blocks[n_pops - 1].row_ptr + blocks[n_pops - 1].coo.nrow;
hts_expand0(double, out->nrow, out->m_d, out->d);
out->nnz = 0;
int pop, k;
for (pop = 0; pop < n_pops; pop++) {
const ld_block_t *block = &blocks[pop];
const coo_matrix_t *coo = &block->coo;
memcpy(&out->d[block->row_ptr], coo->d, sizeof(double) * (coo->nrow > coo->m_d ? coo->m_d : coo->nrow));
for (k = 0; k < coo->nnz; k++)
append_nnz(block->row_ptr + coo->cell[k].i, block->row_ptr + coo->cell[k].j, coo->cell[k].x, out);
}
}
static void write_ld_block(htsFile *fh, bcf_hdr_t *hdr, line_t *lines, int n_lines, ld_block_t *blocks, int n_pops) {
float *es_arr = (float *)malloc(sizeof(float) * n_pops);
float *gw_arr = (float *)malloc(sizeof(float) * n_pops);
int k, pop;
for (k = 0; k < n_lines; k++) {
for (pop = 0; pop < n_pops; pop++) {
ld_block_t *block = &blocks[pop];
// check there is a matching row in the LDGM matrix and that the row maps to this line to avoid duplicating
// loadings
if (lines[k].ld_node >= block->n_node2row || block->node2row[lines[k].ld_node] == 0
|| block->rows[block->node2row[lines[k].ld_node] - 1].n_line - 1 != k
|| isnan(block->rows[block->node2row[lines[k].ld_node] - 1].ez_deriv)) {
bcf_float_set_missing(es_arr[pop]);
bcf_float_set_missing(gw_arr[pop]);
} else {
row_t *row = &block->rows[block->node2row[lines[k].ld_node] - 1];
double ez = lines[k].aa ? -row->ez_deriv : row->ez_deriv;
es_arr[pop] = (float)ez;
gw_arr[pop] = row->gw;
}
}
bcf_update_format_float(hdr, lines[k].line, id_str[ES], es_arr, n_pops);
bcf_update_format_float(hdr, lines[k].line, id_str[GW], gw_arr, n_pops);
if (bcf_write(fh, hdr, lines[k].line) < 0) error("Error: Unable to write to output VCF file\n");
bcf_destroy(lines[k].line);
}
free(es_arr);
free(gw_arr);
}
/****************************************
* CHOLMOD ROUTINES *
****************************************/
// this function converts a coo_matrix_t structure into a cholmod_sparse matrix structure
// it does so without using cholmod_allocate_triplet()/cholmod_triplet_to_sparse() or cholmod_allocate_sparse()
// see http://github.com/rgl-epfl/cholespy/blob/main/src/cholesky_solver.cpp
static void coo_to_cholmod_sparse(const coo_matrix_t *coo, cholmod_sparse *A) {
assert(A->nzmax >= coo->nrow + coo->nnz); // make sure enough memory was allocated
assert(A->packed); // make sure the matrix is packed
assert(A->stype < 0); // make sure the matrix is lower triangular
A->sorted = 0;
int k;
int n_d = coo->nrow > coo->m_d ? coo->m_d : coo->nrow;
int *A_colptr = (int *)A->p;
int *A_rows = (int *)A->i;
double *A_data = (double *)A->x;
// reset the matrix
for (k = 0; k <= A->ncol; k++) A_colptr[k] = 0;
for (k = 0; k < n_d; k++)
if (coo->d[k]) A_colptr[k + 1]++;
for (k = 0; k < coo->nnz; k++)
if (coo->cell[k].i > coo->cell[k].j) A_colptr[coo->cell[k].j + 1]++;
A_colptr[0] = 0;
for (k = 0; k < A->nrow; k++) A_colptr[k + 1] += A_colptr[k];
for (k = 0; k < n_d; k++)
if (coo->d[k]) {
int l = A_colptr[k];
A_rows[l] = k;
A_data[l] = coo->d[k];
A_colptr[k]++;
}
for (k = 0; k < coo->nnz; k++)
if (coo->cell[k].i > coo->cell[k].j) {