bio-allo 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bio-allo might be problematic. Click here for more details.

@@ -0,0 +1,4 @@
1
+ from . import predictPeak
2
+ from . import allocation
3
+
4
+ __version__ = '1.0'
bio-allo-1.0/Allo/allo ADDED
@@ -0,0 +1,363 @@
1
+ #Lexi Morrissey, Mahony Lab @ Pennsylvania State University
2
+ #Last updated 03.06.2023
3
+ #Main method for Allo. Splits the sam files up and sends them to allocation procedure via multiprocessing package.
4
+
5
+ #Arguments
6
+ import argparse
7
+ parser = argparse.ArgumentParser(prog = 'Allo', \
8
+ description = 'Allo is a software that allocates multi-mapped reads in ChIP-seq data\n' \
9
+ 'Developed by Alexis Morrissey, Mahony Laboratory @ The Pennsylvania State University', \
10
+ epilog= 'For more pre-processing info and basic usage, please visit https://github.com/seqcode/allo')
11
+ parser.add_argument('input')
12
+ parser.add_argument('-seq', type=str, nargs=1, help='Single-end or paired-end sequencing mode', \
13
+ choices=['pe','se'], required=True, dest='seq')
14
+ parser.add_argument('-o', type=str, nargs=1, help='Output file name', dest='outfile', default=None)
15
+ parser.add_argument('--mixed', help='Use CNN trained on a dataset with mixed peaks, narrow by default', action='store_true', default=None)
16
+ parser.add_argument('-p', type=int, nargs=1, help='Number of processes, 1 by default', dest='processes', default=None)
17
+ parser.add_argument('-max', type=int, nargs=1, help='Maximum value for number of locations a read can map', dest='maxlocations', default=None)
18
+ parser.add_argument('--keep-unmap', help='Keep unmapped reads and reads that include N in their sequence', action='store_true', default=None)
19
+ parser.add_argument('--remove-zeros', help='Disregard multi-mapped reads that map to regions with 0 uniquely mapped reads (random assignment)', action='store_true', default=None)
20
+ parser.add_argument('--r2', help='Use read 2 for allocation procedure instead of read 1 (only for paired-end sequencing)', action='store_true', default=None)
21
+ parser.add_argument('--readcount', help='CNN will not be used in allocation, only read counts', action='store_true', default=None)
22
+ parser.add_argument('--random', help='Reads will be randomly assigned (similar to Bowtie and BWA on default)', action='store_true', default=None)
23
+ parser.add_argument('--ignore', help='Ignore warnings about read sorting', action='store_true', default=None)
24
+ parser.add_argument('--parser', help='Ignore warnings about read sorting', action='store_true', default=None)
25
+ args = parser.parse_args()
26
+
27
+ #Imports
28
+ import sys
29
+ from joblib import Parallel, delayed
30
+ import multiprocessing
31
+ import subprocess
32
+ import os
33
+ from Allo import allocation
34
+ import math
35
+ from random import randint
36
+ import shutil
37
+ import glob
38
+ import pysam
39
+ import shutil
40
+ import pkgutil
41
+ import Allo
42
+
43
+
44
+ #Function for concatenating files
45
+ def cat(files, outname):
46
+ with open(outname,'wb') as wfd:
47
+ for f in files:
48
+ with open(f,'rb') as fd:
49
+ shutil.copyfileobj(fd, wfd)
50
+
51
+ ##Main Method##
52
+ if __name__ == '__main__':
53
+
54
+ print("\nRunning Allo version 1.0\n\n")
55
+
56
+ #Make a folder to store all temp files in allo
57
+ ids = str(randint(0, 10000))
58
+ curr_dir = os.getcwd()
59
+ allo_dir = os.path.join(curr_dir, r'allo.'+ids)
60
+ if not os.path.exists(allo_dir):
61
+ os.makedirs(allo_dir)
62
+
63
+ #Input name and bam conversion if necessary
64
+ try:
65
+ samfile = args.input
66
+ except:
67
+ print("SAM/BAM file not given or PySam does not recognize format of file.")
68
+ #Convert from bam to sam if necessary
69
+ if not ".sam" in samfile and not ".SAM" in samfile:
70
+ pysam.set_verbosity(0) #Pysam outputs a warning about indexing
71
+ infile = pysam.AlignmentFile(samfile, "rb")
72
+ outfile = pysam.AlignmentFile(allo_dir+"/"+ids+".sam", "w", template=infile)
73
+ for rec in infile:
74
+ outfile.write(rec)
75
+ samfile = allo_dir+"/"+ids+".sam"
76
+ #Output name
77
+ if args.outfile is not None:
78
+ outfile = args.outfile[0]
79
+ else:
80
+ outfile = args.input[:-4] + ".allo.sam"
81
+ #Model and window size
82
+ if args.mixed is not None:
83
+ d = os.path.dirname(sys.modules["Allo"].__file__)
84
+ m = os.path.join(d, "mixed")
85
+ winSize = 500
86
+ else:
87
+ d = os.path.dirname(sys.modules["Allo"].__file__)
88
+ m = os.path.join(d, "narrow")
89
+ winSize = 500
90
+ #Number of threads
91
+ if args.processes is not None:
92
+ thr = args.processes[0]
93
+ else:
94
+ thr = 1
95
+ #Single or paired end
96
+ if args.seq[0] == "se":
97
+ seq = 1
98
+ elif args.seq[0] == "pe":
99
+ seq = 0
100
+ #Options for probabilities
101
+ if args.readcount is not None:
102
+ rc = 1
103
+ elif args.random is not None:
104
+ rc = 2
105
+ else:
106
+ rc = 0
107
+ #Keep unmapped reads
108
+ if args.keep_unmap is not None:
109
+ keep = 1
110
+ else:
111
+ keep = 0
112
+ #Remove reads that only map to zero regions
113
+ if args.remove_zeros is not None:
114
+ rmz = 1
115
+ else:
116
+ rmz = 0
117
+ #User defined max number of alignments
118
+ if args.maxlocations is not None:
119
+ maxa = args.maxlocations[0]
120
+ else:
121
+ maxa = None
122
+ #Use read 2 instead of read 1 for allocation
123
+ if args.r2 is not None:
124
+ r2 = 1
125
+ else:
126
+ r2 = 0
127
+ #Ignore allo warnings
128
+ if args.ignore is not None:
129
+ ig = 1
130
+ else:
131
+ ig = 0
132
+ #Use allo's parser function only
133
+ if args.parser is not None:
134
+ parse = 1
135
+ else:
136
+ parse = 0
137
+
138
+
139
+ #Getting header information and checking to see if file was sorted
140
+ collate = 0
141
+ f = open(samfile)
142
+ header = open(allo_dir+'/header', 'a')
143
+ for line in f:
144
+ if line.startswith('@'):
145
+ header.write(line)
146
+ if "collate" in line:
147
+ collate = 1
148
+ else:
149
+ break
150
+ f.close()
151
+ header.close()
152
+ if collate == 0 and ig == 0:
153
+ print("Warning: PG tag with collate not present in header. File does not appear to be sorted.")
154
+ print("Please use Samtools collate before running Allo. To ignore this warning use argument --ignore")
155
+ sys.exit(0)
156
+
157
+
158
+ #Need list of file names
159
+ tempList = []
160
+ for i in range (0,thr):
161
+ tempList.append(allo_dir+"/allo.temp." + ids + "." + str(i).zfill(2))
162
+
163
+ #Get number of lines
164
+ count = 0
165
+ file = open(samfile, 'rb')
166
+ while True:
167
+ buffer = file.read(8192*1024)
168
+ if not buffer: break
169
+ count += buffer.count('\n'.encode())
170
+ file.close()
171
+
172
+
173
+ #Splitting up file
174
+ size = int(count/len(tempList))
175
+ f = open(samfile)
176
+ linec = 0
177
+ i = 0
178
+ filen = open(tempList[0], 'a')
179
+ for line in f:
180
+ if linec <= size:
181
+ filen.write(line)
182
+ linec = linec + 1
183
+ else:
184
+ filen.write(line)
185
+ filen.close()
186
+ linec = 0
187
+ i = i + 1
188
+ filen = open(tempList[i], 'a')
189
+ filen.close()
190
+
191
+
192
+ #Getting column where alignment score is stored in sam (different for every aligner). If none listed assumes bowtie1 -m 1 -k x
193
+ with open(tempList[-1]) as f:
194
+ for line in f:
195
+ if not line.startswith("@") and not line[2] == "*":
196
+ l = line
197
+ break
198
+ AS = 0
199
+ l = l.split('\t')
200
+ for i in range(0,len(l)):
201
+ if l[i].startswith("AS:"):
202
+ AS = i
203
+
204
+ ##Single-end mode##
205
+ if seq == 1:
206
+ #PHASE I: Parsing unique reads and putting into dictionary
207
+ cnn_scores = {} #Used to keep some previous scores for places in the genome by the cnn to save time
208
+ info = Parallel(n_jobs=thr)(delayed(allocation.parseUniq)(i, winSize, cnn_scores, AS, rc, keep) for i in tempList)
209
+ #Need to run allocation on border reads
210
+ if len(tempList) >= 1:
211
+ l = []
212
+ for i in tempList:
213
+ if os.path.exists(str(i)+"B"):
214
+ l.append(i + "B")
215
+ cat(l,tempList[0]+".borders")
216
+ else:
217
+ os.rename(tempList[0] + 'B', tempList[0]+".borders")
218
+
219
+ info.append(allocation.parseUniq(tempList[0]+".borders", winSize, cnn_scores, AS, rc, keep))
220
+ #Cat with first MM file
221
+ cat([tempList[0]+'MM', tempList[0]+'.bordersMM'], tempList[0]+'.catborders')
222
+ #Fix name
223
+ os.rename(tempList[0]+'.catborders', tempList[0]+'MM')
224
+ #Cat with first UM file
225
+ cat([tempList[0]+'UM', tempList[0]+'.bordersUM'], tempList[0]+'.catborders')
226
+ #Fix name
227
+ os.rename(tempList[0]+".catborders", tempList[0]+"UM")
228
+ #Remove old files
229
+ for filename in glob.glob('./*borders*'):
230
+ os.remove(filename)
231
+
232
+ #Add all values to UMR dictionary
233
+ genLand = {}
234
+ if parse == 0:
235
+ for i in tempList:
236
+ if os.path.exists(str(i)+"UM"):
237
+ allocation.addToDict(str(i)+"UM", genLand, seq)
238
+
239
+ else: #Stopping if parsing only
240
+ l = [allo_dir+"/header"]
241
+ for i in tempList:
242
+ if os.path.exists(str(i)+"UM"):
243
+ l.append(i + "UM")
244
+ cat(l, args.input[:-4]+".allo.UMR_only.sam")
245
+ l = [allo_dir+"/header"]
246
+ for i in tempList:
247
+ if os.path.exists(str(i)+"MM"):
248
+ l.append(i + "MM")
249
+ cat(l, args.input[:-4]+".allo.MMR_only.sam")
250
+ shutil.rmtree(allo_dir)
251
+ sys.exit(0)
252
+
253
+ print("Parsing finished!\n")
254
+
255
+ #PHASE II: Parsing multi-mapped reads
256
+ info2 = Parallel(n_jobs=thr)(delayed(allocation.parseMulti)(i, winSize, genLand, m, cnn_scores, rc, keep, rmz, maxa) for i in tempList)
257
+
258
+
259
+ #Final parsing and file clean up
260
+ #Deleting temporary files and join allocated files
261
+ l = [allo_dir+"/header"]
262
+ for i in tempList:
263
+ if os.path.exists(str(i)+"AL"):
264
+ l.append(i + "AL")
265
+ l.append(i + "UM")
266
+ cat(l, outfile)
267
+
268
+ shutil.rmtree(allo_dir)
269
+
270
+ #Print out useful info
271
+ print("Allocation finished!\n")
272
+ run = [0,0,0,0]
273
+ for i in info:
274
+ run[0] = run[0] + i[0]
275
+ run[1] = run[1] + i[1]
276
+ for i in info2:
277
+ run[2] = run[2] + i[0]
278
+ run[3] = run[3] + i[1]
279
+ run[2] = math.ceil(run[2]/len(info2))
280
+ print("Total uniquely mapped reads analyzed: " + str(run[0]))
281
+ print("Total number of reads allocated: " + str(run[3]))
282
+ print("Total number of reads filtered (use --keep-unmap to disable filtering): " + str(run[1]))
283
+ print("Average number of alignments for reads (affected by -max): " + str(run[2])+"\n\n\n")
284
+
285
+
286
+
287
+
288
+ ##Paired-end mode##
289
+ if seq == 0:
290
+
291
+ #PHASE I: Parsing unique reads and putting into dictionary
292
+ cnn_scores = {} #Used to keep some previous scores for places in the genome by the cnn to save time
293
+ info = Parallel(n_jobs=thr)(delayed(allocation.parseUniqPE)(i, winSize, cnn_scores, AS, rc, keep, r2) for i in tempList)
294
+
295
+ #Need to run allocation on border reads
296
+ if len(tempList) >= 1:
297
+ l = []
298
+ for i in tempList:
299
+ if os.path.exists(str(i)+"B"):
300
+ l.append(i + "B")
301
+ cat(l, tempList[0]+".borders")
302
+ else:
303
+ os.rename(tempList[0]+'B', tempList[0]+".borders")
304
+ info.append(allocation.parseUniqPE(tempList[0]+".borders", winSize, cnn_scores, AS, rc, keep, r2))
305
+ #Cat with first MM file
306
+ cat([tempList[0]+'MM', tempList[0]+'.bordersMM'], tempList[0]+'.catborders')
307
+ #Fix name
308
+ os.rename(tempList[0]+'.catborders', tempList[0]+'MM')
309
+ #Cat with first UM file
310
+ cat([tempList[0]+'UM', tempList[0]+'.bordersUM'], tempList[0]+'.catborders')
311
+ #Fix name
312
+ os.rename(tempList[0]+".catborders", tempList[0]+"UM")
313
+
314
+ #Add all values to UMR dictionary unless only parsing
315
+ genLand = {}
316
+ if parse == 0:
317
+ for i in tempList:
318
+ if os.path.exists(str(i)+"UM"):
319
+ allocation.addToDict(str(i)+"UM", genLand, seq)
320
+ else:
321
+ l = [allo_dir+"/header"]
322
+ for i in tempList:
323
+ if os.path.exists(str(i)+"UM"):
324
+ l.append(i + "UM")
325
+ cat(l, args.input[:-4]+".allo.UMR_only.sam")
326
+ l = [allo_dir+"/header"]
327
+ for i in tempList:
328
+ if os.path.exists(str(i)+"MM"):
329
+ l.append(i + "MM")
330
+ cat(l, args.input[:-4]+".allo.MMR_only.sam")
331
+ shutil.rmtree(allo_dir)
332
+ sys.exit(0)
333
+
334
+ print("Parsing finished!\n")
335
+
336
+ #PHASE II: Parsing multi-mapped reads
337
+ info2 = Parallel(n_jobs=thr)(delayed(allocation.parseMultiPE)(i, winSize, genLand, m, cnn_scores, rc, keep, rmz, maxa) for i in tempList)
338
+
339
+ #Final parsing and file clean up
340
+ #Deleting temporary files and join allocated files
341
+ l = [allo_dir+"/header"]
342
+ for i in tempList:
343
+ if os.path.exists(str(i)+"AL"):
344
+ l.append(i + "AL")
345
+ l.append(i + "UM")
346
+ cat(l, outfile)
347
+
348
+ shutil.rmtree(allo_dir)
349
+
350
+ #Print out useful info
351
+ print("Allocation finished!\n")
352
+ run = [0,0,0,0]
353
+ for i in info:
354
+ run[0] = run[0] + i[0]
355
+ run[1] = run[1] + i[1]
356
+ for i in info2:
357
+ run[2] = run[2] + i[0]
358
+ run[3] = run[3] + i[1]
359
+ run[2] = math.ceil(run[2]/len(info2))
360
+ print("Total uniquely mapped pairs analyzed: " + str(run[0]))
361
+ print("Total number of pairs allocated: " + str(run[3]))
362
+ print("Total number of reads filtered (use --keep-unmap to disable filtering): " + str(run[1]))
363
+ print("Average number of alignments for multi-mapped pairs (affected by -max): " + str(run[2])+"\n\n\n")