1
|
1 #!/home/jjjjia/.conda/envs/py36/bin/python
|
|
2
|
|
3 #$ -S /home/jjjjia/.conda/envs/py36/bin/python
|
|
4 #$ -V # Pass environment variables to the job
|
|
5 #$ -N CPO_pipeline # Replace with a more specific job name
|
|
6 #$ -wd /home/jjjjia/testCases # Use the current working dir
|
|
7 #$ -pe smp 8 # Parallel Environment (how many cores)
|
|
8 #$ -l h_vmem=11G # Memory (RAM) allocation *per core*
|
|
9 #$ -e ./logs/$JOB_ID.err
|
|
10 #$ -o ./logs/$JOB_ID.log
|
|
11 #$ -m ea
|
|
12 #$ -M bja20@sfu.ca
|
|
13
|
3
|
14 #./prediction.py -i ~/testCases/cpoResults/contigs/BC11-Kpn005_S2.fa -m ~/testCases/predictionResultsQsubTest/predictions/BC11-Kpn005_S2.mlst -c ~/testCases/predictionResultsQsubTest/predictions/BC11-Kpn005_S2.recon/contig_report.txt -f ~/testCases/predictionResultsQsubTest/predictions/BC11-Kpn005_S2.recon/mobtyper_aggregate_report.txt -a ~/testCases/predictionResultsQsubTest/predictions/BC11-Kpn005_S2.cp -r ~/testCases/predictionResultsQsubTest/predictions/BC11-Kpn005_S2.rgi.txt -e "Klebsiella"
|
1
|
15 import subprocess
|
|
16 import pandas
|
|
17 import optparse
|
|
18 import os
|
|
19 import datetime
|
|
20 import sys
|
|
21 import time
|
|
22 import urllib.request
|
|
23 import gzip
|
|
24 import collections
|
|
25 import json
|
|
26 import numpy
|
|
27
|
|
28
|
6
|
29 debug = False #debug skips the shell scripts and also dump out a ton of debugging messages
|
1
|
30
|
|
31 if not debug:
|
|
32 #parses some parameters
|
|
33 parser = optparse.OptionParser("Usage: %prog [options] arg1 arg2 ...")
|
|
34 #required
|
3
|
35 #MLSTHIT, mobsuite, resfinder, rgi, mlstscheme
|
1
|
36 parser.add_option("-i", "--id", dest="id", type="string", help="identifier of the isolate")
|
3
|
37 parser.add_option("-m", "--mlst", dest="mlst", type="string", help="absolute file path to mlst result")
|
|
38 parser.add_option("-c", "--mobfinderContig", dest="mobfinderContig", type="string", help="absolute path to mobfinder aggregate result")
|
|
39 parser.add_option("-f", "--mobfinderAggregate", dest="mobfinderAggregate", type="string", help="absolute path to mobfinder plasmid results")
|
|
40 parser.add_option("-a", "--abricate", dest="abricate", type="string", help="absolute path to abricate results")
|
|
41 parser.add_option("-r", "--rgi", dest="rgi", type="string", help="absolute path to rgi results")
|
1
|
42 parser.add_option("-e", "--expected", dest="expectedSpecies", default="NA/NA/NA", type="string", help="expected species of the isolate")
|
3
|
43 parser.add_option("-s", "--mlst-scheme", dest="mlstScheme", default= "./scheme_species_map.tab", type="string", help="absolute file path to mlst scheme")
|
|
44 parser.add_option("-p", "--plasmidfinder", dest="plasmidfinder", type="string", help="absolute file path to plasmidfinder ")
|
21
|
45 parser.add_option("-d", "--mash", dest="mash", type="string", help="absolute file path to mash plasmiddb result")
|
1
|
46
|
|
47 #parallelization, useless, these are hard coded to 8cores/64G RAM
|
|
48 #parser.add_option("-t", "--threads", dest="threads", default=8, type="int", help="number of cpu to use")
|
|
49 #parser.add_option("-p", "--memory", dest="memory", default=64, type="int", help="memory to use in GB")
|
|
50
|
|
51 (options,args) = parser.parse_args()
|
|
52 #if len(args) != 8:
|
|
53 #parser.error("incorrect number of arguments, all 7 is required")
|
|
54 curDir = os.getcwd()
|
3
|
55 ID = str(options.id).lstrip().rstrip()
|
|
56 mlst = str(options.mlst).lstrip().rstrip()
|
|
57 mobfindercontig = str(options.mobfinderContig).lstrip().rstrip()
|
|
58 mobfinderaggregate = str(options.mobfinderAggregate).lstrip().rstrip()
|
|
59 abricate = str(options.abricate).lstrip().rstrip()
|
|
60 rgi = str(options.rgi).lstrip().rstrip()
|
|
61 expectedSpecies = str(options.expectedSpecies).lstrip().rstrip()
|
|
62 mlstScheme = str(options.mlstScheme).lstrip().rstrip()
|
|
63 plasmidfinder = str(options.plasmidfinder).lstrip().rstrip()
|
18
|
64 mash = str(options.mash).lstrip().rstrip()
|
3
|
65 outputDir = "./"
|
|
66 print(mlst)
|
|
67 print(mobfindercontig)
|
|
68 print(mobfinderaggregate)
|
|
69 print(abricate)
|
|
70 print(rgi)
|
|
71 print(expectedSpecies)
|
|
72 print(mlstScheme)
|
18
|
73 print(mash)
|
|
74
|
1
|
75 else:
|
|
76 curDir = os.getcwd()
|
3
|
77 ID = "BC11"
|
|
78 mlst = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\BC11-Kpn005_S2.mlst"
|
|
79 mobfindercontig = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\BC11-Kpn005_S2.recon\contig_report.txt"
|
|
80 mobfinderaggregate = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\BC11-Kpn005_S2.recon\mobtyper_aggregate_report.txt"
|
|
81 abricate = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\BC11-Kpn005_S2.cp"
|
|
82 rgi = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\BC11-Kpn005_S2.rgi.txt"
|
1
|
83 expectedSpecies = "Escherichia coli"
|
3
|
84 mlstScheme = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\scheme_species_map.tab"
|
|
85 plasmidfinder = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\BC11-Kpn005_S2.origins"
|
18
|
86 mash = "D:\OneDrive\ProjectCDC\ProjectCDCInPython\ProjectCDCInPython\pipelineTest\predictions\mash.tsv"
|
3
|
87 outputDir = "./"
|
1
|
88
|
|
89 #region result objects
|
|
90 #define some objects to store values from results
|
|
91 #//TODO this is not the proper way of get/set private object variables. every value has manually assigned defaults intead of specified in init(). Also, use property(def getVar, def setVar).
|
|
92 class starFinders(object):
|
|
93 def __init__(self):
|
|
94 self.file = ""
|
|
95 self.sequence = ""
|
|
96 self.start = 0
|
|
97 self.end = 0
|
|
98 self.gene = ""
|
|
99 self.shortGene = ""
|
|
100 self.coverage = ""
|
|
101 self.coverage_map = ""
|
|
102 self.gaps = ""
|
|
103 self.pCoverage = 100.00
|
|
104 self.pIdentity = 100.00
|
|
105 self.database = ""
|
|
106 self.accession = ""
|
|
107 self.product = ""
|
|
108 self.source = "chromosome"
|
|
109 self.row = ""
|
|
110
|
|
111 class PlasFlowResult(object):
|
|
112 def __init__(self):
|
|
113 self.sequence = ""
|
|
114 self.length = 0
|
|
115 self.label = ""
|
|
116 self.confidence = 0
|
|
117 self.usefulRow = ""
|
|
118 self.row = ""
|
|
119
|
|
120 class MlstResult(object):
|
|
121 def __init__(self):
|
|
122 self.file = ""
|
|
123 self.speciesID = ""
|
|
124 self.seqType = 0
|
|
125 self.scheme = ""
|
|
126 self.species = ""
|
|
127 self.row=""
|
|
128
|
|
129 class mobsuiteResult(object):
|
|
130 def __init__(self):
|
|
131 self.file_id = ""
|
|
132 self.cluster_id = ""
|
|
133 self.contig_id = ""
|
|
134 self.contig_num = 0
|
|
135 self.contig_length = 0
|
|
136 self.circularity_status = ""
|
|
137 self.rep_type = ""
|
|
138 self.rep_type_accession = ""
|
|
139 self.relaxase_type = ""
|
|
140 self.relaxase_type_accession = ""
|
|
141 self.mash_nearest_neighbor = ""
|
|
142 self.mash_neighbor_distance = 0.00
|
|
143 self.repetitive_dna_id = ""
|
|
144 self.match_type = ""
|
|
145 self.score = 0
|
|
146 self.contig_match_start = 0
|
|
147 self.contig_match_end = 0
|
|
148 self.row = ""
|
|
149
|
|
150 class mobsuitePlasmids(object):
|
|
151 def __init__(self):
|
|
152 self.file_id = ""
|
|
153 self.num_contigs = 0
|
|
154 self.total_length = 0
|
|
155 self.gc = ""
|
|
156 self.rep_types = ""
|
|
157 self.rep_typeAccession = ""
|
|
158 self.relaxase_type= ""
|
|
159 self.relaxase_type_accession = ""
|
|
160 self.mpf_type = ""
|
|
161 self.mpf_type_accession= ""
|
|
162 self.orit_type = ""
|
|
163 self.orit_accession = ""
|
|
164 self.PredictedMobility = ""
|
|
165 self.mash_nearest_neighbor = ""
|
|
166 self.mash_neighbor_distance = 0.00
|
|
167 self.mash_neighbor_cluster= 0
|
|
168 self.row = ""
|
3
|
169
|
1
|
170 class RGIResult(object):
|
|
171 def __init__(self):
|
|
172 self.ORF_ID = ""
|
|
173 self.Contig = ""
|
|
174 self.Start = -1
|
|
175 self.Stop = -1
|
|
176 self.Orientation = ""
|
|
177 self.Cut_Off = ""
|
|
178 self.Pass_Bitscore = 100000
|
|
179 self.Best_Hit_Bitscore = 0.00
|
|
180 self.Best_Hit_ARO = ""
|
|
181 self.Best_Identities = 0.00
|
|
182 self.ARO = 0
|
|
183 self.Model_type = ""
|
|
184 self.SNPs_in_Best_Hit_ARO = ""
|
|
185 self.Other_SNPs = ""
|
|
186 self.Drug_Class = ""
|
|
187 self.Resistance_Mechanism = ""
|
|
188 self.AMR_Gene_Family = ""
|
|
189 self.Predicted_DNA = ""
|
|
190 self.Predicted_Protein = ""
|
|
191 self.CARD_Protein_Sequence = ""
|
|
192 self.Percentage_Length_of_Reference_Sequence = 0.00
|
|
193 self.ID = ""
|
|
194 self.Model_ID = 0
|
|
195 self.source = ""
|
|
196 self.row = ""
|
|
197
|
18
|
198 class MashResult(object):
|
|
199 def __init__(self):
|
|
200 self.size = 0.0
|
|
201 self.depth = 0.0
|
|
202 self.identity = 0.0
|
|
203 self.sharedHashes = ""
|
|
204 self.medianMultiplicity = 0
|
|
205 self.pvalue = 0.0
|
|
206 self.queryID= ""
|
|
207 self.queryComment = ""
|
|
208 self.species = ""
|
|
209 self.row = ""
|
|
210 self.accession = ""
|
|
211 self.gcf=""
|
|
212 self.assembly=""
|
|
213
|
|
214 def toDict(self): #doesnt actually work
|
|
215 return dict((name, getattr(self, name)) for name in dir(self) if not name.startswith('__'))
|
|
216
|
|
217
|
1
|
218 #endregion
|
|
219
|
|
220 #region useful functions
|
|
221 def read(path):
|
|
222 return [line.rstrip('\n') for line in open(path)]
|
|
223 def execute(command):
|
|
224 process = subprocess.Popen(command, shell=False, cwd=curDir, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
225
|
|
226 # Poll process for new output until finished
|
|
227 while True:
|
|
228 nextline = process.stdout.readline()
|
|
229 if nextline == '' and process.poll() is not None:
|
|
230 break
|
|
231 sys.stdout.write(nextline)
|
|
232 sys.stdout.flush()
|
|
233
|
|
234 output = process.communicate()[0]
|
|
235 exitCode = process.returncode
|
|
236
|
|
237 if (exitCode == 0):
|
|
238 return output
|
|
239 else:
|
|
240 raise subprocess.CalledProcessError(exitCode, command)
|
|
241 def httpGetFile(url, filepath=""):
|
|
242 if (filepath == ""):
|
|
243 return urllib.request.urlretrieve(url)
|
|
244 else:
|
|
245 urllib.request.urlretrieve(url, filepath)
|
|
246 return True
|
|
247 def gunzip(inputpath="", outputpath=""):
|
|
248 if (outputpath == ""):
|
|
249 with gzip.open(inputpath, 'rb') as f:
|
|
250 gzContent = f.read()
|
|
251 return gzContent
|
|
252 else:
|
|
253 with gzip.open(inputpath, 'rb') as f:
|
|
254 gzContent = f.read()
|
|
255 with open(outputpath, 'wb') as out:
|
|
256 out.write(gzContent)
|
|
257 return True
|
|
258 def ToJson(dictObject, outputPath):
|
3
|
259 #outDir = outputDir + '/summary/' + ID + ".json/"
|
|
260 #if not (os.path.exists(outDir)):
|
|
261 #os.makedirs(outDir)
|
|
262 #with open(outputPath, 'w') as f:
|
|
263 #json.dump([ob.__dict__ for ob in dictObject.values()], f, ensure_ascii=False)
|
|
264 return ""
|
1
|
265 #endregion
|
|
266
|
|
267 #region functions to parse result files
|
3
|
268 def ParseMLSTResult(pathToMLSTResult, scheme):
|
1
|
269 _mlstResult = {}
|
3
|
270 scheme = pandas.read_csv(scheme, delimiter='\t', header=0)
|
1
|
271 scheme = scheme.replace(numpy.nan, '', regex=True)
|
|
272
|
|
273 taxon = {}
|
|
274 #record the scheme as a dictionary
|
|
275 taxon["-"] = "No MLST Match"
|
|
276 for i in range(len(scheme.index)):
|
|
277 key = scheme.iloc[i,0]
|
|
278 if (str(scheme.iloc[i,2]) == "nan"):
|
|
279 value = str(scheme.iloc[i,1])
|
|
280 else:
|
|
281 value = str(scheme.iloc[i,1]) + " " + str(scheme.iloc[i,2])
|
|
282
|
|
283 if (key in taxon.keys()):
|
|
284 taxon[key] = taxon.get(key) + ";" + value
|
|
285 else:
|
|
286 taxon[key] = value
|
|
287 #read in the mlst result
|
|
288 mlst = pandas.read_csv(pathToMLSTResult, delimiter='\t', header=None)
|
|
289 _mlstHit = MlstResult()
|
|
290
|
|
291 _mlstHit.file = mlst.iloc[0,0]
|
|
292 _mlstHit.speciesID = (mlst.iloc[0,1])
|
|
293 _mlstHit.seqType = str(mlst.iloc[0,2])
|
|
294 for i in range(3, len(mlst.columns)):
|
|
295 _mlstHit.scheme += mlst.iloc[0,i] + ";"
|
|
296 _mlstHit.species = taxon[_mlstHit.speciesID]
|
|
297 _mlstHit.row = "\t".join(str(x) for x in mlst.ix[0].tolist())
|
|
298 _mlstResult[_mlstHit.speciesID]=_mlstHit
|
|
299
|
|
300 return _mlstResult
|
|
301
|
|
302 def ParsePlasmidFinderResult(pathToPlasmidFinderResult):
|
|
303 #pipelineTest/contigs/BC110-Kpn005.fa contig00019 45455 45758 IncFIC(FII)_1 8-308/499 ========/=..... 8/11 59.52 75.65 plasmidfinder AP001918 IncFIC(FII)_1__AP001918
|
|
304 #example resfinder:
|
|
305 #pipelineTest/contigs/BC110-Kpn005.fa contig00038 256 1053 OXA-181 1-798/798 =============== 0/0 100.00 100.00 bccdc AEP16366.1 OXA-48 family carbapenem-hydrolyzing class D beta-lactamase OXA-181
|
|
306
|
|
307 _pFinder = {} #***********************
|
|
308 plasmidFinder = pandas.read_csv(pathToPlasmidFinderResult, delimiter='\t', header=0)
|
|
309 plasmidFinder = plasmidFinder.replace(numpy.nan, '', regex=True)
|
|
310
|
|
311
|
|
312 for i in range(len(plasmidFinder.index)):
|
|
313 pf = starFinders()
|
|
314 pf.file = str(plasmidFinder.iloc[i,0])
|
|
315 pf.sequence = str(plasmidFinder.iloc[i,1])
|
|
316 pf.start = int(plasmidFinder.iloc[i,2])
|
|
317 pf.end = int(plasmidFinder.iloc[i,3])
|
|
318 pf.gene = str(plasmidFinder.iloc[i,4])
|
|
319 pf.shortGene = pf.gene[:pf.gene.index("_")]
|
|
320 pf.coverage = str(plasmidFinder.iloc[i,5])
|
|
321 pf.coverage_map = str(plasmidFinder.iloc[i,6])
|
|
322 pf.gaps = str(plasmidFinder.iloc[i,7])
|
|
323 pf.pCoverage = float(plasmidFinder.iloc[i,8])
|
|
324 pf.pIdentity = float(plasmidFinder.iloc[i,9])
|
|
325 pf.database = str(plasmidFinder.iloc[i,10])
|
|
326 pf.accession = str(plasmidFinder.iloc[i,11])
|
|
327 pf.product = str(plasmidFinder.iloc[i,12])
|
|
328 pf.source = "plasmid"
|
|
329 pf.row = "\t".join(str(x) for x in plasmidFinder.ix[i].tolist())
|
|
330 _pFinder[pf.gene]=pf
|
|
331 #row = "\t".join(str(x) for x in plasmidFinder.ix[i].tolist())
|
|
332 #plasmidFinderContigs.append(str(plasmidFinder.iloc[i,1]))
|
|
333 #origins.append(str(plasmidFinder.iloc[i,4][:plasmidFinder.iloc[i,4].index("_")]))
|
|
334 return _pFinder
|
|
335
|
|
336 def ParseMobsuiteResult(pathToMobsuiteResult):
|
|
337 _mobsuite = {}
|
|
338 mResult = pandas.read_csv(pathToMobsuiteResult, delimiter='\t', header=0)
|
|
339 mResult = mResult.replace(numpy.nan, '', regex=True)
|
|
340
|
|
341 for i in range(len(mResult.index)):
|
|
342 mr = mobsuiteResult()
|
|
343 mr.file_id = str(mResult.iloc[i,0])
|
|
344 mr.cluster_id = str(mResult.iloc[i,1])
|
|
345 if (mr.cluster_id == "chromosome"):
|
|
346 break
|
|
347 mr.contig_id = str(mResult.iloc[i,2])
|
|
348 mr.contig_num = mr.contig_id[(mr.contig_id.find("contig")+6):mr.contig_id.find("_len=")]
|
|
349 mr.contig_length = int(mResult.iloc[i,3])
|
|
350 mr.circularity_status = str(mResult.iloc[i,4])
|
|
351 mr.rep_type = str(mResult.iloc[i,5])
|
|
352 mr.rep_type_accession = str(mResult.iloc[i,6])
|
|
353 mr.relaxase_type = str(mResult.iloc[i,7])
|
|
354 mr.relaxase_type_accession = str(mResult.iloc[i,8])
|
|
355 mr.mash_nearest_neighbor = str(mResult.iloc[i,9])
|
|
356 mr.mash_neighbor_distance = float(mResult.iloc[i,10])
|
|
357 mr.repetitive_dna_id = str(mResult.iloc[i,11])
|
|
358 mr.match_type = str(mResult.iloc[i,12])
|
|
359 if (mr.match_type == ""):
|
|
360 mr.score = -1
|
|
361 mr.contig_match_start = -1
|
|
362 mr.contig_match_end = -1
|
|
363 else:
|
|
364 mr.score = int(mResult.iloc[i,13])
|
|
365 mr.contig_match_start = int(mResult.iloc[i,14])
|
|
366 mr.contig_match_end = int(mResult.iloc[i,15])
|
|
367 mr.row = "\t".join(str(x) for x in mResult.ix[i].tolist())
|
|
368 _mobsuite[mr.contig_id]=(mr)
|
|
369 return _mobsuite
|
|
370
|
|
371 def ParseMobsuitePlasmids(pathToMobsuiteResult):
|
|
372 _mobsuite = {}
|
|
373 mResults = pandas.read_csv(pathToMobsuiteResult, delimiter='\t', header=0)
|
|
374 mResults = mResults.replace(numpy.nan, '', regex=True)
|
|
375
|
|
376 for i in range(len(mResults.index)):
|
|
377 mr = mobsuitePlasmids()
|
|
378 mr.file_id = str(mResults.iloc[i,0])
|
|
379 mr.num_contigs = int(mResults.iloc[i,1])
|
|
380 mr.total_length = int(mResults.iloc[i,2])
|
|
381 mr.gc = int(mResults.iloc[i,3])
|
|
382 mr.rep_types = str(mResults.iloc[i,4])
|
|
383 mr.rep_typeAccession = str(mResults.iloc[i,5])
|
|
384 mr.relaxase_type = str(mResults.iloc[i,6])
|
|
385 mr.relaxase_type_accession = str(mResults.iloc[i,7])
|
|
386 mr.mpf_type = str(mResults.iloc[i,8])
|
|
387 mr.mpf_type_accession = str(mResults.iloc[i,9])
|
|
388 mr.orit_type = str(mResults.iloc[i,10])
|
|
389 mr.orit_accession = str(mResults.iloc[i,11])
|
|
390 mr.PredictedMobility = str(mResults.iloc[i,12])
|
|
391 mr.mash_nearest_neighbor = str(mResults.iloc[i,13])
|
|
392 mr.mash_neighbor_distance = float(mResults.iloc[i,14])
|
|
393 mr.mash_neighbor_cluster = int(mResults.iloc[i,15])
|
|
394 mr.row = "\t".join(str(x) for x in mResults.ix[i].tolist())
|
|
395 _mobsuite[mr.file_id] = mr
|
|
396 return _mobsuite
|
|
397
|
|
398 def ParseResFinderResult(pathToResFinderResults, plasmidContigs, likelyPlasmidContigs):
|
|
399 _rFinder = {}
|
|
400 resFinder = pandas.read_csv(pathToResFinderResults, delimiter='\t', header=0)
|
|
401 resFinder = resFinder.replace(numpy.nan, '', regex=True)
|
|
402
|
|
403 for i in range(len(resFinder.index)):
|
|
404 rf = starFinders()
|
|
405 rf.file = str(resFinder.iloc[i,0])
|
|
406 rf.sequence = str(resFinder.iloc[i,1])
|
|
407 rf.start = int(resFinder.iloc[i,2])
|
|
408 rf.end = int(resFinder.iloc[i,3])
|
|
409 rf.gene = str(resFinder.iloc[i,4])
|
|
410 rf.shortGene = rf.gene
|
|
411 rf.coverage = str(resFinder.iloc[i,5])
|
|
412 rf.coverage_map = str(resFinder.iloc[i,6])
|
|
413 rf.gaps = str(resFinder.iloc[i,7])
|
|
414 rf.pCoverage = float(resFinder.iloc[i,8])
|
|
415 rf.pIdentity = float(resFinder.iloc[i,9])
|
|
416 rf.database = str(resFinder.iloc[i,10])
|
|
417 rf.accession = str(resFinder.iloc[i,11])
|
|
418 rf.product = str(resFinder.iloc[i,12])
|
|
419 rf.row = "\t".join(str(x) for x in resFinder.ix[i].tolist())
|
|
420 if (rf.sequence[6:] in plasmidContigs):
|
|
421 rf.source = "plasmid"
|
|
422 elif (rf.sequence[6:] in likelyPlasmidContigs):
|
|
423 rf.source = "likely plasmid"
|
|
424 else:
|
|
425 rf.source = "likely chromosome"
|
|
426 _rFinder[rf.gene]=rf
|
|
427 return _rFinder
|
|
428
|
|
429 def ParseRGIResult(pathToRGIResults, plasmidContigs, likelyPlasmidContigs):
|
|
430 _rgiR = {}
|
|
431 RGI = pandas.read_csv(pathToRGIResults, delimiter='\t', header=0)
|
|
432 RGI = RGI.replace(numpy.nan, '', regex=True)
|
|
433
|
|
434 for i in range(len(RGI.index)):
|
|
435 r = RGIResult()
|
|
436 r.ORF_ID = str(RGI.iloc[i,0])
|
|
437 r.Contig = str(RGI.iloc[i,1])
|
|
438 r.Contig_Num = r.Contig[6:r.Contig.find("_")]
|
|
439 r.Start = int(RGI.iloc[i,2])
|
|
440 r.Stop = int(RGI.iloc[i,3])
|
|
441 r.Orientation = str(RGI.iloc[i,4])
|
|
442 r.Cut_Off = str(RGI.iloc[i,5])
|
|
443 r.Pass_Bitscore = int(RGI.iloc[i,6])
|
|
444 r.Best_Hit_Bitscore = float(RGI.iloc[i,7])
|
|
445 r.Best_Hit_ARO = str(RGI.iloc[i,8])
|
|
446 r.Best_Identities = float(RGI.iloc[i,9])
|
|
447 r.ARO = int(RGI.iloc[i,10])
|
|
448 r.Model_type = str(RGI.iloc[i,11])
|
|
449 r.SNPs_in_Best_Hit_ARO = str(RGI.iloc[i,12])
|
|
450 r.Other_SNPs = str(RGI.iloc[i,13])
|
|
451 r.Drug_Class = str(RGI.iloc[i,14])
|
|
452 r.Resistance_Mechanism = str(RGI.iloc[i,15])
|
|
453 r.AMR_Gene_Family = str(RGI.iloc[i,16])
|
|
454 r.Predicted_DNA = str(RGI.iloc[i,17])
|
|
455 r.Predicted_Protein = str(RGI.iloc[i,18])
|
|
456 r.CARD_Protein_Sequence = str(RGI.iloc[i,19])
|
|
457 r.Percentage_Length_of_Reference_Sequence = float(RGI.iloc[i,20])
|
|
458 r.ID = str(RGI.iloc[i,21])
|
|
459 r.Model_ID = int(RGI.iloc[i,22])
|
|
460 r.row = "\t".join(str(x) for x in RGI.ix[i].tolist())
|
|
461 if (r.Contig_Num in plasmidContigs):
|
|
462 r.source = "plasmid"
|
|
463 elif (r.Contig_Num in likelyPlasmidContigs):
|
|
464 r.source = "likely plasmid"
|
|
465 else:
|
|
466 r.source = "likely chromosome"
|
|
467 _rgiR[r.Model_ID]=r
|
|
468 return _rgiR
|
3
|
469
|
|
470 def ParsePlasmidFinderResult(pathToPlasmidFinderResult):
|
|
471 #pipelineTest/contigs/BC110-Kpn005.fa contig00019 45455 45758 IncFIC(FII)_1 8-308/499 ========/=..... 8/11 59.52 75.65 plasmidfinder AP001918 IncFIC(FII)_1__AP001918
|
|
472 #example resfinder:
|
|
473 #pipelineTest/contigs/BC110-Kpn005.fa contig00038 256 1053 OXA-181 1-798/798 =============== 0/0 100.00 100.00 bccdc AEP16366.1 OXA-48 family carbapenem-hydrolyzing class D beta-lactamase OXA-181
|
|
474
|
|
475 _pFinder = {} #***********************
|
|
476 plasmidFinder = pandas.read_csv(pathToPlasmidFinderResult, delimiter='\t', header=0)
|
|
477
|
|
478 for i in range(len(plasmidFinder.index)):
|
|
479 pf = starFinders()
|
|
480 pf.file = str(plasmidFinder.iloc[i,0])
|
|
481 pf.sequence = str(plasmidFinder.iloc[i,1])
|
|
482 pf.start = int(plasmidFinder.iloc[i,2])
|
|
483 pf.end = int(plasmidFinder.iloc[i,3])
|
|
484 pf.gene = str(plasmidFinder.iloc[i,4])
|
13
|
485 if (pf.gene.find("_") > -1):
|
|
486 pf.shortGene = pf.gene[:pf.gene.index("_")]
|
|
487 else:
|
|
488 pf.shortGene = pf.gene
|
3
|
489 pf.coverage = str(plasmidFinder.iloc[i,5])
|
|
490 pf.coverage_map = str(plasmidFinder.iloc[i,6])
|
|
491 pf.gaps = str(plasmidFinder.iloc[i,7])
|
|
492 pf.pCoverage = float(plasmidFinder.iloc[i,8])
|
|
493 pf.pIdentity = float(plasmidFinder.iloc[i,9])
|
|
494 pf.database = str(plasmidFinder.iloc[i,10])
|
|
495 pf.accession = str(plasmidFinder.iloc[i,11])
|
|
496 pf.product = str(plasmidFinder.iloc[i,12])
|
|
497 pf.source = "plasmid"
|
|
498 pf.row = "\t".join(str(x) for x in plasmidFinder.ix[i].tolist())
|
|
499 _pFinder[pf.gene]=pf
|
|
500 #row = "\t".join(str(x) for x in plasmidFinder.ix[i].tolist())
|
|
501 #plasmidFinderContigs.append(str(plasmidFinder.iloc[i,1]))
|
|
502 #origins.append(str(plasmidFinder.iloc[i,4][:plasmidFinder.iloc[i,4].index("_")]))
|
|
503 return _pFinder
|
18
|
504
|
|
505 def ParseMashResult(pathToMashScreen):
|
|
506 mashScreen = pandas.read_csv(pathToMashScreen, delimiter='\t', header=None)
|
|
507
|
|
508 _mashPlasmidHits = {} #***********************
|
|
509 #parse what the species are.
|
|
510 for i in (range(len(mashScreen.index))):
|
|
511 mr = MashResult()
|
|
512 mr.identity = float(mashScreen.ix[i, 0])
|
|
513 mr.sharedHashes = mashScreen.ix[i, 1]
|
|
514 mr.medianMultiplicity = int(mashScreen.ix[i, 2])
|
|
515 mr.pvalue = float(mashScreen.ix[i, 3])
|
|
516 mr.name = mashScreen.ix[i, 4] #accession
|
|
517 mr.row = "\t".join(str(x) for x in mashScreen.ix[i].tolist())
|
|
518 _mashPlasmidHits[mr.name] = mr
|
|
519 return _mashPlasmidHits
|
1
|
520 #endregion
|
|
521
|
|
522 def Main():
|
3
|
523 outputDir = "./"
|
1
|
524 notes = []
|
|
525 #init the output list
|
|
526 output = []
|
|
527 jsonOutput = []
|
|
528
|
3
|
529 print(str(datetime.datetime.now()) + "\n\nID: " + ID + "\nAssembly: " + ID)
|
|
530 output.append(str(datetime.datetime.now()) + "\n\nID: " + ID + "\nAssembly: " + ID)
|
1
|
531
|
|
532 #region parse the mlst results
|
|
533 print("step 3: parsing mlst, plasmid, and amr results")
|
|
534
|
|
535 print("identifying MLST")
|
3
|
536 mlstHit = ParseMLSTResult(mlst, str(mlstScheme))#***********************
|
1
|
537 ToJson(mlstHit, "mlst.json") #write it to a json output
|
|
538 mlstHit = list(mlstHit.values())[0]
|
|
539
|
|
540 #endregion
|
|
541
|
|
542 #region parse mobsuite, resfinder and rgi results
|
|
543 print("identifying plasmid contigs and amr genes")
|
|
544
|
|
545 plasmidContigs = []
|
|
546 likelyPlasmidContigs = []
|
|
547 origins = []
|
|
548
|
|
549 #parse mobsuite results
|
3
|
550 mSuite = ParseMobsuiteResult(mobfindercontig) #outputDir + "/predictions/" + ID + ".recon/contig_report.txt")#*************
|
1
|
551 ToJson(mSuite, "mobsuite.json") #*************
|
3
|
552 mSuitePlasmids = ParseMobsuitePlasmids(mobfinderaggregate)#outputDir + "/predictions/" + ID + ".recon/mobtyper_aggregate_report.txt")#*************
|
1
|
553 ToJson(mSuitePlasmids, "mobsuitePlasmids.json") #*************
|
|
554
|
|
555 for key in mSuite:
|
|
556 if mSuite[key].contig_num not in plasmidContigs and mSuite[key].contig_num not in likelyPlasmidContigs:
|
|
557 if not (mSuite[key].rep_type == ''):
|
|
558 plasmidContigs.append(mSuite[key].contig_num)
|
|
559 else:
|
|
560 likelyPlasmidContigs.append(mSuite[key].contig_num)
|
|
561 for key in mSuite:
|
|
562 if mSuite[key].rep_type not in origins:
|
|
563 origins.append(mSuite[key].rep_type)
|
|
564
|
|
565 #parse resfinder AMR results
|
3
|
566 pFinder = ParsePlasmidFinderResult(plasmidfinder)
|
|
567 ToJson(pFinder, "origins.json")
|
|
568
|
|
569 rFinder = ParseResFinderResult(abricate, plasmidContigs, likelyPlasmidContigs)#outputDir + "/predictions/" + ID + ".cp", plasmidContigs, likelyPlasmidContigs) #**********************
|
1
|
570 ToJson(rFinder, "resfinder.json") #*************
|
|
571
|
3
|
572 rgiAMR = ParseRGIResult(rgi, plasmidContigs, likelyPlasmidContigs) # outputDir + "/predictions/" + ID + ".rgi.txt", plasmidContigs, likelyPlasmidContigs)#***********************
|
1
|
573 ToJson(rgiAMR, "rgi.json") #*************
|
|
574
|
18
|
575 plasmidFamily = ParseMashResult(mash)
|
|
576 ToJson(plasmidFamily, "mash.json")
|
|
577
|
13
|
578 carbapenamases = []
|
|
579 resfinderCarbas = [] #list of rfinder objects for lindaout list
|
1
|
580 amrGenes = []
|
|
581 for keys in rFinder:
|
|
582 carbapenamases.append(rFinder[keys].shortGene + "(" + rFinder[keys].source + ")")
|
13
|
583 resfinderCarbas.append(rFinder[keys])
|
1
|
584 for keys in rgiAMR:
|
13
|
585 if (rgiAMR[keys].Drug_Class.find("carbapenem") > -1 and rgiAMR[keys].AMR_Gene_Family.find("beta-lactamase") > -1):
|
23
|
586 if ((rgiAMR[keys].Best_Hit_ARO+ "(" + rgiAMR[keys].source + ")") not in carbapenamases):
|
1
|
587 carbapenamases.append(rgiAMR[keys].Best_Hit_ARO+ "(" + rgiAMR[keys].source + ")")
|
|
588 else:
|
23
|
589 if ((rgiAMR[keys].Best_Hit_ARO+ "(" + rgiAMR[keys].source + ")") not in amrGenes):
|
1
|
590 amrGenes.append(rgiAMR[keys].Best_Hit_ARO+ "(" + rgiAMR[keys].source + ")")
|
|
591 #endregion
|
|
592
|
|
593 #region output parsed mlst information
|
|
594 print("formatting mlst outputs")
|
|
595 output.append("\n\n\n~~~~~~~MLST summary~~~~~~~")
|
|
596 output.append("MLST determined species: " + mlstHit.species)
|
|
597 output.append("\nMLST Details: ")
|
|
598 output.append(mlstHit.row)
|
|
599
|
|
600 output.append("\nMLST information: ")
|
|
601 if (mlstHit.species == expectedSpecies):
|
|
602 output.append("MLST determined species is the same as expected species")
|
|
603 #notes.append("MLST determined species is the same as expected species")
|
|
604 else:
|
|
605 output.append("!!!MLST determined species is NOT the same as expected species, contamination? mislabeling?")
|
|
606 notes.append("MLST: Not expected species. Possible contamination or mislabeling")
|
|
607
|
|
608 #endregion
|
|
609
|
|
610 #region output the parsed plasmid/amr results
|
|
611 output.append("\n\n\n~~~~~~~~Plasmids~~~~~~~~\n")
|
|
612
|
|
613 output.append("predicted plasmid origins: ")
|
|
614 output.append(";".join(origins))
|
|
615
|
|
616 output.append("\ndefinitely plasmid contigs")
|
|
617 output.append(";".join(plasmidContigs))
|
|
618
|
|
619 output.append("\nlikely plasmid contigs")
|
|
620 output.append(";".join(likelyPlasmidContigs))
|
|
621
|
|
622 output.append("\nmob-suite prediction details: ")
|
|
623 for key in mSuite:
|
|
624 output.append(mSuite[key].row)
|
|
625
|
|
626 output.append("\n\n\n~~~~~~~~AMR Genes~~~~~~~~\n")
|
|
627 output.append("predicted carbapenamase Genes: ")
|
|
628 output.append(",".join(carbapenamases))
|
|
629 output.append("other RGI AMR Genes: ")
|
|
630 for key in rgiAMR:
|
|
631 output.append(rgiAMR[key].Best_Hit_ARO + "(" + rgiAMR[key].source + ")")
|
|
632
|
|
633 output.append("\nDetails about the carbapenamase Genes: ")
|
|
634 for key in rFinder:
|
|
635 output.append(rFinder[key].row)
|
|
636 output.append("\nDetails about the RGI AMR Genes: ")
|
|
637 for key in rgiAMR:
|
|
638 output.append(rgiAMR[key].row)
|
|
639
|
|
640 #write summary to a file
|
|
641 summaryDir = outputDir + "/summary/" + ID
|
3
|
642 out = open("summary.txt", 'w')
|
1
|
643 for item in output:
|
|
644 out.write("%s\n" % item)
|
|
645
|
|
646
|
|
647 #TSV output
|
6
|
648 lindaOut = []
|
1
|
649 tsvOut = []
|
13
|
650 lindaOut.append("ID\tQUALITY\tExpected Species\tMLST Scheme\tSequence Type\tMLST_ALLELE_1\tMLST_ALLELE_2\tMLST_ALLELE_3\tMLST_ALLELE_4\tMLST_ALLELE_5\tMLST_ALLELE_6\tMLST_ALLELE_7\tSEROTYPE\tK_CAPSULE\tPLASMID_2_RFLP\tPLASMID_1_FAMILY\tPLASMID_1_BEST_MATCH\tPLASMID_1_COVERAGE\tPLASMID_1_SNVS_TO_BEST_MATCH\tPLASMID_1_CARBAPENEMASE\tPLASMID_1_INC_GROUP\tPLASMID_2_RFLP\tPLASMID_2_FAMILY\tPLASMID_2_BEST_MATCH\tPLASMID_2_COVERAGE\tPLASMID_2_SNVS_TO_BEST_MATCH\tPLASMID_2_CARBAPENEMASE\tPLASMID_2_INC_GROUP")
|
|
651 lindaTemp = ID + "\t" #id
|
|
652 lindaTemp += "\t" #quality
|
|
653 lindaTemp += expectedSpecies + "\t" #expected
|
|
654 lindaTemp += mlstHit.species + "\t" #mlstscheme
|
|
655 lindaTemp += str(mlstHit.seqType) + "\t" #seq type
|
|
656 lindaTemp += "\t".join(mlstHit.scheme.split(";")) + "\t"#mlst alleles x 7
|
|
657 lindaTemp += "\t\t" #sero and kcap
|
|
658
|
|
659 #resfinderCarbas
|
18
|
660 index = 0
|
13
|
661 for carbs in resfinderCarbas:
|
|
662 if (carbs.source == "plasmid"): #
|
18
|
663 lindaTemp += "\t"
|
|
664 plasmid = plasmidFamily[list(plasmidFamily.keys())[index]]
|
|
665 lindaTemp += plasmid.name + "\t"
|
|
666 lindaTemp += str(plasmid.identity) + "\t"
|
|
667 lindaTemp += plasmid.sharedHashes + "\t"
|
13
|
668 lindaTemp += carbs.shortGene + "\t" #found an carbapenase
|
|
669 contig = carbs.sequence[6:] #this is the contig number
|
|
670 for i in mSuite.keys():
|
|
671 if (str(mSuite[i].contig_num) == str(contig)): #found the right plasmid
|
18
|
672 clusterid = mSuite[i].cluster_id
|
|
673 rep_types = mSuitePlasmids["plasmid_" + str(clusterid) + ".fasta"].rep_types
|
|
674 lindaTemp += rep_types
|
13
|
675 lindaOut.append(lindaTemp)
|
|
676 out = open("summary.linda.tsv", 'w')
|
|
677 for item in lindaOut:
|
|
678 out.write("%s\n" % item)
|
6
|
679
|
24
|
680 tsvOut.append("new\tID\tExpected Species\tMLST Species\tSequence Type\tMLST Scheme\tCarbapenem Resistance Genes\tOther AMR Genes\tPlasmid Best Match\tPlasmid Identity\tPlasmid Shared Hash\tTotal Plasmids\tPlasmids ID\tNum_Contigs\tPlasmid Length\tPlasmid RepType\tPlasmid Mobility\tNearest Reference\tDefinitely Plasmid Contigs\tLikely Plasmid Contigs")
|
1
|
681 #start with ID
|
6
|
682 temp = "\t"
|
1
|
683 temp += (ID + "\t")
|
|
684 temp += expectedSpecies + "\t"
|
|
685
|
|
686 #move into MLST
|
|
687 temp += mlstHit.species + "\t"
|
|
688 temp += str(mlstHit.seqType) + "\t"
|
|
689 temp += mlstHit.scheme + "\t"
|
|
690
|
|
691 #now onto AMR genes
|
|
692 temp += ";".join(carbapenamases) + "\t"
|
|
693 temp += ";".join(amrGenes) + "\t"
|
|
694
|
|
695 #lastly plasmids
|
22
|
696 temp += str(plasmidFamily[list(plasmidFamily.keys())[0]].name) + "\t"
|
24
|
697 temp += str(plasmidFamily[list(plasmidFamily.keys())[0]].identity) + "\t"
|
|
698 temp += str(plasmidFamily[list(plasmidFamily.keys())[0]].sharedHashes) + "\t"
|
1
|
699 temp+= str(len(mSuitePlasmids)) + "\t"
|
|
700 plasmidID = ""
|
|
701 contigs = ""
|
|
702 lengths = ""
|
|
703 rep_type = ""
|
|
704 mobility = ""
|
|
705 neighbour = ""
|
|
706 for keys in mSuitePlasmids:
|
|
707 plasmidID += str(mSuitePlasmids[keys].mash_neighbor_cluster) + ";"
|
|
708 contigs += str(mSuitePlasmids[keys].num_contigs) + ";"
|
|
709 lengths += str(mSuitePlasmids[keys].total_length) + ";"
|
|
710 rep_type += str(mSuitePlasmids[keys].rep_types) + ";"
|
|
711 mobility += str(mSuitePlasmids[keys].PredictedMobility) + ";"
|
|
712 neighbour += str(mSuitePlasmids[keys].mash_nearest_neighbor) + ";"
|
|
713 temp += plasmidID + "\t" + contigs + "\t" + lengths + "\t" + rep_type + "\t" + mobility + "\t" + neighbour + "\t"
|
|
714 temp += ";".join(plasmidContigs) + "\t"
|
|
715 temp += ";".join(likelyPlasmidContigs)
|
|
716 tsvOut.append(temp)
|
|
717
|
|
718 summaryDir = outputDir + "/summary/" + ID
|
3
|
719 out = open("summary.tsv", 'w')
|
1
|
720 for item in tsvOut:
|
|
721 out.write("%s\n" % item)
|
|
722 #endregion
|
|
723
|
|
724
|
|
725 start = time.time()#time the analysis
|
|
726 print("Starting workflow...")
|
|
727 #analysis time
|
|
728 Main()
|
|
729
|
|
730 end = time.time()
|
5
|
731 print("Finished!\nThe analysis used: " + str(end-start) + " seconds") |