-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmr_link_2_standalone.py
1918 lines (1547 loc) · 81.5 KB
/
mr_link_2_standalone.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
import numpy as np
import scipy.optimize
import scipy.stats
import re
import pandas as pd
import argparse
import os
import time
import subprocess
import copy
import scipy
import scipy.io
from typing import Any, Tuple, Dict
import tempfile
import bitarray
import pyarrow.dataset as ds
import duckdb
from collections import OrderedDict
class PlinkGenoReader:
"""
TODO documentation
"""
def __init__(self, plink_bed_prepend):
self.prepend = plink_bed_prepend
self.bed_loc = f'{self.prepend}.bed'
self.bim_loc = f'{self.prepend}.bim'
self.fam_loc = f'{self.prepend}.fam'
for filename in [self.bed_loc, self.bim_loc, self.fam_loc]:
if not os.path.exists(filename):
raise ValueError(f'Error Could not find {filename=} when reading the genotype reference')
self.n_individuals = 0
with open(self.fam_loc, 'r') as f:
for line in f:
if not line in ['\n', '\r\n']:
self.n_individuals+=1
last_chromosome_position = ('0', 0)
self._decoder = {0: bitarray.bitarray('00'), #homoz A1 (usually minor)
1: bitarray.bitarray('01'), #heteroz
2: bitarray.bitarray('11'), #homoz A2 (usually major)
3: bitarray.bitarray('10'), # missing
}
## Ensured that this is ordered, so we can find a range.
self.bim_data = OrderedDict()
self.snp_name_to_variant_order = {}
with open(self.bim_loc, 'r') as f:
for i, line in enumerate(f):
split = line.split()
self.bim_data[split[1]] = (split[0], split[3], split[4], split[5])
self.snp_name_to_variant_order[split[1]] = i
if split[0] != last_chromosome_position[0]:
last_chromosome_position = (split[0], int(split[3]))
elif last_chromosome_position[1] > int(split[3]):
raise ValueError(f'Error: bim file is not ordered correctly at {split}')
else:
last_chromosome_position = (split[0], int(split[3]))
self.n_variants = len(self.bim_data)
def read_list_of_snps_into_geno_array(self, snps_to_load: set, missing_encoding=3, dtype=float):
"""
# TODO fix documentation.
Reads a bed file into a numpy array.
"""
self._missing_encoding = missing_encoding
snps_to_load = list(snps_to_load)
variant_idxes_to_load = [self.snp_name_to_variant_order[x] for x in snps_to_load]
n_variants = len(snps_to_load)
bytes_per_variant = int(np.ceil(self.n_individuals / 4))
byte_array = bytearray(b"\0" * bytes_per_variant * len(snps_to_load))
with open(self.bed_loc, "rb") as bed_file:
magick = bed_file.read(3)
if magick != b'l\x1b\x01':
raise ValueError("Plink file magic string is not correct.")
byte_array_position = 0
for variant_idx in variant_idxes_to_load:
bed_file.seek((variant_idx * bytes_per_variant) + 3, 0)
byte_array[byte_array_position: byte_array_position+bytes_per_variant] = bed_file.read(bytes_per_variant)
byte_array_position = byte_array_position + bytes_per_variant
genotypes = np.zeros((self.n_individuals, n_variants), dtype=np.uint8)
offset = 0
for i in range(n_variants):
bits = bitarray.bitarray(endian="little")
bits.frombytes(byte_array[offset:(offset+bytes_per_variant)])
array = list(bits.decode(self._decoder))[:self.n_individuals]
genotypes[:,i] = array
offset+=bytes_per_variant
genotypes = np.array(genotypes, dtype=dtype)
genotypes[genotypes == 3] = missing_encoding
#convert genotypes to minor allele is coded as one.
tmp_geno = copy.deepcopy(genotypes)
tmp_geno[genotypes == 2] = 0
tmp_geno[genotypes == 0] = 2
genotypes = tmp_geno
self.genotypes = genotypes
return genotypes, snps_to_load
class StartEndRegion:
"""
Class that implements a genomic region, which is really a stretch of base pairs.
Attributes
----------
chromosome: str
string representing the chromosome
start: int
start base pair position of the genomic region.
end: int
end position of the genomic region.
Methods
-------
position_in_region(self, chr, position):
returns a bool on if the single position is within the region.
snp_in_region(chr, position)
returns a bool on if the single position is within the region.
synonym method of position in region.
snp_object_in_region(snp_object)
returns a bool on if the object of class SNP is within the region.
region_overlaps(other_region)
returns a bool if another of region of the same class overlaps.
"""
def __init__(self, *args, **kwargs):
if type(args[0]) == list and len(args) == 1:
self.chromosome = str(args[0][0])
self.start = int(args[0][1])
self.end = int(args[0][2])
elif len(args) == 3 and type(args[0]) != list:
self.chromosome = str(args[0])
self.start = int(args[1])
self.end = int(args[2])
elif type(args[0]) == str and len(args) == 1:
self.chromosome, _, rest = args[0].partition(":")
self.start, self.end = [int(x) for x in rest.split('-')]
elif isinstance(args[0], StartEndRegion) and len(args) == 1:
self.chromosome = args[0].chromosome
self.start = args[0].start
self.end = args[0].end
else:
raise ValueError(
"Constructor only accepts a list [<chr>, <start>, <end>], three arguments (<chr>, <start>, <end>) "
"or a string formatted as 'chr:start-end' ")
# Runtime checks.
if self.start > self.end:
raise RuntimeError("Region cannot have a start position smaller than an end position")
if self.start < 0 or self.end < 0:
raise RuntimeError("Region cannot have negative positions.")
def position_in_region(self, chr, position):
"""
return if the position is in the region.
:param chr: chromosome str or castable to str
:param position: position int or castable to int
:return: bool
"""
return (self.chromosome == str(chr)) and (self.start <= int(position) <= self.end)
def snp_in_region(self, chr, position):
"""
return if the position is in the region.
synonym method of position_in_region method.
:param chr: chromosome str or castable to str
:param position: position int or castable to int
:return: bool
"""
return self.position_in_region(chr, position)
def snp_object_in_region(self, snp_object):
"""
:param snp_object: object of type SNP (this package)
:return: True or false if snp in region
"""
return self.snp_in_region(snp_object.chromosome, snp_object.position)
def region_overlaps(self, other_region):
if self.chromosome == other_region.chromosome:
# this may contain an error, and could be done more efficiently.
if self.start <= other_region.start <= self.end \
or self.start <= other_region.end <= self.end \
or other_region.start <= self.start <= other_region.end \
or other_region.start <= self.end <= other_region.end:
return True
return False
def __str__(self):
return '{}:{}-{}'.format(self.chromosome, self.start, self.end)
def __lt__(self, other):
if not other.__class__ is self.__class__:
return NotImplemented
if not self.chromosome == other.chromosome:
try:
return int(self.chromosome) < int(other.chromosome)
except:
return self.chromosome < other.chromosome
return self.start < other.start
def __gt__(self, other):
if not other.__class__ is self.__class__:
return NotImplemented
if not self.chromosome == other.chromosome:
try:
return int(self.chromosome) > int(other.chromosome)
except:
return self.chromosome > other.chromosome
return self.start > other.end
def __contains__(self, item):
if isinstance(item, StartEndRegion):
return self.region_overlaps(item)
else:
raise ValueError("Only classes (or inheritance allowed:) SNP.variant or gene_regions.StartEndRegion")
def __repr__(self):
return f'{self.chromosome}:{self.start}-{self.end}'
class StartEndRegions:
"""
This class contains multiple start end regions
Attributes
----------
gene_regions: list of StartEndRegion objects
Methods
-------
in_gene_regions(self, chr, position)
identifies if a position is in any of the regions.
make_non_overlapping_regions(self)
combines the regions into contiguous non-overlapping regions.
"""
def __init__(self, list_of_regions):
self.gene_regions = list([StartEndRegion] * len(list_of_regions))
i = 0
for region in list_of_regions:
tmp = StartEndRegion(region)
self.gene_regions[i] = tmp
i += 1
def in_gene_regions(self, chr, position):
"""
Identify if a snp is in any of the gene regions.
:param chr: chromosome castable to str
:param position: position castable to int
:return: boolean
"""
for i in self.gene_regions:
if i.snp_in_region(chr, position):
return True
return False
def make_non_overlapping_regions(self):
"""
Combines all overlapping regions, and turns them into one big region.
:return: new instance of StartEndRegions containing contiguous, non overlapping regions
"""
sorted_regions = sorted(self.gene_regions)
combined = False
non_overlapping = []
index = 0
tmp_region = sorted_regions[index]
while index < len(sorted_regions) - 1:
if tmp_region.region_overlaps(sorted_regions[index + 1]):
tmp_region.end = sorted_regions[
index + 1].end # Assumes this is sorted, so we don't look at the start region
else:
non_overlapping.append(tmp_region)
tmp_region = sorted_regions[index + 1]
index += 1
# finally, add the last tmp region to the file.
non_overlapping.append(tmp_region)
return StartEndRegions([str(x) for x in non_overlapping])
def __next__(self):
self.i += 1
if self.i > len(self.gene_regions):
raise StopIteration
else:
return self.gene_regions[self.i - 1]
def __iter__(self):
self.i = 0
return self
def __repr__(self):
return (f'StartEndRegions with {len(self.gene_regions)} regions across chromosome(s) '
f'{sorted(set([x.chromosome for x in self.gene_regions]))}')
def __contains__(self, item):
if isinstance(item, StartEndRegion):
for region in sorted(self.gene_regions):
if region > item:
return False
elif region in item:
return True
else:
continue
else:
raise ValueError("Only classes (or inheritance allowed:) SNP.variant or gene_regions.StartEndRegion")
def identify_regions(sumstats_exposure: str,
bed_prepend: str,
plink_p_threshold: float,
plink_maf_threshold: float,
padding: int,
plink_tmp_prepend: str,
r_sq_threshold=0.01,
verbosity_level=0) -> StartEndRegions:
"""
This is a function that takes a summary_statistics file, and the location of a bed file
and clumps the most associated variants using plink.
:param sumstats_exposure: pandas.DataFrame containing at least the columns rsid, pval, where .rsid should
match the variants in the bed file.
:param bed_prepend: str containing the path prepend of plink genotype files in the .bed, .bim, .fam file
:param plink_p_threshold: float the p value threshold used for clumping
:param plink_maf_threshold: the minor allele frequency threshold used for further filtering
:param padding: int, the number of base poirs of padding of the plink region, and the combination of clumps/
:param plink_tmp_prepend: str a prepend of a file location where files are stored
:param r_sq_threshold: float, the rˆ2 threshold for clumping, default = 0.01
:param verbosity_level: int the verbosity level. Will return the output of plink as stdout if it is not Null.
:return: StartEndRegions that were found using all the clumps that were present.
"""
stderr = subprocess.DEVNULL if not verbosity_level else None
stdout = subprocess.DEVNULL if not verbosity_level else None
files_to_remove = []
subprocess.run(['plink',
'--bfile', bed_prepend,
'--maf', f'{plink_maf_threshold}',
'--clump', sumstats_exposure,
'--clump-p1', f'{plink_p_threshold:.2e}',
'--clump-r2', f'{r_sq_threshold}',
'--clump-kb', f'{padding / 1000}',
'--clump-snp-field', 'rsid',
'--clump-field', 'p_value',
'--out', f'{plink_tmp_prepend}_clumping_results'
], check=True, stderr=stderr, stdout=stdout)
files_to_remove += [f'{plink_tmp_prepend}_clumping_results.{x}' for x in ['clumped', 'log', 'nosex']]
if not os.path.exists(f'{plink_tmp_prepend}_clumping_results.clumped'):
return None
all_regions = []
try:
with open(f'{plink_tmp_prepend}_clumping_results.clumped') as f:
f.readline() # header
for line in f:
if line in {'', '\n'}:
continue
split = line.split()
chromosome = split[0]
position = split[3]
data = [str(chromosome), int(int(position) - padding if int(position) - padding > 0 else 0),
int(position) + padding]
all_regions.append(
StartEndRegion(data)
)
all_regions = sorted(all_regions)
except Exception as x:
raise ValueError(f'Couldn\'t parse the clumped file with error {x}')
combined_regions = StartEndRegions(all_regions).make_non_overlapping_regions()
for filename in files_to_remove:
if os.path.exists(filename):
os.remove(filename)
return combined_regions.gene_regions
def mr_link2_loglik_reference_v0(th: np.ndarray, lam: np.ndarray,
c_x: np.ndarray, c_y: np.ndarray,
n_x: float, n_y: float) -> float:
"""
The MR-link2 log likelihood function. This function calculates -1 * likelihood of three parameters:
alpha, sigma_x and sigma_y.
Designed to be used in optimization algorithms like those in scipy.minimize
:param th:
List or numpy array of floats with the parameters to optimize first is alpha, second the
1 / exposure heritability (per variant) and third the 1/ outcome heritability (per variant).
:param lam:
np.ndarray of selected eigenvalues of the cX and cY parameters.
:param c_x:
The dot product of the selected eigenvectors and summary statistics vector of the exposure
:param c_y:
The dot product of the selected eigenvectors and summary statistics vector of the outcome
:param n_x:
The number of individuals in the exposure dataset
:param n_y:
The number of individuals in the outcome dataset
:return:
a single float that contains the likelihood of the parameters theta.
"""
n_x = np.longdouble(n_x)
n_y = np.longdouble(n_y)
a = np.longdouble(th[0])
tX = abs(np.longdouble(th[1]))
tY = abs(np.longdouble(th[2]))
lam = np.asarray(lam, dtype=np.longdouble)
c_x = np.asarray(c_x, dtype=np.longdouble)
c_y = np.asarray(c_y, dtype=np.longdouble)
Dxx = 1. / (((a ** 2 * n_y + n_x) * lam + tX) - a ** 2 * n_y ** 2 * (lam ** 2) / (n_y * lam + tY))
Dxy = -Dxx * (a * n_y * lam) / (n_y * lam + tY)
# This if statement is used to catch a float overflow warning.
# sometimes elements of (nY*lam*tY) can be infinite, but this will reduce the second term to zero.
# Analogously, the _a_ value can be set to zero, leading to an overflow error as well, but setting the second term
# to zero as well.
Dyy = (1. / (n_y * lam + tY))
if a != 0: # catching a overflow error
selection = (n_y * lam + tY) < np.sqrt(np.finfo(np.float64).max)
if np.any(selection):
Dyy[selection] = Dyy[selection] + (Dxx * (a ** 2 * n_y ** 2 * lam ** 2)) / ((n_y * lam + tY) ** 2)
dX = n_x * c_x + a * n_y * c_y
dY = n_y * c_y
m = len(c_x)
loglik = -m * np.log(2 * np.pi) + \
-(1 / 2) * sum(
np.log((a ** 2 * n_y + n_x) * lam + tX - a ** 2 * n_y ** 2 * (lam ** 2) / (n_y * lam + tY))) + \
-(1 / 2) * sum(np.log(n_y * lam + tY)) + \
+(1 / 2) * (sum(dX ** 2 * Dxx) + 2 * sum(dX * dY * Dxy) + sum(dY ** 2 * Dyy)) + \
-(n_x / 2) * sum((c_x ** 2) / lam) + \
-(n_y / 2) * sum((c_y ** 2) / lam) + \
+(m / 2) * (np.log(n_x) + np.log(n_y)) - sum(np.log(lam)) + (m / 2) * (np.log(tX) + np.log(tY))
return -loglik
def mr_link2_loglik_reference_v2(th: np.ndarray, lam: np.ndarray,
c_x: np.ndarray, c_y: np.ndarray,
n_x: float, n_y: float) -> float:
"""
The MR-link2 log likelihood function. This function calculates -1 * likelihood of three parameters:
alpha, sigma_x and sigma_y.
Designed to be used in optimization algorithms like those in scipy.minimize
:param th:
List or numpy array of floats with the parameters to optimize first is alpha, second the
1 / exposure heritability (per variant) and third the 1/ outcome heritability (per variant).
:param lam:
np.ndarray of selected eigenvalues of the cX and cY parameters.
:param c_x:
The dot product of the selected eigenvectors and summary statistics vector of the exposure
:param c_y:
The dot product of the selected eigenvectors and summary statistics vector of the outcome
:param n_x:
The number of individuals in the exposure dataset
:param n_y:
The number of individuals in the outcome dataset
:return:
a single float that contains the likelihood of the parameters theta.
"""
n_x = float(n_x)
n_y = float(n_y)
a = th[0]
tX = abs(th[1])
tY = abs(th[2])
Dyy = (1. / (n_y * lam + tY))
if a != 0.0:
Dxx = 1. / (np.exp(np.log(a ** 2 * n_y + n_x) + np.log(lam)) + tX -
np.exp(np.log(a ** 2 * n_y ** 2 * (lam ** 2)) - np.log(n_y * lam + tY)))
Dxy = -Dxx * a * np.exp(np.log((n_y * lam)) - np.log(n_y * lam + tY))
Dyy = Dyy + np.exp(np.log(Dxx * (a ** 2 * n_y ** 2 * lam ** 2)) - (2 * np.log(n_y * lam + tY)))
asq_ny_sq_lam_sq_div_ny_lam_ty = np.exp(np.log(a ** 2 * n_y ** 2 * (lam ** 2)) - np.log(n_y * lam + tY))
else:
Dxx = 1. / (np.exp(np.log(n_x) + np.log(lam)) + tX)
Dxy = -Dxx * a * np.exp(np.log((n_y * lam)) - np.log(n_y * lam + tY))
Dyy = Dyy
asq_ny_sq_lam_sq_div_ny_lam_ty = 0.0 * lam
dX = n_x * c_x + a * n_y * c_y
dY = n_y * c_y
m = len(c_x)
loglik = -m * np.log(2 * np.pi) + \
-(1 / 2) * sum(np.log((a ** 2 * n_y + n_x) * lam + tX - asq_ny_sq_lam_sq_div_ny_lam_ty)) + \
-(1 / 2) * sum(np.log(n_y * lam + tY)) + \
+(1 / 2) * (sum(dX ** 2 * Dxx) + 2 * sum(dX * dY * Dxy) + sum(dY ** 2 * Dyy)) + \
-(n_x / 2) * sum((c_x ** 2) / lam) + \
-(n_y / 2) * sum((c_y ** 2) / lam) + \
+(m / 2) * (np.log(n_x) + np.log(n_y)) - sum(np.log(lam)) + (m / 2) * (np.log(tX) + np.log(tY))
return -loglik
def mr_link2_loglik_alpha_h0(th, lam, cX, cY, nX, nY) -> float: # fix alpha to zero
"""
The MR-link2 log likelihood function when the causal effect is zero.
This function calculates -1 * likelihood of two parameters:
sigma_x and sigma_y. the causal effect alpha is set to zero
Designed to be used in optimization algorithms like those in scipy.minimize
:param th:
List or numpy array of floats with the 2 parameters to optimize first is the
1 / exposure heritability (per variant) and third the 1 / outcome heritability (per variant).
:param lam:
np.ndarray of selected eigenvalues of the cX and cY parameters.
:param cX:
The dot product of the selected eigenvectors and summary statistics vector of the exposure
:param cY:
The dot product of the selected eigenvectors and summary statistics vector of the outcome
:param nX:
The number of individuals in the exposure dataset
:param nY:
The number of individuals in the outcome dataset
:return:
a single float that contains the likelihood of the parameters theta.
"""
return mr_link2_loglik_reference_v2(np.asarray([0.0, th[0], th[1]]), lam, cX, cY, nX, nY)
def mr_link2_loglik_sigma_y_h0(th, lam, c_x, c_y, n_x, n_y) -> float: # this is for fixing sigma_y to zero
"""
The MR-link2 log likelihood function when the pleiotropic effect is zero.
This function calculates -1 * likelihood of two parameters:
alpha and sigma_x. the causal effect alpha is set to zero
Designed to be used in optimization algorithms like those in scipy.minimize
:param th:
List or numpy array of floats with the 2 parameters to optimize first is alpha, second the
1 / exposure heritability (per variant).
:param lam:
np.ndarray of selected eigenvalues of the cX and cY parameters.
:param c_x:
The dot product of the selected eigenvectors and summary statistics vector of the exposure
:param c_y:
The dot product of the selected eigenvectors and summary statistics vector of the outcome
:param n_x:
The number of individuals in the exposure dataset
:param n_y:
The number of individuals in the outcome dataset
:return:
a single float that contains the likelihood of the parameters theta.
"""
n_x = float(n_x)
n_y = float(n_y)
a = th[0]
tX = abs(th[1])
Dyy = np.zeros_like(lam)
if a != 0.0:
Dxx = 1. / (np.exp(np.log(a ** 2 * n_y + n_x) + np.log(lam)) + tX)
Dxy = np.zeros_like(lam) # -Dxx * a * np.exp(np.log((n_y * lam)) - np.log(n_y * lam + tY))
Dyy = Dyy + np.zeros_like(
lam) # np.exp(np.log(Dxx * (a ** 2 * n_y ** 2 * lam ** 2)) - (2 * np.log(n_y * lam + tY)))
asq_ny_sq_lam_sq_div_ny_lam_ty = np.zeros_like(
lam) # np.exp(np.log(a ** 2 * n_y ** 2 * (lam ** 2)) - np.log(n_y * lam + tY))
else:
Dxx = 1. / (np.exp(np.log(n_x) + np.log(lam)) + tX)
Dxy = np.zeros_like(lam) # -Dxx * a * np.exp(np.log((n_y * lam)) - np.log(n_y * lam + tY))
Dyy = Dyy
asq_ny_sq_lam_sq_div_ny_lam_ty = np.zeros_like(lam)
dX = n_x * c_x + a * n_y * c_y
dY = n_y * c_y
m = len(c_x)
loglik = -m * np.log(2 * np.pi) + \
-(1 / 2) * sum(np.log((a ** 2 * n_y + n_x) * lam + tX - asq_ny_sq_lam_sq_div_ny_lam_ty)) + \
+(1 / 2) * (sum(dX ** 2 * Dxx) + 2 * sum(dX * dY * Dxy) + sum(dY ** 2 * Dyy)) + \
-(n_x / 2) * sum((c_x ** 2) / lam) + \
-(n_y / 2) * sum((c_y ** 2) / lam) + \
+(m / 2) * (np.log(n_x) + np.log(n_y)) - sum(np.log(lam)) + (m / 2) * (np.log(tX))
# + (m/2) * np.log(tY)) -(1 / 2) * sum(np.log(n_y * lam + tY)) ## These two terms should cancel out.
return -loglik
def mr_link2(selected_eigenvalues: np.ndarray, selected_eigenvectors: np.ndarray,
exposure_betas: np.ndarray, outcome_betas: np.ndarray, n_exp: float, n_out: float,
sigma_exp_guess: float, sigma_out_guess: float) -> dict[str, Any]:
"""
Run MR-link-2, perform two likelihood ratio tests: one for the pleiotropic effect sigma_y and one for the
causal effect alpha
:param selected_eigenvalues: eigenvalues that are selected for this MR-link2 run
:param selected_eigenvectors: Eigenvectors that are selected for this MR-link2 run
:param exposure_betas: a vector of exposure betas
:param outcome_betas: a vector of outcome betas
:param n_exp: number of individuals in the exposure cohort
:param n_out: number of individuals in the outcome cohort
:param sigma_exp_guess: guess for sigma exposure
:param sigma_out_guess: guess for sigma outcoem
:return: returns a dictionary containing the results of the MR-link-2 optimizations
that can be used as a row in a pandas dataframe
"""
start_time = time.time()
method = 'Nelder-Mead'
options = {'maxiter': 300, 'disp': False}
c_x = selected_eigenvectors.T @ exposure_betas
c_y = selected_eigenvectors.T @ outcome_betas
max_sigma = np.sqrt(np.finfo(np.float64).max)
"""
Alpha h0 estimation
"""
alpha_h0_guesses = [
[sigma_exp_guess, sigma_out_guess],
[max_sigma, max_sigma],
[1, max_sigma],
[1e3, 1e3]
]
alpha_h0_results = scipy.optimize.minimize(mr_link2_loglik_alpha_h0, args=(selected_eigenvalues,
c_x,
c_y,
n_exp,
n_out),
x0=np.asarray(alpha_h0_guesses[0]),
method=method, options=options)
for alpha_h0_guess in alpha_h0_guesses[1:]: # first one already done
if alpha_h0_results.success:
break
new_alpha_h0_results = scipy.optimize.minimize(mr_link2_loglik_alpha_h0, args=(selected_eigenvalues,
c_x,
c_y,
n_exp,
n_out),
x0=np.asarray(alpha_h0_guess),
method=method, options=options)
if alpha_h0_results.fun >= new_alpha_h0_results.fun:
alpha_h0_results = new_alpha_h0_results
"""
Sigma_y estimation
"""
sigma_y_guesses = [[0.0, sigma_exp_guess],
[1.0, sigma_exp_guess],
[0.0, alpha_h0_results.x[0]],
[1.0, alpha_h0_results.x[0]],
[0.0, max_sigma],
[1e-10, max_sigma]
]
sigma_y_h0_results = scipy.optimize.minimize(mr_link2_loglik_sigma_y_h0, args=(selected_eigenvalues,
c_x,
c_y,
n_exp,
n_out),
x0=np.asarray(sigma_y_guesses[0]),
method=method, options=options)
for sigma_y_guess in sigma_y_guesses[1:]:
if sigma_y_h0_results.success:
break
new_sigma_y_h0_results = scipy.optimize.minimize(mr_link2_loglik_sigma_y_h0, args=(selected_eigenvalues,
c_x,
c_y,
n_exp,
n_out),
x0=np.asarray(sigma_y_guess),
method=method, options=options)
if new_sigma_y_h0_results.fun < sigma_y_h0_results.fun:
sigma_y_h0_results = new_sigma_y_h0_results
"""
Ha estimation
"""
ha_guesses = [
[0.0, alpha_h0_results.x[0], alpha_h0_results.x[1]],
[sigma_y_h0_results.x[0], sigma_y_h0_results.x[1], np.sqrt(np.finfo(np.float64).max)],
[1.0, alpha_h0_results.x[0], alpha_h0_results.x[1]],
[1e-10, max_sigma, max_sigma]
]
ha_results = scipy.optimize.minimize(fun=mr_link2_loglik_reference_v2, args=(selected_eigenvalues,
c_x,
c_y,
n_exp,
n_out),
x0=np.asarray(ha_guesses[0], dtype=float),
method=method, options=options)
for ha_guess in ha_guesses[1:]:
if ha_results.success:
break
new_ha_result = scipy.optimize.minimize(fun=mr_link2_loglik_reference_v2,
args=(selected_eigenvalues,
c_x,
c_y,
n_exp,
n_out),
x0=np.asarray(ha_guess, dtype=float),
method=method, options=options)
if new_ha_result.fun < ha_results.fun:
ha_results = new_ha_result
#
if True or not ha_results.success:
a = mr_link2_loglik_reference_v0(ha_results.x, selected_eigenvalues, c_x, c_y, n_exp, n_out)
b = mr_link2_loglik_reference_v2(ha_results.x, selected_eigenvalues, c_x, c_y, n_exp, n_out)
if not np.isclose(a, b):
print(f'Functions are not the same {a} compared to {b}, difference: {a - b:.4e}')
pass # for debugging purposes
## Now take the likelihoods and start doing the likelihood ratio test
alpha = ha_results.x[0]
alpha_chi_sq = 2 * (
alpha_h0_results.fun - ha_results.fun) ## This is the likelihood ratio, because they are in log scale
alpha_p_val = scipy.stats.chi2.sf(alpha_chi_sq, 1) ## This is
z_alpha = 0.0 if alpha_chi_sq <= 0 else np.sign(alpha) * np.sqrt(alpha_chi_sq)
se_alpha = alpha / z_alpha if z_alpha != 0 else np.nan
sigma_y = 1 / abs(ha_results.x[2])
sigma_y_chi_sq = 2 * (sigma_y_h0_results.fun - ha_results.fun)
sigma_y_p_val = scipy.stats.chi2.sf(sigma_y_chi_sq, 1)
z_sigma_y = 0.0 if sigma_y_chi_sq <= 0 else np.sqrt(sigma_y_chi_sq)
se_sigma_y = sigma_y / z_sigma_y if z_sigma_y != 0 else np.nan
to_return = {'alpha': alpha, 'se(alpha)': se_alpha, 'p(alpha)': alpha_p_val,
'sigma_y': sigma_y, 'se(sigma_y)': se_sigma_y, 'p(sigma_y)': sigma_y_p_val,
'sigma_x': 1 / abs(ha_results.x[1]),
'alpha_h0_sigma_x': 1 / abs(alpha_h0_results.x[0]),
'alpha_h0_sigma_y': 1 / abs(alpha_h0_results.x[1]),
'alpha_h0_loglik': alpha_h0_results.fun,
'sigma_y_h0_alpha': sigma_y_h0_results.x[0],
'sigma_y_h0_sigma_x': 1 / abs(sigma_y_h0_results.x[1]),
'sigma_y_h0_loglik': sigma_y_h0_results.fun,
'ha_loglik': ha_results.fun,
'optim_alpha_h0_success': alpha_h0_results.success,
'optim_alpha_h0_nit': alpha_h0_results.nit,
'optim_sigma_y_h0_success': sigma_y_h0_results.success,
'optim_sigma_y_h0_nit': sigma_y_h0_results.nit,
'optim_ha_success': ha_results.success,
'optim_ha_nit': ha_results.nit,
'function_time': time.time() - start_time
}
return to_return
def select_instruments_by_clumping(p_values: np.ndarray,
correlation_matrix: np.ndarray,
clumping_p_threshold: float,
r_threshold=0.1) -> list[int]:
"""
This function performs clumping based on a pre-computed correlation matrix.
:param p_values: np.ndarry of p values
:param correlation_matrix: a square correlation matrix **not squared correlation**
:param clumping_p_threshold: the p value threshold to select the SNPs on
:param r_threshold: the correlation threshold in pearson correlation. **not squared**
:return: a list of indices as selected SNPS.
"""
selection = []
mask = np.ones(len(p_values), dtype=bool)
while min(p_values[mask]) <= clumping_p_threshold:
mask_idxs = sorted(np.where(mask)[0])
selected = mask_idxs[np.argmin(p_values[mask])]
selection.append(selected)
to_keep = np.abs(correlation_matrix[selected, :]) <= r_threshold
mask = np.logical_and(mask, to_keep).reshape((len(p_values)))
if np.sum(mask) == 0:
break
return selection
def match_n_variants_n_individuals_from_plink_log(plink_logfile: str) -> Tuple[int, int]:
"""
This is a utitlity function to
:param plink_logfile: str
location of the plink logfile which will be parsed for the number of individuals and variants
:return: tuple
Tuple containing the numbeer of variants and number of individuals
"""
regex = re.compile('^([0-9]+) variants and ([0-9]+) people pass filters and QC\.')
with open(plink_logfile) as f:
for line in f:
match_obj = regex.match(line)
if match_obj:
return int(match_obj[1]), int(match_obj[2])
raise ValueError('Did not find n_individuals in the plink log.')
def run_colocalization_analysis(bXs, bYs, pXs, pYs, n_exp, n_out, mafs, ld_mat: np.ndarray,
out_file='tmp__colocalization__testing_out.txt.gz', in_file='tmp__colocalization__testing_in.txt.gz', ld_file='tmp__colocalization__testing_ld.bin'):
stderr = subprocess.DEVNULL if not verbosity else None
stdout = subprocess.DEVNULL if not verbosity else None
all_dfs = []
# ['MAF', 'pvalues', 'N', 'type', 'simulation'])
if len(bXs.shape) == 2:
n_sims = bXs.shape[1]
for i_pheno in range(n_sims):
exp_tmp_df = pd.DataFrame()
exp_tmp_df['beta'] = bXs[:, i_pheno] * mafs * (1 - mafs)
exp_tmp_df['MAF'] = mafs
exp_tmp_df['p_values'] = pXs[:, i_pheno]
exp_tmp_df['N'] = n_exp
exp_tmp_df['type'] = 'quant'
exp_tmp_df['simulation'] = i_pheno
exp_tmp_df['exp_or_outcome'] = 'exposure'
out_tmp_df = pd.DataFrame()
out_tmp_df['beta'] = bYs[:, i_pheno] * mafs * (1 - mafs)
out_tmp_df['MAF'] = mafs
out_tmp_df['p_values'] = pYs[:, i_pheno]
out_tmp_df['N'] = n_out
out_tmp_df['type'] = 'quant'
out_tmp_df['simulation'] = i_pheno
out_tmp_df['exp_or_outcome'] = 'outcome'
all_dfs.append(exp_tmp_df)
all_dfs.append(out_tmp_df)
else:
n_sims = 1
for i_pheno in range(n_sims):
exp_tmp_df = pd.DataFrame()
exp_tmp_df['beta'] = bXs * mafs * (1 - mafs)
exp_tmp_df['MAF'] = mafs
exp_tmp_df['p_values'] = pXs
exp_tmp_df['N'] = n_exp
exp_tmp_df['type'] = 'quant'
exp_tmp_df['simulation'] = i_pheno
exp_tmp_df['exp_or_outcome'] = 'exposure'
out_tmp_df = pd.DataFrame()
out_tmp_df['beta'] = bYs * mafs * (1 - mafs)
out_tmp_df['MAF'] = mafs
out_tmp_df['p_values'] = pYs
out_tmp_df['N'] = n_out
out_tmp_df['type'] = 'quant'
out_tmp_df['simulation'] = i_pheno
out_tmp_df['exp_or_outcome'] = 'outcome'
all_dfs.append(exp_tmp_df)
all_dfs.append(out_tmp_df)
full_df = pd.concat(all_dfs)
full_df.to_csv(out_file, sep='\t', index=False)
ld_mat.tofile(ld_file)
subprocess.run(['Rscript', f'{os.path.dirname(os.path.abspath(__file__))}/r_analyses/colocalization_analysis.R',
out_file, in_file, ld_file],
check=True,
stdout=stdout,
stderr=stderr,
)
if os.path.exists(in_file):
results = pd.read_csv(in_file, sep='\t')
else:
raise ValueError('Could not perform coloc')
os.remove(out_file)
os.remove(in_file)
os.remove(ld_file)
return results
def run_external_mr_analysis(bXs, bYs, seXs, seYs, pXs, pYs, n_exp, n_out, mafs, ld_mat: np.ndarray, instruments,
out_file='tmp__colocalization_mr_testing_out.txt.gz', in_file='mr_testing_in.txt.gz',
ld_file='mr_testing_ld.bin'):
"""
This function is written to run the MR analyses
:param bXs:
:param bYs:
:param seXs:
:param seYs:
:param pXs:
:param pYs:
:param n_exp:
:param n_out:
:param mafs:
:param ld_mat:
:param instruments:
:param out_file:
:param in_file:
:param ld_file:
:return: a dataframe of results.
"""
all_dfs = []
print(instruments.shape)
if len(bXs.shape) == 2:
for i_pheno in range(bXs.shape[1]):
exp_tmp_df = pd.DataFrame()
exp_tmp_df['beta'] = bXs[:, i_pheno] # * mafs * (1 - mafs)
exp_tmp_df['ses'] = seXs[:, i_pheno] # * mafs * (1 - mafs)
exp_tmp_df['MAF'] = mafs
exp_tmp_df['p_values'] = pXs[:, i_pheno]
exp_tmp_df['N'] = n_exp
exp_tmp_df['type'] = 'quant'
exp_tmp_df['simulation'] = i_pheno
exp_tmp_df['exp_or_outcome'] = 'exposure'
exp_tmp_df['selected_as_instrument'] = instruments[:, i_pheno]
out_tmp_df = pd.DataFrame()
out_tmp_df['beta'] = bYs[:, i_pheno] # * mafs * (1 - mafs)
out_tmp_df['ses'] = seYs[:, i_pheno]
out_tmp_df['MAF'] = mafs
out_tmp_df['p_values'] = pYs[:, i_pheno]
out_tmp_df['N'] = n_out
out_tmp_df['type'] = 'quant'
out_tmp_df['simulation'] = i_pheno
out_tmp_df['exp_or_outcome'] = 'outcome'
out_tmp_df['selected_as_instrument'] = instruments[:, i_pheno]
all_dfs.append(exp_tmp_df)
all_dfs.append(out_tmp_df)
else:
for i_pheno in range(1):
exp_tmp_df = pd.DataFrame()
exp_tmp_df['beta'] = bXs
exp_tmp_df['ses'] = seXs
exp_tmp_df['MAF'] = mafs
exp_tmp_df['p_values'] = pXs
exp_tmp_df['N'] = n_exp
exp_tmp_df['type'] = 'quant'
exp_tmp_df['simulation'] = i_pheno
exp_tmp_df['exp_or_outcome'] = 'exposure'
exp_tmp_df['selected_as_instrument'] = instruments