19526: Output tile locations and pvalues at specified threshold.
[lightning.git] / manhattan.py
1 # Copyright (C) The Lightning Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 import csv
6 import os
7 import sys
8
9 import matplotlib
10 import numpy
11 import pandas
12 import qmplot
13
14 (_,
15  input_path,
16  output_path,
17  csv_threshold_str,
18  csv_output_path,
19  ) = sys.argv
20 csv_threshold = float(csv_threshold_str)
21
22 columns = numpy.load(os.path.join(input_path, 'onehot-columns.npy'))
23
24 # pvalue maps tag# => [pvalue1, pvalue2, ...] (one het p-value and one hom p-value for each tile variant)
25 pvalue = {}
26 for i in range(columns.shape[1]):
27     tag = columns[0,i]
28     x = pvalue.get(tag, [])
29     x.append(pow(10, -columns[4,i] / 1000000))
30     pvalue[tag] = x
31
32 # tilepos maps tag# => (chromosome, position)
33 tilepos = {}
34 for dirent in os.scandir(input_path):
35     if dirent.name.endswith('.annotations.csv'):
36         with open(dirent, 'rt', newline='') as annotations:
37             for annotation in csv.reader(annotations):
38                 # 500000,0,2,=,chr1,160793649,,,
39                 if annotation[3] == "=":
40                     tilepos[int(annotation[0])] = (annotation[4], int(annotation[5]))
41
42 if csv_threshold > 0 and csv_output_path != "":
43     with open(csv_output_path, 'wt') as f:
44         for tag, chrpos in sorted(tilepos.items(), key=lambda item: (item[1][0][-1] > '9', item[1][0].lstrip('chr').zfill(2), item[1][1])):
45             for p in pvalue.get(tag, []):
46                 if p < pow(10, -csv_threshold):
47                     print(f'{tag},{chrpos[0]},{chrpos[1]},{p}', file=f)
48
49 series = {"#CHROM": [], "POS": [], "P": []}
50 for tag, chrpos in sorted(tilepos.items(), key=lambda item: (item[1][0][-1] > '9', item[1][0].lstrip('chr').zfill(2), item[1][1])):
51     for p in pvalue.get(tag, []):
52         series["#CHROM"].append(chrpos[0])
53         series["POS"].append(chrpos[1])
54         series["P"].append(p)
55
56 qmplot.manhattanplot(data=pandas.DataFrame(series),
57                      suggestiveline=2e-10,  # Turn off suggestiveline
58                      genomewideline=2e-11,  # Turn off genomewidel
59                      sign_line_cols=["#D62728", "#2CA02C"],
60                      marker=".",
61                      alpha = 0.6,
62                      hline_kws={"linestyle": "--", "lw": 1.3},
63                      title="Tile Variant Manhattan Plot",
64                      # xtick_label_set=xtick,
65                      xlabel="Chromosome",
66                      ylabel=r"$-log_{10}{(P)}$",
67                      xticklabel_kws={"rotation": "vertical"})
68 matplotlib.pyplot.savefig(output_path, bbox_inches="tight")