-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeaks_intersection_with_promoters.py
executable file
·185 lines (147 loc) · 6.3 KB
/
peaks_intersection_with_promoters.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
'''
Copyright © 2018 Anton Tsukanov. Contacts: [email protected]
License: http://www.gnu.org/licenses/gpl.txt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
import pandas as pd
import numpy as np
import argparse
import sys
#def read_gtf(path):
#
# gtf = pd.read_csv(path,
# sep='\t',comment='#', header=None, dtype= {'chr': str},
# names=['chr', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute'])
# attribute = gtf['attribute'].str.split('; ')
# gtf = gtf.drop(columns=['attribute'])
#
# res = []
# for record in attribute:
# rec = []
# for i in record:
# if i == '':
# continue
# (a,b) = i.strip().split(maxsplit=1)
# rec.append((a.strip(),b.strip(';\" ')))
# res.append(dict(rec))
# attribute = pd.DataFrame(res)
# gtf = pd.concat([gtf, attribute], axis=1, sort=False)
# return(gtf)
def read_gtf(path):
gtf = pd.read_csv(path,
sep='\t',comment='#', header=None, dtype= {'chr': str},
names=['chr', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame', 'attribute'])
res = map(slpit_attribute, gtf['attribute'])
attribute = pd.DataFrame(list(res))
gtf = gtf.drop(columns=['attribute'])
gtf = pd.concat([gtf, attribute], axis=1, sort=False)
del attribute
return(gtf)
def slpit_attribute(record):
record = record.split('; ')
rec = []
for i in record:
if i == '':
continue
(a,b) = i.strip().split(maxsplit=1)
rec.append((a.strip(),b.strip(';\" ')))
return(dict(rec))
def read_peaks(path):
df = pd.read_csv(path,
sep='\t', header=None,
usecols=[0, 1, 2, 3, 4, 5], dtype= {'chr': str},
names=['chr', 'start', 'end', 'name', 'score', 'strand'])
return(df)
def get_promoters(gtf, rigth=-5000, left=5000):
if 'gene_biotype' in gtf.columns:
df = gtf[np.logical_and(gtf['feature'] == 'gene', gtf['gene_biotype'] == 'protein_coding')]
#df = gtf[gtf['feature'] == 'gene']
if 'gene_type' in gtf.columns:
df = gtf[np.logical_and(gtf['feature'] == 'gene', gtf['gene_type'] == 'protein_coding')]
#df = gtf[gtf['feature'] == 'gene']
promoters = {'chr': [], 'start': [], 'end': [],
'name': [], 'score': [], 'strand': [],
'signalValue': [], 'pValue': [], 'qValue': [],
'peak': [], 'gene_id': []}
for line, strand in enumerate(df['strand']):
if strand == '+':
promoters['start'].append(df['start'].iloc[line] + rigth)
promoters['end'].append(df['start'].iloc[line] + left)
if strand == '-':
promoters['start'].append(df['end'].iloc[line] - left)
promoters['end'].append(df['end'].iloc[line] - rigth)
promoters['chr'].append(df['chr'].iloc[line])
promoters['name'].append(df['gene_id'].iloc[line])
promoters['score'].append(df['score'].iloc[line])
promoters['strand'].append(df['strand'].iloc[line])
promoters['signalValue'].append(0)
promoters['pValue'].append(-1)
promoters['qValue'].append(-1)
promoters['peak'].append(-1)
promoters['gene_id'].append(df['gene_id'].iloc[line])
return(pd.DataFrame(promoters))
def overlap(peak, promoters):
'''
Does the range (start1, end1) overlap with (start2, end2)?
Based on De Morgan's laws
'''
overlaps = promoters[np.logical_and(np.less_equal(peak['start'], promoters['end']),
np.greater_equal(peak['end'], promoters['start']))]
return(list(overlaps['gene_id']))
def peaks_intersect_genes(peaks, promoters):
chrs_of_promoters = promoters['chr'].unique()
chrs_of_peaks = peaks['chr'].unique()
chrs = np.intersect1d(chrs_of_promoters, chrs_of_peaks)
genes_id = []
for chr_ in chrs:
chr_peaks = pd.DataFrame(peaks[peaks['chr'] == chr_])
chr_promoters = pd.DataFrame(promoters[promoters['chr'] == chr_])
for index, peak in chr_peaks.iterrows():
genes_id += overlap(peak, chr_promoters)
return(genes_id)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--gtf', action='store', dest='gtf',
required=True, help='path to GTF file')
parser.add_argument('-p', '--peaks', action='store', dest='peaks',
required=True, help='path to peaks file')
parser.add_argument('-o', '--output', action='store', dest='genes_id',
required=True, help='path to txt file to write genes_id')
parser.add_argument('-l', '--left', action='store', type=int, dest='left',
default=2000, required=False, help='left_tail + TSS, default_value = 2000')
parser.add_argument('-r', '--right', action='store', type=int, dest='rigth',
default=-2000, required=False, help='TSS + rigth_tail, default_value = -2000')
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
return(parser.parse_args())
def write_results(out, res):
#res = [i.capitalize() for i in res]
res = [i.split('.')[0] for i in res]
with open(out, 'w') as file:
for gene_id in res:
file.write(gene_id + '\n')
def main():
args = parse_args()
gtf_path = args.gtf
peaks_path = args.peaks
left = args.left
rigth = args.rigth
out = args.genes_id
gtf = read_gtf(gtf_path)
promoters = get_promoters(gtf, left=left, rigth=rigth)
promoters = promoters.sort_values(by=['chr', 'start'])
peaks = read_peaks(peaks_path)
peaks = peaks.sort_values(by=['chr', 'start'])
res = peaks_intersect_genes(peaks, promoters)
#res = np.unique(res)
write_results(out, res)
if __name__ == '__main__':
main()