-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbedgen.py
78 lines (63 loc) · 2.11 KB
/
bedgen.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
"""
This module contains functions for creating the contents of the BED file and
writing it to disk
"""
import csv
def create_bed_contents(lrg_object, introns_choice):
"""Creates the contents for the BED file. Returns a nested list with
each row being [chromosome, start, end, label]
Args:
lrg_object (dict): An LRG_Object containing LRG ID, HGNC name etc
introns_choice (bool): Include introns True or False
Returns:
bedcontents (list): Nested list of rows [chromosome, start, end, label]
"""
bedcontents = []
# Adds exon rows
for item in lrg_object.mapped_flanked_exon_coords:
chromosome = "chr"+lrg_object.chromosome
start = lrg_object.mapped_flanked_exon_coords[item][0]
end = lrg_object.mapped_flanked_exon_coords[item][1]
label = "Exon_"+str(item)
if start > end:
start, end = end, start
else:
pass
bedcontents.append([chromosome, start, end, label])
# Adds intron rows if specified on the command line or in the UI
if introns_choice == True:
for item in lrg_object.mapped_intron_coords:
chromosome = "chr"+lrg_object.chromosome
start = lrg_object.mapped_intron_coords[item][0]
end = lrg_object.mapped_intron_coords[item][1]
if start > end:
start, end = end, start
else:
pass
label = "Intron_"+str(item)
bedcontents.append([chromosome, start, end, label])
return bedcontents
def write_bed_file(filetowrite, bedheader, bedcontents):
"""Writes the BED header and contents to file.
Args:
filetowrite (str): The filename to write to
bedheader (list): The header to write. List of strings
bedcontents (list): Nested list of rows [chromosome, start, end, label]
Returns:
True if BED file written successfully
Raises:
SystemExit: If the file could not be written
"""
try:
with open(filetowrite, 'w', newline='') as csv_file:
writer = csv.writer(csv_file, delimiter="\t")
writer.writerow(bedheader)
for line in bedcontents:
writer.writerow(line)
print("")
print(" BED file successfully written to " + filetowrite)
print("")
return True
except:
print(" Could not write BED file. Check write permissions")
raise SystemExit