forked from JonJala/mtag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtag.py
executable file
·1572 lines (1266 loc) · 77.6 KB
/
mtag.py
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
#!/usr/bin/env python
'''
'''
from __future__ import division
from __future__ import absolute_import
import numpy as np
import pandas as pd
import scipy.optimize
import argparse
import itertools
import time
import os, re
import joblib
import sys, gzip, bz2
import logging
from argparse import Namespace
from ldsc_mod.ldscore import sumstats as sumstats_sig
from ldsc_mod.ldscore import allele_info
import mtag_munge as munge_sumstats
import warnings
warnings.filterwarnings("ignore")
__version__ = '1.0.8'
borderline = "<><><<>><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"
header ="\n"
header += borderline +"\n"
header += "<>\n"
header += "<> MTAG: Multi-trait Analysis of GWAS \n"
header += "<> Version: {}\n".format(str(__version__))
header += "<> (C) 2017 Omeed Maghzian, Raymond Walters, and Patrick Turley\n"
header += "<> Harvard University Department of Economics / Broad Institute of MIT and Harvard\n"
header += "<> GNU General Public License v3\n"
header += borderline + "\n"
header += "<> Note: It is recommended to run your own QC on the input before using this program. \n"
header += "<> Software-related correspondence: [email protected] \n"
header += "<> All other correspondence: [email protected] \n"
header += borderline +"\n"
header += "\n\n"
pd.set_option('display.max_rows', 500)
pd.set_option('display.width', 800)
pd.set_option('precision', 12)
pd.set_option('max_colwidth', 800)
pd.set_option('colheader_justify', 'left')
np.set_printoptions(linewidth=800)
np.set_printoptions(precision=3)
## General helper functions
def safely_create_folder(folder_path):
try:
os.makedirs(folder_path)
except OSError:
if not os.path.isdir(folder_path):
raise
class DisableLogger():
'''
For disabling the logging module when calling munge_sumstats
'''
def __enter__(self):
logging.disable(logging.CRITICAL)
def __exit__(self, a, b, c):
logging.disable(logging.NOTSET)
## Read / Write functions
def _read_SNPlist(file_path, SNP_index):
# TODO Add more possible ways of reading SNPlists
snplist = pd.read_csv(file_path, header=0, index_col=False)
if SNP_index not in snplist.columns:
raise ValueError("SNPlist read from {} does not include --snp_name {} in its columns.".format(file_path, SNP_index))
return pd.read_csv(file_path, header=0, index_col=False)
def _read_GWAS_sumstats(GWAS_file_name, chunksize):
'''
read GWAS summary statistics from file that is in one of the acceptable formats.
'''
# TODO read more file types
(openfunc, compression) = munge_sumstats.get_compression(GWAS_file_name)
dat_gen = pd.read_csv(GWAS_file_name, index_col=False, header=0,delim_whitespace=True, compression=compression, na_values=['.','NA'],
iterator=True, chunksize=chunksize)
dat_gen = list(dat_gen)
dat_gen_unfiltered = pd.concat(dat_gen, axis=0).reset_index(drop=True)
return dat_gen_unfiltered, dat_gen
def _read_matrix(file_path):
'''
For reading 2-dimensional matrices. These files must be in .npy form or whitespace delimited .csv files
'''
ext = file_path[-4:]
if ext == '.npy':
return np.load(file_path)
if ext == '.txt':
return np.loadtxt(file_path)
else:
raise ValueError('{} is not one of the acceptable file paths for reading in matrix-valued objects.'.format(ext))
## LDSC related functions
def sec_to_str(t):
'''Convert seconds to days:hours:minutes:seconds'''
[d, h, m, s, n] = reduce(lambda ll, b : divmod(ll[0], b) + ll[1:], [(t, 1), 60, 60, 24])
f = ''
if d > 0:
f += '{D}d:'.format(D=d)
if h > 0:
f += '{H}h:'.format(H=h)
if m > 0:
f += '{M}m:'.format(M=m)
f += '{S}s'.format(S=s)
return f
class Logger_to_Logging(object):
"""
Logger class that write uses logging module and is needed to use munge_sumstats or ldsc from the LD score package.
"""
def __init__(self):
logging.info('created Logger instance to pass through ldsc.')
super(Logger_to_Logging, self).__init__()
def log(self,x):
logging.info(x)
def _perform_munge(args, GWAS_df, GWAS_dat_gen,p):
'''
Use the modified LDSC munging to clean sumstats
'''
original_cols = GWAS_df.columns
merge_alleles = None
out = None
ignore_list = ""
if args.info_min is None:
ignore_list += "info"
a1_munge = None if args.a1_name == "a1" else args.a1_name
a2_munge = None if args.a2_name == "a2" else args.a2_name
eaf_munge = None if args.eaf_name == "freq" else args.eaf_name
p_munge = None if args.p_name == "p" else args.p_name
beta_munge = args.beta_name if args.beta_name is not None else 'beta'
z_munge = args.z_name if args.z_name is not None else 'z'
n_add = args.n_list[p] if args.n_value is not None else None
if args.use_beta_se:
argnames = Namespace(sumstats=None,N=None,N_cas=None,N_con=None,out=out,maf_min=args.maf_min_list[p], info_min =args.info_min_list[p],daner=False, no_alleles=False, merge_alleles=merge_alleles,n_min=args.n_min_list[p],chunksize=args.chunksize, snp=args.snp_name,N_col=args.n_name, N_cas_col=None, N_con_col = None, a1=a1_munge, a2=a2_munge, p=p_munge, frq=eaf_munge,signed_sumstats=beta_munge+',0', keep_beta=True, keep_se=True, info=None,info_list=None, nstudy=None,nstudy_min=None,ignore=ignore_list,a1_inc=False, keep_maf=True, daner_n=False, keep_str_ambig=True, input_datgen=GWAS_dat_gen, cnames=list(original_cols), n_value=n_add)
else:
argnames = Namespace(sumstats=None,N=None,N_cas=None,N_con=None,out=out,maf_min=args.maf_min_list[p], info_min =args.info_min_list[p],daner=False, no_alleles=False, merge_alleles=merge_alleles,n_min=args.n_min_list[p],chunksize=args.chunksize, snp=args.snp_name,N_col=args.n_name, N_cas_col=None, N_con_col = None, a1=a1_munge, a2=a2_munge, p=p_munge,frq=eaf_munge,signed_sumstats=z_munge+',0', keep_beta=False, keep_se=False, info=None,info_list=None, nstudy=None,nstudy_min=None,ignore=ignore_list,a1_inc=False, keep_maf=True, daner_n=False, keep_str_ambig=True, input_datgen=GWAS_dat_gen, cnames=list(original_cols), n_value=n_add)
logging.info(borderline)
logging.info('Munging Trait {} {}'.format(p+1,borderline[:-17]))
logging.info(borderline)
munged_results = munge_sumstats.munge_sumstats(argnames, write_out=False, new_log=False)
GWAS_df = GWAS_df.merge(munged_results, how='inner',left_on =args.snp_name,right_on='SNP',suffixes=('','_ss'))
if args.n_value is not None:
GWAS_df = GWAS_df[list(original_cols) + ["N"]]
else:
GWAS_df = GWAS_df[original_cols]
logging.info(borderline)
logging.info('Munging of Trait {} complete. SNPs remaining:\t {}'.format(p+1, len(GWAS_df)))
logging.info(borderline+'\n')
return GWAS_df, munged_results
def _quick_mode(ndarray,axis=0):
'''
From stackoverflow: Efficient calculation of the mode of an array. Scipy.stats.mode is way too slow
'''
if ndarray.size == 1:
return (ndarray[0],1)
elif ndarray.size == 0:
raise Exception('Attempted to find mode on an empty array!')
try:
axis = [i for i in range(ndarray.ndim)][axis]
except IndexError:
raise Exception('Axis %i out of range for array with %i dimension(s)' % (axis,ndarray.ndim))
srt = np.sort(ndarray, axis=axis)
dif = np.diff(srt, axis=axis)
shape = [i for i in dif.shape]
shape[axis] += 2
indices = np.indices(shape)[axis]
index = tuple([slice(None) if i != axis else slice(1,-1) for i in range(dif.ndim)])
indices[index][dif == 0] = 0
indices.sort(axis=axis)
bins = np.diff(indices, axis=axis)
location = np.argmax(bins, axis=axis)
mesh = np.indices(bins.shape)
index = tuple([slice(None) if i != axis else 0 for i in range(dif.ndim)])
index = [mesh[i][index].ravel() if i != axis else location.ravel() for i in range(bins.ndim)]
counts = bins[tuple(index)].reshape(location.shape)
index[axis] = indices[tuple(index)]
modals = srt[tuple(index)].reshape(location.shape)
return (modals, counts)
def set_default_cnames(args):
return{args.snp_name: 'SNP',
args.z_name: 'Z',
args.n_name: 'N',
args.beta_name: 'BETA',
args.se_name: 'SE',
args.eaf_name: 'FRQ',
args.chr_name: 'CHR',
args.bpos_name: 'BP',
args.a1_name: 'A1',
args.a2_name: 'A2',
args.p_name: "P"}
def load_and_merge_data(args):
'''
Parses file names from MTAG command line arguments and returns the relevant used for method.
The output DATA has internal column names!
'''
#=====================
# Parse inputs + filters
#=====================
GWAS_input_files = args.sumstats.split(',')
P = len(GWAS_input_files) # of phenotypes/traits
if args.n_min is not None:
args.n_min_list = [float(x) for x in args.n_min.split(',')]
if len(args.n_min_list) == 1:
args.n_min_list = args.n_min_list * P
else:
args.n_min_list = [None]*P
if args.maf_min is not None:
args.maf_min_list = [float(x) for x in args.maf_min.split(',')]
if len(args.maf_min_list) == 1:
args.maf_min_list = args.maf_min_list * P
else:
args.maf_min_list = [None]*P
if args.info_min is not None:
args.info_min_list = [float(x) for x in args.info_min.split(',')]
if len(args.info_min_list) == 1:
args.info_min_list = args.info_min_list * P
else:
args.info_min_list = [None]*P
if args.n_value is not None:
args.n_list = [int(x) for x in args.n_value.split(',')]
assert P == len(args.n_list), "Mismatch of length of --n_value and number of summary statistics."
#=====================
# Reading sumstats
#=====================
GWAS_d = dict()
sumstats_format = dict()
for p, GWAS_input in enumerate(GWAS_input_files):
# read sumstats and add suffix
GWAS_d[p], gwas_dat_gen = _read_GWAS_sumstats(GWAS_input, args.chunksize)
logging.info('Read in Trait {} summary statistics ({} SNPs) from {} ...'.format(p+1,len(GWAS_d[p]), GWAS_input))
# perform munge sumstats
GWAS_d[p], sumstats_format[p] = _perform_munge(args, GWAS_d[p], gwas_dat_gen, p)
# generate Z checker:
if args.use_beta_se:
GWAS_d[p]['Z'] = GWAS_d[p][args.beta_name] / GWAS_d[p][args.se_name]
z_checker = np.mean(np.square(GWAS_d[p]['Z']))
else:
z_checker = np.mean(np.square(GWAS_d[p][args.z_name]))
# checker of chi2 --> error if sumstats has very low chi2
if z_checker < 1.02 and not args.force:
raise ValueError("The mean chi2 statistic of trait {} is less than 1.02, which may lead to unstable estimates. To perform MTAG on your results anyways, include the --force option, though the estimates should be interpreted cautiously.".format(p+1))
# conform column names internally
else:
if z_checker < 1.02:
logging.info("Warning: The mean chi2 statistic of trait {} is less 1.02 - MTAG estimates may be unstable.".format(p+1))
GWAS_d[p].rename(columns=munge_sumstats.set_default_cnames(args), inplace=True)
GWAS_d[p].rename(columns=set_default_cnames(args), inplace=True)
GWAS_d[p] = GWAS_d[p].add_suffix(p)
# flag inconsistency change
if args.info_min_list[p] is not None and "INFO{}".format(p) not in GWAS_d[p].columns:
raise IOError("--info_min is specified but info column is not present in sumstats {}".format(p+1))
if args.maf_min_list[p] is not None and "FRQ{}".format(p) not in GWAS_d[p].columns:
raise IOError("--maf_min is specified but maf column is not present in sumstats {}".format(p+1))
if args.n_min_list[p] is not None and "N{}".format(p) not in GWAS_d[p].columns:
raise IOError("--n_min is specified but n column is not present in sumstats {}".format(p+1))
# convert Alleles to uppercase
for col in [col+str(p) for col in ['A1','A2']]:
GWAS_d[p][col] = GWAS_d[p][col].str.upper()
GWAS_d[p] = GWAS_d[p].rename(columns={x+str(p):x for x in GWAS_d[p].columns})
GWAS_d[p] = GWAS_d[p].rename(columns={'SNP'+str(p):'SNP'})
# Drop SNPs that are missing
missing_snps = GWAS_d[p]['SNP'].isin(['NA','.'])
M0 = len(GWAS_d[p])
GWAS_d[p] = GWAS_d[p][np.logical_not(missing_snps)]
if M0-len(GWAS_d[p]) > 0:
logging.info('Trait {}: Dropped {} SNPs for missing values in the "snp_name" column'.format(p+1, M0-len(GWAS_d[p])))
# Drop snps that are duplicated
M0 = len(GWAS_d[p])
GWAS_d[p] = GWAS_d[p].drop_duplicates(subset='SNP', keep='first')
if M0-len(GWAS_d[p]) > 0:
logging.info('Trait {}: Dropped {} SNPs for duplicate values in the "snp_name" column'.format(p+1, M0-len(GWAS_d[p])))
#=====================
# merge sumstats
# intersection/union
#=====================
for p in range(P):
if p == 0:
GWAS_all = GWAS_d[p]
GWAS_int = GWAS_all.copy()
if args.meta_format:
GWAS_all['Trait0'] = 1
else:
if args.meta_format:
# add trait tags for all SNPs if meta
GWAS_all = GWAS_all.merge(GWAS_d[p], how='outer', on='SNP', indicator=True)
GWAS_all.loc[np.logical_or(GWAS_all._merge=='both',GWAS_all._merge=='right_only'),'Trait{}'.format(p)] = 1
GWAS_all.loc[GWAS_all._merge=='left_only','Trait{}'.format(p)] = 0
GWAS_all.loc[GWAS_all._merge=='right_only', 'Trait{}'.format(p-1)] = 0
GWAS_all.drop(['_merge'], axis=1, inplace=True)
# intersection only
GWAS_int = GWAS_int.merge(GWAS_d[p], how='inner', on='SNP')
M_0 = len(GWAS_int)
snps_to_flip = np.logical_and(GWAS_int['A1'+str(0)] == GWAS_int['A2'+str(p)], GWAS_int['A2'+str(0)] == GWAS_int['A1'+str(p)])
GWAS_int['flip_snps'+str(p)]= snps_to_flip
snps_to_keep = np.logical_or(np.logical_and(GWAS_int['A1'+str(0)]==GWAS_int['A1'+str(p)], GWAS_int['A2'+str(0)]==GWAS_int['A2'+str(p)]), snps_to_flip)
GWAS_int = GWAS_int[snps_to_keep]
if len(GWAS_int) < M_0:
logging.info('Dropped {} SNPs due to inconsistent allele pairs from phenotype {}. {} SNPs remain.'.format(M_0 - len(GWAS_int),p+1, len(GWAS_int)))
if np.sum(snps_to_flip) > 0:
zz = 'Z'
freq_name = 'FRQ'
GWAS_int.loc[snps_to_flip, zz+str(p)] = -1*GWAS_int.loc[snps_to_flip, zz+str(p)]
GWAS_int.loc[snps_to_flip, freq_name + str(p)] = 1. - GWAS_int.loc[snps_to_flip, freq_name + str(p)]
store_allele = GWAS_int.loc[snps_to_flip, 'A1'+str(p)]
GWAS_int.loc[snps_to_flip, 'A1'+str(p)] = GWAS_int.loc[snps_to_flip, 'A2'+str(p)]
GWAS_int.loc[snps_to_flip, 'A2'+str(p)] = store_allele
logging.info('Flipped the signs of of {} SNPs to make them consistent with the effect allele orderings of the first trait.'.format(np.sum(snps_to_flip)))
STRAND_AMBIGUOUS_SET = [x for x in allele_info.STRAND_AMBIGUOUS.keys() if allele_info.STRAND_AMBIGUOUS[x]]
GWAS_int['strand_ambig'] = (GWAS_int['A1'+str(0)].str.upper() + GWAS_int['A2'+str(0)].str.upper()).isin(STRAND_AMBIGUOUS_SET)
if not args.incld_ambig_snps:
M_0 = len(GWAS_int)
GWAS_int = GWAS_int[np.logical_not(GWAS_int['strand_ambig'])]
logging.info('Dropped {} SNPs due to strand ambiguity, {} SNPs remain in intersection after merging trait{}'.format(M_0-len(GWAS_int),len(GWAS_int), p+1))
else:
logging.info('{} strand ambiguous SNPs in Trait {} are included.'.format(np.sum(GWAS_int['strand_ambig']), p+1))
logging.info('... Merge of GWAS summary statistics complete. Number of SNPs:\t {}'.format(len(GWAS_int)))
GWAS_orig_cols = GWAS_all.columns
## Parses include files
if args.include is not None:
for j, include_file in enumerate(args.include.split(',')):
if j == 0:
snps_include = _read_SNPlist(include_file, 'SNP')
else:
snps_include = snps_include.merge(_read_SNPlist(include_file,'SNP'),how='outer', on='SNP')
GWAS_all = GWAS_all.merge(snps_include, how="left", on = 'SNP', indicator="included_merge", suffixes=('','_incl'))
GWAS_all = GWAS_all.loc[GWAS_all['included_merge']=='both']
GWAS_all = GWAS_all.loc[:,GWAS_orig_cols]
logging.info('(--include) Number of SNPs remaining after restricting to SNPs in the union of {include_path}: \t {M} remain'.format(include_path=args.include,M=len(GWAS_all)))
## Parses exclude files
if args.exclude is not None:
for exclude_file in args.exclude.split(','):
snps_exclude = _read_SNPlist(exclude_file, 'SNP')
GWAS_all = GWAS_all.merge(snps_exclude, how="left", on = 'SNP', indicator="excluded_merge", suffixes=('','_incl'))
GWAS_all = GWAS_all.loc[GWAS_all['excluded_merge']=='left_only']
GWAS_all = GWAS_all.loc[:,GWAS_orig_cols]
logging.info('(-exclude) Number of SNPs remaining after excluding to SNPs in {exclude_path}: \t {M} remain'.format(exclude_path=exclude_file,M=len(GWAS_all)))
## Parse chromosomes
if args.only_chr is not None and not args.no_chr_data:
chr_toInclude = args.only_chr.split(',')
chr_toInclude = [int(c) for c in chr_toInclude]
GWAS_all = GWAS_all[GWAS_all['CHR'+str(0)].isin(chr_toInclude)]
## conform GWAS_int back to intersection
GWAS_int = GWAS_int.merge(GWAS_all[['SNP']],how='inner',on='SNP')
## add information to Namespace
args.P = P
return GWAS_all, GWAS_int, args
def ldsc_matrix_formatter(result_rg, output_var):
'''
Key Arguments:
result_rg - matrix w/ RG objects obtained from estimate_rg (w/ None's on the diagonal)
output_var - interested variable in the form of '.[VAR_NAME]'
'''
output_mat = np.empty_like(result_rg, dtype=float)
(nrow, ncol) = result_rg.shape
for i in range(nrow):
for j in range(ncol):
if result_rg[i, j] is None:
output_mat[i, j] = None
else:
exec('output_mat[i, j] = result_rg[i, j]{}'.format(output_var))
return(output_mat)
def estimate_sigma(data_df, args):
sigma_hat = np.empty((args.P,args.P))
args.munge_out = args.out+'_ldsc_temp/'
# Creates data files for munging
# Munge data
ignore_list = ""
if args.info_min is None:
ignore_list += "info"
gwas_ss_df = dict()
for p in range(args.P):
logging.info('Preparing phenotype {} to estimate sigma'.format(p))
ld_ss_name = {'SNP':'SNP',
'A1' + str(p): 'A1',
'A2' + str(p): 'A2',
'Z' + str(p): 'Z',
'N' + str(p): 'N',
'FRQ' + str(p): 'FRQ'}
if args.use_beta_se:
ld_ss_name['BETA' + str(p)] = 'BETA'
ld_ss_name['SE' + str(p)] = 'SE'
gwas_ss_df[p] = data_df[ld_ss_name.keys()].copy()
gwas_ss_df[p] = gwas_ss_df[p].rename(columns=ld_ss_name)
# run ldsc
h2_files = None
rg_files = args.sumstats
rg_out = '{}_rg_misc'.format(args.out)
rg_mat = True
args_ldsc_rg = Namespace(out=rg_out, bfile=None,l2=None,extract=None,keep=None, ld_wind_snps=None,ld_wind_kb=None, ld_wind_cm=None,print_snps=None, annot=None,thin_annot=False,cts_bin=None, cts_break=None,cts_names=None, per_allele=False, pq_exp=None, no_print_annot=False,maf=None,h2=h2_files, rg=rg_files,ref_ld=None,ref_ld_chr=args.ld_ref_panel, w_ld=None,w_ld_chr=args.ld_ref_panel,overlap_annot=False,no_intercept=False, intercept_h2=None, intercept_gencov=None,M=None,two_step=None, chisq_max=None,print_cov=False,print_delete_vals=False,chunk_size=50, pickle=False,invert_anyway=False,yes_really=False,n_blocks=200,not_M_5_50=False,return_silly_things=False,no_check_alleles=False,print_coefficients=False,samp_prev=None,pop_prev=None, frqfile=None, h2_cts=None, frqfile_chr=None,print_all_cts=False, sumstats_frames=[ gwas_ss_df[i] for i in range(args.P)], rg_mat=rg_mat)
if args.no_overlap:
sigma_hat = np.zeros((args.P, args.P))
for t in range(args.P):
args_ldsc_rg.sumstats_frames = [gwas_ss_df[t]]
rg_results_t = sumstats_sig.estimate_rg(args_ldsc_rg, Logger_to_Logging())
sigma_hat[t,t] = ldsc_matrix_formatter(rg_results_t, '.gencov.intercept')[0]
else:
rg_results = sumstats_sig.estimate_rg(args_ldsc_rg, Logger_to_Logging())
sigma_hat = ldsc_matrix_formatter(rg_results, '.gencov.intercept')
# if args.no_overlap:
# T = sigma_hat.shape[0]
# sigma_hat = sigma_hat * np.eye(T)
# logging.info(type(sigma_hat))
logging.info(sigma_hat)
return sigma_hat
def _posDef_adjustment(mat, scaling_factor=0.99,max_it=1000):
'''
Checks whether the provided is pos semidefinite. If it is not, then it performs the the adjustment procedure descried in 1.2.2 of the Supplementary Note
scaling_factor: the multiplicative factor that all off-diagonal elements of the matrix are scaled by in the second step of the procedure.
max_it: max number of iterations set so that
'''
logging.info('Checking for positive definiteness ..')
assert mat.ndim == 2
assert mat.shape[0] == mat.shape[1]
is_pos_semidef = lambda m: np.all(np.linalg.eigvals(m) >= 0)
if is_pos_semidef(mat):
return mat
else:
logging.info('matrix is not positive definite, performing adjustment..')
P = mat.shape[0]
for i in range(P):
for j in range(i,P):
if np.abs(mat[i,j]) > np.sqrt(mat[i,i] * mat[j,j]):
mat[i,j] = scaling_factor*np.sign(mat[i,j])*np.sqrt(mat[i,i] * mat[j,j])
mat[j,i] = mat[i,j]
n=0
while not is_pos_semidef(mat) and n < max_it:
dg = np.diag(mat)
mat = scaling_factor * mat
mat[np.diag_indices(P)] = dg
n += 1
if n == max_it:
logging.info('Warning: max number of iterations reached in adjustment procedure. Sigma matrix used is still non-positive-definite.')
else:
logging.info('Completed in {} iterations'.format(n))
return mat
def extract_gwas_sumstats(DATA, args, t0):
'''
Output:
-------
All matrices are of the shape MxP, where M is the number of SNPs used in MTAG and P is the number of summary statistics results used. Columns are ordered according to the initial ordering of GWAS input files.
results_template = pd.Dataframe of snp_name chr bpos a1 a2
Zs: matrix of Z scores
Ns: matrix of sample sizes
Fs: matrix of allele frequencies
'''
n_cols = ['N' +str(p) for p in t0]
Ns = DATA.filter(items=n_cols).as_matrix()
# Apply sample-size specific filters
N_passFilter = np.ones(len(Ns), dtype=bool)
N_nearMode = np.ones_like(Ns, dtype=bool)
if args.homogNs_frac is not None or args.homogNs_dist is not None:
N_modes, _ = _quick_mode(Ns)
assert len(N_modes) == Ns.shape[1]
if args.homogNs_frac is not None:
logging.info('--homogNs_frac {} is on, filtering SNPs ...'.format(args.homogNs_frac))
assert args.homogNs_frac >= 0.
homogNs_frac_list = [float(x) for x in args.homogNs_frac.split(',')]
if len(homogNs_frac_list) == 1:
homogNs_frac_list = homogNs_frac_list*args.P
for p in t0:
N_nearMode[:,p] = np.abs((Ns[:,p] - N_modes[p])) / N_modes[p] <= homogNs_frac_list[p]
elif args.homogNs_dist is not None:
logging.info('--homogNs_dist {} is on, filtering SNPs ...'.format(args.homogNs_dist))
homogNs_dist_list = [float(x) for x in args.homogNs_dist.split(',')]
if len(homogNs_dist_list) == 1:
homogNs_dist_list = homogNs_dist_list*args.P
assert np.all(np.array(homogNs_dist_list) >=0)
for p in t0:
N_nearMode[:,p] = np.abs(Ns[:,p] - N_modes[p]) <= homogNs_dist_list[p]
else:
raise ValueError('Cannot specify both --homogNs_frac and --homogNs_dist at the same time.')
# report restrictions
mode_restrictions = 'Sample size restrictions close to mode:\n'
for p in range(Ns.shape[1]):
mode_restrictions +="Phenotype {}: \t {} SNPs pass modal sample size filter \n".format(p+1,np.sum(N_nearMode[:,p]))
mode_restrictions+="Intersection of SNPs that pass modal sample size filter for all traits:\t {}".format(np.sum(np.all(N_nearMode, axis=1)))
logging.info(mode_restrictions)
N_passFilter = np.logical_and(N_passFilter, np.all(N_nearMode,axis=1))
if args.n_max is not None:
n_max_restrictions = "--n_max used, removing SNPs with sample size greater than {}".format(args.n_max)
N_passMax = Ns <= args.n_max
for p in range(Ns.shape[1]):
n_max_restrictions += "Phenotype {}: \t {} SNPs pass modal sample size filter".format(p+1,np.sum(N_passMax[:,p]))
n_max_restrictions += "Intersection of SNPs that pass maximum sample size filter for all traits:\t {}".format(np.sum(np.all(N_passMax, axis=1)))
logging.info(n_max_restrictions)
N_passFilter = np.logical_and(N_passFilter, np.all(N_passMax,axis=1))
Ns = Ns[N_passFilter]
DATA = DATA[N_passFilter].reset_index()
N_raw = np.copy(Ns)
f_cols = ['FRQ'+ str(p) for p in t0]
Fs = DATA.filter(items=f_cols).as_matrix()
if args.use_beta_se:
beta_cols = ['BETA'+str(p) for p in t0]
se_cols = ['SE'+str(p) for p in t0]
BETAs = DATA.filter(items=beta_cols).as_matrix()
SEs = DATA.filter(items=se_cols).as_matrix()
# standardizing factor
std_factor = np.sqrt(2*Fs*(1-Fs))
Zs = BETAs / SEs
SEs = np.multiply(SEs, std_factor)
Ns = 1 / np.square(SEs)
else:
z_cols = ['Z'+str(p) for p in t0]
Zs = DATA.filter(items=z_cols).as_matrix()
assert Zs.shape[1] == Ns.shape[1] == Fs.shape[1]
results_template = DATA[['SNP']].copy()
if args.no_chr_data:
for col in ['A1','A2']:
results_template.loc[:,col] = DATA[col+str(t0[0])]
else:
for col in ['CHR','BP','A1','A2']:
results_template.loc[:,col] = DATA[col+str(t0[0])]
# TODO: non-error form of integer conversion
# results_template[args.chr_name] = results_template[args.chr_name].astype(int)
# results_template[args.bpos_name] = results_template[args.bpos_name].astype(int)
return Zs, Ns, Fs, results_template, DATA, N_raw
###########################################
## OMEGA ESTIMATION
##########################################
def jointEffect_probability(Z_score, omega_hat, sigma_hat,N_mats, S=None):
''' For each SNP m in each state s , computes the evaluates the multivariate normal distribution at the observed row of Z-scores
Calculate the distribution of (Z_m | s ) for all s in S, m in M. --> M x|S| matrix
The output is a M x n_S matrix of joint probabilities
'''
DTYPE = np.float64
(M,P) = Z_score.shape
if S is None: # 2D dimensional form
assert omega_hat.ndim == 2
omega_hat = omega_hat.reshape(1,P,P)
S = np.ones((1,P),dtype=bool)
(n_S,_) = S.shape
jointProbs = np.empty((M,n_S))
xRinvs = np.zeros([M,n_S,P], dtype=DTYPE)
logSqrtDetSigmas = np.zeros([M,n_S], dtype=DTYPE)
Ls = np.zeros([M,n_S,P,P], dtype=DTYPE)
cov_s = np.zeros([M,n_S,P,P], dtype=DTYPE)
Zs_rep = np.einsum('mp,s->msp',Z_score,np.ones(n_S)) # functionally equivalent to repmat
cov_s = np.einsum('mpq,spq->mspq',N_mats,omega_hat) + sigma_hat
Ls = np.linalg.cholesky(cov_s)
Rs = np.transpose(Ls, axes=(0,1,3,2))
xRinvs = np.linalg.solve(Ls, Zs_rep)
logSqrtDetSigmas = np.sum(np.log(np.diagonal(Rs,axis1=2,axis2=3)),axis=2).reshape(M,n_S)
quadforms = np.sum(xRinvs**2,axis=2).reshape(M,n_S)
jointProbs = np.exp(-0.5 * quadforms - logSqrtDetSigmas - P * np.log(2 * np.pi) / 2)
if n_S == 1:
jointProbs = jointProbs.flatten()
return jointProbs
def gmm_omega(Zs, Ns, sigma_LD):
logging.info('Using GMM estimator of Omega ..')
N_mats = np.sqrt(np.einsum('mp,mq->mpq', Ns,Ns))
Z_outer = np.einsum('mp,mq->mpq',Zs, Zs)
return np.mean((Z_outer - sigma_LD) / N_mats, axis=0)
def numerical_omega(args, Zs,N_mats,sigma_LD,omega_start):
M,P = Zs.shape
solver_options = dict()
solver_options['fatol'] = 1.0e-8
solver_options['xatol'] = args.tol
solver_options['disp'] = False
solver_options['maxiter'] = P*250 if args.perfect_gencov else P*(P+1)*500
if args.perfect_gencov:
x_start = np.log(np.diag(omega_start))
else:
x_start = flatten_out_omega(omega_start)
opt_results = scipy.optimize.minimize(_omega_neglogL,x_start,args=(Zs,N_mats,sigma_LD,args),method='Nelder-Mead',options=solver_options)
if args.perfect_gencov:
return np.sqrt(np.outer(np.exp(opt_results.x), np.exp(opt_results.x))), opt_results
else:
return rebuild_omega(opt_results.x), opt_results
def _omega_neglogL(x,Zs,N_mats,sigma_LD,args):
if args.perfect_gencov:
omega_it = np.sqrt(np.outer(np.exp(x),np.exp(x)))
else:
omega_it = rebuild_omega(x)
joint_prob = jointEffect_probability(Zs,omega_it,sigma_LD,N_mats)
return - np.sum(np.log(joint_prob))
def flatten_out_omega(omega_est):
# stacks the lower part of the cholesky decomposition ROW_WISE [(0,0) (1,0) (1,1) (2,0) (2,1) (2,2) ...]
P_c = len(omega_est)
x_chol = np.linalg.cholesky(omega_est)
# transform components of cholesky decomposition for better optimization
lowTr_ind = np.tril_indices(P_c)
x_chol_trf = np.zeros((P_c,P_c))
for i in range(P_c):
for j in range(i): # fill in lower triangular components not on diagonal
x_chol_trf[i,j] = x_chol[i,j]/np.sqrt(x_chol[i,i]*x_chol[j,j])
x_chol_trf[np.diag_indices(P_c)] = np.log(np.diag(x_chol)) # replace with log transformation on the diagonal
return tuple(x_chol_trf[lowTr_ind])
def rebuild_omega(chol_elems, s=None):
'''Rebuild state-dependent Omega given combination of causal states
cholX_elements are the elements (entered row-wise) of the lower triangular cholesky decomposition of Omega_s
'''
if s is None:
P = int((-1 + np.sqrt(1.+ 8.*len(chol_elems)))/2.)
s = np.ones(P,dtype=bool)
P_c = P
else:
P_c = int(np.sum(s))
P = s.shape[1] if s.ndim == 2 else len(s)
cholL = np.zeros((P_c,P_c))
cholL[np.tril_indices(P_c)] = np.array(chol_elems)
cholL[np.diag_indices(P_c)] = np.exp(np.diag(cholL)) # exponentiate the diagnoal so cholL unique
for i in range(P_c):
for j in range(i): # multiply by exponentiated diags
cholL[i,j] = cholL[i,j]*np.sqrt(cholL[i,i]*cholL[j,j])
omega_c = np.dot(cholL, cholL.T)
# Expand to include zeros of matrix
omega = np.zeros((P,P))
s_caus_ind = np.argwhere(np.outer(s, s))
omega[(s_caus_ind[:,0],s_caus_ind[:,1])] = omega_c.flatten()
return omega
def estimate_omega(args,Zs,Ns,sigma_LD, omega_in=None):
# start_time =time.time()
logging.info('Beginning estimation of Omega ...')
M,P = Zs.shape
N_mats = np.sqrt(np.einsum('mp, mq -> mpq',Ns, Ns))
if args.perfect_gencov and args.equal_h2:
logging.info('--perfect_gencov and --equal_h2 option used')
return np.ones((P,P))
if args.numerical_omega:
if omega_in is None: # omega_in serves as starting point
omega_in = np.zeros((P,P))
omega_in[np.diag_indices(P)] = np.diag(gmm_omega(Zs,Ns,sigma_LD))
omega_hat = omega_in
omega_hat, opt_results = numerical_omega(args, Zs,N_mats, sigma_LD,omega_hat)
numerical_msg = "\n Numerical optimization of Omega complete:"
numerical_msg += "\nSuccessful termination? {}".format("Yes" if opt_results.success else "No")
numerical_msg += "\nTermination message:\t{}".format(opt_results.message)
numerical_msg += "\nCompleted in {} iterations".format(opt_results.nit)
logging.info(numerical_msg)
return omega_hat
if args.perfect_gencov:
omega_hat = _posDef_adjustment(gmm_omega(Zs,Ns,sigma_LD))
return np.sqrt(np.outer(np.diag(omega_hat), np.diag(omega_hat)))
# else: gmm_omega (default)
return _posDef_adjustment(gmm_omega(Zs,Ns,sigma_LD))
def cov2corr(cov, return_std=False):
'''
convert covariance matrix to correlation matrix
'''
cov = np.asanyarray(cov)
std_ = np.sqrt(np.diag(cov))
corr = cov / np.outer(std_, std_)
return corr
########################
## MTAG CALCULATION ####
########################
def mtag_analysis(Zs, Ns, omega_hat, sigma_LD):
logging.info('Beginning MTAG calculations...')
M,P = Zs.shape
W_N = np.einsum('mp,pq->mpq',np.sqrt(Ns),np.eye(P))
W_N_inv = np.linalg.inv(W_N)
Sigma_N = np.einsum('mpq,mqr->mpr',np.einsum('mpq,qr->mpr',W_N_inv,sigma_LD),W_N_inv)
mtag_betas = np.zeros((M,P))
mtag_se = np.zeros((M,P))
mtag_factor = np.zeros((M,P))
for p in range(P):
# Note that in the code, what I call "gamma should really be omega", but avoid the latter term due to possible confusion with big Omega
gamma_k = omega_hat[:,p]
tau_k_2 = omega_hat[p,p]
om_min_gam = omega_hat - np.outer(gamma_k,gamma_k)/tau_k_2
xx = om_min_gam + Sigma_N
inv_xx = np.linalg.inv(xx)
yy = gamma_k/tau_k_2
W_inv_Z = np.einsum('mqp,mp->mq',W_N_inv,Zs)
beta_denom = np.einsum('mp,p->m',np.einsum('q,mqp->mp',yy,inv_xx),yy)
mtag_factor[:,p] = np.einsum('mp,m->m',np.einsum('q,mqp->mp',yy,inv_xx), 1/beta_denom)
mtag_var_p = 1. / beta_denom
mtag_betas[:,p] = np.einsum('mp,mp->m',np.einsum('q,mqp->mp',yy,inv_xx), W_inv_Z) / beta_denom
mtag_se[:,p] = np.sqrt(mtag_var_p)
logging.info(' ... Completed MTAG calculations.')
return mtag_betas, mtag_se, mtag_factor
####################
## SAVING RESULTS ##
####################
def save_mtag_results(args,results_template,Zs,Ns,Fs,mtag_betas,mtag_se,mtag_factor):
'''
Output will be of the form:
snp_name z n maf mtag_beta mtag_se mtag_zscore mtag_pval
'''
p_values = lambda z: 2*(scipy.stats.norm.cdf(-1.*np.abs(z)))
M,P = mtag_betas.shape
if args.std_betas:
logging.info('Outputting standardized betas..')
# meta-analysis mode
if args.equal_h2 and args.perfect_gencov:
logging.info('With meta-analysis mode, MTAG produces a single set of sumstats, where betas are unstandardized using 2p(1-p) where p is the average allele frequencies across traits.')
Fs = np.mean(Fs, axis=1)
if args.std_betas:
weights = np.ones(M,dtype=float)
else:
weights = np.sqrt( 2*Fs*(1.-Fs))
# check betas and se are identical in all columns
for p in range(1,P):
for col in ['mtag_betas','mtag_se']:
if not np.all(mtag_betas[:,p] == mtag_betas[:,0]):
raise ValueError('Meta-analysis mode is not implemented correctly')
# output meta-analysis results
logging.info('Writing Meta-analysis results to file ...')
out_df = results_template.copy()
out_df['meta_freq'] = Fs
out_df['mtag_beta'] = mtag_betas[:,0] / weights
out_df['mtag_se'] = mtag_se[:,0] / weights
out_df['mtag_z'] = mtag_betas[:,0]/mtag_se[:,0]
out_df['mtag_pval'] = p_values(out_df['mtag_z'])
out_path = args.out +'_mtag_meta.txt'
out_df.to_csv(out_path,sep='\t', index=False)
else:
for p in range(P):
logging.info('Writing Phenotype {} to file ...'.format(p+1))
out_df = results_template.copy()
out_df['Z'] = Zs[:,p]
out_df['N'] = Ns[:,p]
out_df['FRQ'] = Fs[:,p]
if args.std_betas:
weights = np.ones(M,dtype=float)
else:
weights = np.sqrt( 2*Fs[:,p]*(1. - Fs[:,p]))
out_df['mtag_beta'] = mtag_betas[:,p] / weights
out_df['mtag_se'] = mtag_se[:,p] / weights
out_df['mtag_z'] = mtag_betas[:,p]/mtag_se[:,p]
out_df['mtag_pval'] = p_values(out_df['mtag_z'])
if P == 1:
out_path = args.out +'_trait.txt'
else:
out_path = args.out +'_trait_' + str(p+1) + '.txt'
out_df.to_csv(out_path,sep='\t', index=False)
def write_summary(args,Zs,Ns,Fs,mtag_betas,mtag_se,mtag_factor):
'''
Note that in the current version, Ns is the full dataframe under the meta_format mode.
'''
_,P = mtag_factor.shape
if not args.equal_h2:
omega_out = "\nEstimated Omega:\n"
omega_out += str(args.omega_hat)
omega_out += '\n'
omega_out += "\n(Correlation):\n"
omega_out += str(cov2corr(args.omega_hat))
omega_out += '\n'
np.savetxt(args.out +'_omega_hat.txt',args.omega_hat, delimiter ='\t')
else:
omega_out = "Omega hat not computed because --equal_h2 was used.\n"
sigma_out = "\nEstimated Sigma:\n"
sigma_out += str(args.sigma_hat)
sigma_out += '\n'
sigma_out += "\n(Correlation):\n"
sigma_out += str(cov2corr(args.sigma_hat))
sigma_out += '\n'
np.savetxt(args.out +'_sigma_hat.txt',args.sigma_hat, delimiter ='\t')
weight_out = "\nMTAG weight factors: (average across SNPs)\n"
weight_out += str(np.mean(mtag_factor,axis=0))
weight_out += '\n'
summary_df = pd.DataFrame(index=np.arange(1,P+1))
input_phenotypes = [ '...'+f[-16:] if len(f) > 20 else f for f in args.sumstats.split(',')]
for p in range(P):
summary_df.loc[p+1,'Trait'] = input_phenotypes[p]
summary_df.loc[p+1, '# SNPs used'] = int(len(Zs[:,p]))
if args.meta_format:
comb_df_extract = [Ns[y][x] for y in Ns.keys() for x in Ns[y].keys() if x==p]
out_df = pd.concat(comb_df_extract, axis=0)
summary_df.loc[p+1, 'N (max)'] = np.max(out_df[args.n_name])
summary_df.loc[p+1, 'N (mean)'] = np.mean(out_df[args.n_name])
else:
summary_df.loc[p+1, 'N (max)'] = np.max(Ns[:,p])
summary_df.loc[p+1, 'N (mean)'] = np.mean(Ns[:,p])
summary_df.loc[p+1, 'GWAS mean chi^2'] = np.mean(np.square(Zs[:,p])) / args.sigma_hat[p,p]
Z_mtag = mtag_betas[:,p]/mtag_se[:,p]
summary_df.loc[p+1, 'MTAG mean chi^2'] = np.mean(np.square(Z_mtag))
summary_df.loc[p+1, 'GWAS equiv. (max) N'] = int(summary_df.loc[p+1, 'N (max)']*(summary_df.loc[p+1, 'MTAG mean chi^2'] - 1) / (summary_df.loc[p+1, 'GWAS mean chi^2'] - 1))
summary_df['N (max)'] = summary_df['N (max)'].astype(int)
summary_df['N (mean)'] = summary_df['N (mean)'].astype(int)
summary_df['# SNPs used'] = summary_df['# SNPs used'].astype(int)
summary_df['GWAS equiv. (max) N'] = summary_df['GWAS equiv. (max) N'].astype(int)
final_summary = "\nSummary of MTAG results:\n"
final_summary +="------------------------\n"
final_summary += str(summary_df.round(3))+'\n'
final_summary += omega_out
final_summary += sigma_out
final_summary += weight_out
logging.info(final_summary)
logging.info(' ')
logging.info('MTAG results saved to file.')
def save_mtag_results_U(args, comb_df):
'''
Concatenate mtag results by subtypes and write to files
'''
for p in range(args.P):
logging.info('Writing Phenotype {} to file...'.format(p+1))
comb_df_extract = [comb_df[y][x] for y in comb_df.keys() for x in comb_df[y].keys() if x==p]
out_df = pd.concat(comb_df_extract, axis=0)
M_0 = out_df.shape[0]
if M_0 - out_df.shape[0] != 0:
raise ValueError('--meta_format option was not implemented correctly.')
out_path = args.out +'_trait_' + str(p+1) + '.txt'
out_df.to_csv(out_path,sep='\t', index=False, na_rep="NA")
## maxFDR Functions
create_S = lambda P: np.asarray(list(itertools.product([False,True], repeat=P)))
def MTAG_var_Z_jt_c(t, Omega, Omega_c, sigma_LD, Ns):
'''
Omega: full Omega matrix
Omega_c: conditional Omega
Sigma_LD
N_mean: vector of length of "sample sizes" (1/c**2).
This formula only works with constant N, etc.
'''
T = Ns.shape[1]
W_N = np.einsum('mp,pq->mpq',np.sqrt(Ns),np.eye(T))
W_N_inv = np.linalg.inv(W_N)
Sigma_j = np.einsum('mpq,mqr->mpr',np.einsum('mpq,qr->mpr',W_N_inv,sigma_LD),W_N_inv)
gamma_k = Omega[:,t]
tau_k_2 = Omega[t,t]
om_min_gam = Omega - np.outer(gamma_k, gamma_k) / tau_k_2
xx = om_min_gam + Sigma_j
inv_xx = np.linalg.inv(xx)
# num_L / R are the same due to symmetry
num_L = np.einsum('p,mpq->mq', gamma_k / tau_k_2, inv_xx)