-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_db.py
More file actions
427 lines (373 loc) · 15.4 KB
/
build_db.py
File metadata and controls
427 lines (373 loc) · 15.4 KB
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
'''
Author: Saideep Gona
This script is intended to populate the given database from local files
'''
from application_for_build_db import db
from application_for_build_db import ChIP_Meta, Peaks, Presets
import glob
import os
import sys
import pickle
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import unicodedata
import multiprocessing
plt.ion()
# plt.use('Agg')
# IO ************************************************************
pwd = os.getcwd()
num_cpus = multiprocessing.cpu_count()
if len(sys.argv) > 1:
peak_dir = sys.argv[1]
metadata_dir = sys.argv[2]
metrics_dir = sys.argv[3]
peak_file = sys.argv[4]
motif_occ_dir = sys.argv[5]
motif_occ_file = sys.argv[6]
else:
peak_dir = pwd + "/pass_peaks/"
metadata_path = pwd + "/pass_metadata/metadata.pkl"
metrics_dir = pwd + "/static/images/"
peak_file = pwd + "/all_peaks.tsv"
motif_occ_dir = pwd + "/pass_motifs/"
motif_occ_file = pwd + "/all_motif_occs.tsv"
if os.path.isfile(peak_file):
os.remove(peak_file)
os.system("touch "+peak_file)
else:
os.system("touch "+peak_file)
if os.path.isfile(motif_occ_file):
os.remove(motif_occ_file)
os.system("touch "+motif_occ_file)
else:
os.system("touch "+motif_occ_file)
peak_bool = True
motif_bool = False
# IO END *********************************************************
def find_duplicates(in_list):
unique = set(in_list)
# print(unique)
for each in unique:
count = in_list.count(each)
if count > 1:
print ("duplicate: " + each + " " + count)
def histogram(field, data, metrics_dir):
# print(data, "d for h")
plt.rc('axes',edgecolor='white')
plt.rc('lines', color='white')
plt.rc('text', color='white')
plt.rc('xtick', color='white')
plt.rc('ytick', color='white')
np_data = np.array(data)
plt.hist(data, color = 'white', bins = 50)
plt.xlabel("Bin Ranges", color='white')
plt.ylabel("Frequency", color='white')
plt.title("Distribution of "+field+" values across all peaks in database")
# field = "_".join(metrics_dir.split(" "))
savefile = metrics_dir + "/" + field + "_hist.png"
# print(savefile)
plt.savefig(savefile, transparent=True)
plt.clf()
def slugify(value):
"""
Mini version of slugify which just converts spaces to underscores
"""
new_val = ""
for char in value:
if char == " ":
new_val += "_"
else:
new_val += char
return new_val
def setify(in_list):
return list(set(in_list))
def log_p_conv(num):
# print("converting: " + num)
flo = float(num)
log = np.log10(flo)
return (-1.0) * log
# MAIN ***********************************************************
db.create_all()
# Read in metadata
metadata_dict = pickle.load(open(metadata_path, "rb"))
metadata_dict_ref = {}
find_duplicates(list(metadata_dict.keys()))
print(len(list(metadata_dict.keys())), " NUMBER OF STUDIES")
# sys.exit()
# print(metadata_files)
for m_f in list(metadata_dict.keys()): # This loop updates the metadata database information with current metadata
# print(m_f)
print(metadata_dict[m_f])
tissue_obj = metadata_dict[m_f]["tissue"] # If list of tissues, creates duplicate entries for each
if type(tissue_obj) == list:
tissue_obj = setify(tissue_obj)
if len(tissue_obj) == 0:
tissue = "NA"
meta = ChIP_Meta(
experiment_accession = m_f,
tissue_types = tissue,
transcription_factors = metadata_dict[m_f]["tf"]
)
metadata_dict_ref[m_f] = [tissue_obj, metadata_dict[m_f]["tf"]]
# print(meta)
db.session.add(meta)
else:
tissue_obj = setify(tissue_obj)
for tissue_p in tissue_obj:
tissue = slugify(tissue_p)
meta = ChIP_Meta(
experiment_accession = m_f,
tissue_types = tissue,
transcription_factors = metadata_dict[m_f]["tf"]
)
metadata_dict_ref[m_f] = [tissue_obj, metadata_dict[m_f]["tf"]]
# print(meta)
db.session.add(meta)
elif type(tissue_obj) == str: # Standard single tissue entry
tissue = slugify(tissue_obj)
# print(tissue)
meta = ChIP_Meta(
experiment_accession = m_f,
tissue_types = tissue,
transcription_factors = metadata_dict[m_f]["tf"]
)
metadata_dict_ref[m_f] = [tissue_obj, metadata_dict[m_f]["tf"]]
print(meta)
db.session.add(meta)
else:
continue
db.session.commit()
# Read in and group all peak files that have already been filtered into the "pass peaks directory"
if peak_bool:
with open(peak_file, "a") as p_file:
peak_id_count = 0
pileup = []
p_values = []
fold_enrichment = []
q_values = []
full_peak_array = []
peak_files = glob.glob(peak_dir+"/*")
print(peak_files)
p_f_count = 1
for p_f in peak_files:
print(p_f_count, "pfcount")
print(p_f)
p_f_count += 1
# if peak_id_count > 100:
# print("peak id break")
# break
with open(p_f, "r") as pre_f:
if p_f[0:3] == "EXP":
f = pre_f.readlines()
else:
f = pre_f.readlines()[24:]
for line in f:
p_l = line.rstrip("\n").split("\t")
if len(p_l) < 10:
print("length wrong")
continue
try:
int(p_l[1])
except:
continue
exp_acc = p_f.rstrip("_peaks.xls").split("/")[-1]
if exp_acc not in metadata_dict_ref:
print(exp_acc, " not in metadata!")
continue
if p_l[1] == "0":
print(p_l, "0 start")
# sys.exit()
pileup.append(float(p_l[5]))
p_values.append(float(p_l[6]))
fold_enrichment.append(float(p_l[7]))
q_values.append(float(p_l[8]))
# Handle multiple tissue-specification entries
tissue_obj = metadata_dict_ref[exp_acc][0]
if type(tissue_obj) == list:
# print(tissue_obj)
if len(tissue_obj) == 0:
tissue = "NA"
else:
for tissue_p in tissue_obj:
tissue = slugify(tissue_p)
write_dict = {
"experiment_accession": p_f.rstrip("_peaks.xls").split("/")[-1],
"tissue_types": tissue,
"transcription_factors": metadata_dict_ref[exp_acc][1],
"chrom": p_l[0],
"start": str(int(p_l[1]) - 1),
"end": str(int(p_l[2]) - 1),
"length": p_l[3],
"summit": str(int(p_l[4]) - 1),
"pileup": p_l[5],
"log_p": p_l[6],
"fold_enrichment": p_l[7],
"log_q": p_l[8],
"id": peak_id_count
}
peak_id_count+=1
peaks_column_list = [
"chrom",
"start",
"end",
"id",
"length",
"summit",
"pileup",
"log_p",
"fold_enrichment",
"log_q",
"transcription_factors",
"tissue_types",
"experiment_accession",
]
write_list = [str(write_dict[x]) for x in peaks_column_list]
p_file.write("\t".join(write_list)+"\n")
# full_peak_array.append(write_list)
# peak = Peaks(
# experiment_accession = p_f.rstrip("_peaks.xls").split("/")[-1],
# tissue_types = tissue,
# transcription_factors = metadata_dict_ref[exp_acc][1],
# chrom = p_l[0],
# start = str(int(p_l[1]) - 1),
# end = str(int(p_l[2]) - 1),
# length = p_l[3],
# summit = str(int(p_l[4]) - 1),
# pileup = p_l[5],
# log_p = p_l[6],
# fold_enrichment = p_l[7],
# log_q = p_l[8]
# )
# db.session.add(peak)
elif type(tissue_obj) == str: # Standard single tissue entry
tissue = slugify(tissue_obj)
# Peak columns:
# chr start end length summit pileup -log_p fold_enrichment -log_q
write_dict = {
"experiment_accession": p_f.rstrip("_peaks.xls").split("/")[-1],
"tissue_types": tissue,
"transcription_factors": metadata_dict_ref[exp_acc][1],
"chrom": p_l[0],
"start": str(int(p_l[1]) - 1),
"end": str(int(p_l[2]) - 1),
"length": p_l[3],
"summit": str(int(p_l[4]) - 1),
"pileup": p_l[5],
"log_p": p_l[6],
"fold_enrichment": p_l[7],
"log_q": p_l[8],
"id": peak_id_count
}
peak_id_count += 1
peaks_column_list = [
"chrom",
"start",
"end",
"id",
"length",
"summit",
"pileup",
"log_p",
"fold_enrichment",
"log_q",
"transcription_factors",
"tissue_types",
"experiment_accession",
]
write_list = [str(write_dict[x]) for x in peaks_column_list]
p_file.write("\t".join(write_list)+"\n")
# full_peak_array.append(write_list)
# peak = Peaks(
# experiment_accession = p_f.rstrip("_peaks.xls").split("/")[-1],
# tissue_types = tissue,
# transcription_factors = metadata_dict_ref[exp_acc][1],
# chrom = p_l[0],
# start = str(int(p_l[1]) - 1),
# end = str(int(p_l[2]) - 1),
# length = p_l[3],
# summit = str(int(p_l[4]) - 1),
# pileup = p_l[5],
# log_p = p_l[6],
# fold_enrichment = p_l[7],
# log_q = p_l[8]
# )
# print(peak)
# db.session.add(peak)
# db.session.commit()
print(num_cpus)
os.system("split --number=l/"+str(num_cpus)+" "+peak_file+" "+peak_file+"_")
peak_fields = {
"pileup": pileup,
"-log_p": p_values,
"fold_enrichment": fold_enrichment,
"-log_q": q_values
}
for field in peak_fields.keys():
histogram(field, peak_fields[field], metrics_dir)
# Move over the motif occurences
# Motif processing steps
# 1.) Download PWMs to: (/motifs/motif_dir)
# 2.) Run find_motif_sites.py (/motifs/find_motif_sites.py)
# 3.) Run convert_occs_to_bed.py (/motifs/convert_occs_to_bed.py)
# 4.) Download DNase-Seq footprints to: (/gtrd_raw_footprints/)
# 5.) Run convert_gtrd.py (/convert_gtrd.py)
# Creates tissue-specific mappings using footprints
motif_occ_files = glob.glob(motif_occ_dir + "/*")
# motif_occ_files = [x.split("/")[-1] for x in motif_occ_files_glob]
print(motif_occ_files)
if motif_bool:
score = []
p_values = []
motif_id_count = 0
for mof in motif_occ_files:
print(mof)
mof_split = mof.split("/")[-1]
tf = mof_split.split("_")[0]
tissue = mof_split.split("_")[1]
with open(motif_occ_file, "a") as out:
with open(mof, "r") as m:
line_count = 1
p_title = motif_occ_file.split("\t")[-1].split("_")
for line in m:
if line_count == 1:
line_count+=1
continue
line_count += 1
# print(line)
p_l = line.rstrip("\n").split("\t")
write_dict = {
"tissue_types": tissue,
"transcription_factors": tf,
"chrom": p_l[0],
"start": str(int(p_l[1]) - 1),
"end": str(int(p_l[2]) - 1),
"length": p_l[3],
"score": p_l[5],
"log_p": str((-1)*log_p_conv(p_l[6])),
"id": motif_id_count
}
column_list = [
"chrom",
"start",
"end",
"id",
"length",
"score",
"log_p",
"transcription_factors",
"tissue_types"
]
score.append(float(p_l[5]))
p_values.append((-1)*log_p_conv(p_l[6]))
write_list = [str(write_dict[x]) for x in column_list]
out.write("\t".join(write_list)+"\n")
motif_id_count += 1
motif_fields = {
"motif_score": score,
"-log_p_motif": p_values
}
for field in motif_fields.keys():
histogram(field, motif_fields[field], metrics_dir)
# END MAIN ********************************************************