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
|
7 #$ -pe smp 1 # Parallel Environment (how many cores)
|
1
|
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
|
7
|
14 # >python cpo_galaxy_tree.py -t /path/to/tree.ph -d /path/to/distance/matrix -m /path/to/metadata
|
|
15
|
|
16 # <requirements>
|
|
17 # <requirement type="package" version="0.23.4">pandas</requirement>
|
|
18 # <requirement type="package" version="3.6">python</requirement>
|
|
19 # <requirement type="package" version="3.1.1">ete3</requirement>
|
|
20 # <requirement type="package" version="5.9.3">pyqt</requirement>
|
|
21 # </requirements>
|
1
|
22
|
|
23 import subprocess
|
7
|
24 import pandas #conda pandas
|
1
|
25 import optparse
|
|
26 import os
|
|
27 import datetime
|
|
28 import sys
|
|
29 import time
|
|
30 import urllib.request
|
|
31 import gzip
|
|
32 import collections
|
|
33 import json
|
7
|
34 import numpy #conda numpy
|
|
35 import ete3 as e #conda ete3 3.1.1**** >requires pyqt5
|
6
|
36
|
1
|
37
|
|
38 #parses some parameters
|
|
39 parser = optparse.OptionParser("Usage: %prog [options] arg1 arg2 ...")
|
|
40 parser.add_option("-t", "--tree", dest="treePath", type="string", default="./pipelineTest/tree.txt", help="identifier of the isolate")
|
|
41 parser.add_option("-d", "--distance", dest="distancePath", type="string", default="./pipelineTest/distance.tab", help="absolute file path forward read (R1)")
|
|
42 parser.add_option("-m", "--metadata", dest="metadataPath", type="string", default="./pipelineTest/metadata.tsv",help="absolute file path to reverse read (R2)")
|
|
43 (options,args) = parser.parse_args()
|
|
44 treePath = str(options.treePath).lstrip().rstrip()
|
|
45 distancePath = str(options.distancePath).lstrip().rstrip()
|
|
46 metadataPath = str(options.metadataPath).lstrip().rstrip()
|
|
47
|
|
48
|
|
49 #region result objects
|
|
50 #define some objects to store values from results
|
|
51 #//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).
|
|
52 class workflowResult(object):
|
|
53 def __init__(self):
|
|
54 self.new = False
|
|
55 self.ID = ""
|
|
56 self.ExpectedSpecies = ""
|
|
57 self.MLSTSpecies = ""
|
|
58 self.SequenceType = ""
|
|
59 self.MLSTScheme = ""
|
|
60 self.CarbapenemResistanceGenes =""
|
|
61 self.OtherAMRGenes=""
|
|
62 self.TotalPlasmids = 0
|
|
63 self.plasmids = []
|
|
64 self.DefinitelyPlasmidContigs =""
|
|
65 self.LikelyPlasmidContigs=""
|
|
66 self.row = ""
|
|
67 class plasmidObj(object):
|
|
68 def __init__(self):
|
|
69 self.PlasmidsID = 0
|
|
70 self.Num_Contigs = 0
|
|
71 self.PlasmidLength = 0
|
|
72 self.PlasmidRepType = ""
|
|
73 self.PlasmidMobility = ""
|
|
74 self.NearestReference = ""
|
|
75
|
|
76 #endregion
|
|
77
|
|
78 #region useful functions
|
7
|
79 def read(path): #read in a text file to a list
|
1
|
80 return [line.rstrip('\n') for line in open(path)]
|
7
|
81 def execute(command): #subprocess.popen call bash command
|
1
|
82 process = subprocess.Popen(command, shell=False, cwd=curDir, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
83
|
|
84 # Poll process for new output until finished
|
|
85 while True:
|
|
86 nextline = process.stdout.readline()
|
|
87 if nextline == '' and process.poll() is not None:
|
|
88 break
|
|
89 sys.stdout.write(nextline)
|
|
90 sys.stdout.flush()
|
|
91
|
|
92 output = process.communicate()[0]
|
|
93 exitCode = process.returncode
|
|
94
|
|
95 if (exitCode == 0):
|
|
96 return output
|
|
97 else:
|
|
98 raise subprocess.CalledProcessError(exitCode, command)
|
7
|
99 def httpGetFile(url, filepath=""): #download a file from the web
|
1
|
100 if (filepath == ""):
|
|
101 return urllib.request.urlretrieve(url)
|
|
102 else:
|
|
103 urllib.request.urlretrieve(url, filepath)
|
|
104 return True
|
7
|
105 def gunzip(inputpath="", outputpath=""): #gunzip
|
1
|
106 if (outputpath == ""):
|
|
107 with gzip.open(inputpath, 'rb') as f:
|
|
108 gzContent = f.read()
|
|
109 return gzContent
|
|
110 else:
|
|
111 with gzip.open(inputpath, 'rb') as f:
|
|
112 gzContent = f.read()
|
|
113 with open(outputpath, 'wb') as out:
|
|
114 out.write(gzContent)
|
|
115 return True
|
7
|
116 def addFace(name): #function to add a facet to a tree
|
6
|
117 #if its the reference branch, populate the faces with column headers
|
|
118 face = e.faces.TextFace(name,fsize=10,tight_text=True)
|
|
119 face.border.margin = 5
|
|
120 face.margin_right = 5
|
|
121 face.margin_left = 5
|
|
122 return face
|
1
|
123 #endregion
|
|
124
|
|
125 #region functions to parse result files
|
|
126 def ParseWorkflowResults(pathToResult):
|
|
127 _worflowResult = {}
|
6
|
128 r = pandas.read_csv(pathToResult, delimiter='\t', header=0)
|
1
|
129 r = r.replace(numpy.nan, '', regex=True)
|
|
130 for i in range(len(r.index)):
|
|
131 _results = workflowResult()
|
6
|
132 if(str(r.loc[r.index[i], 'new']).lower() == "new"):
|
1
|
133 _results.new = True
|
|
134 else:
|
|
135 _results.new = False
|
6
|
136 _results.ID = str(r.loc[r.index[i], 'ID'])
|
|
137 _results.ExpectedSpecies = str(r.loc[r.index[i], 'Expected Species'])
|
|
138 _results.MLSTSpecies = str(r.loc[r.index[i], 'MLST Species'])
|
|
139 _results.SequenceType = str(r.loc[r.index[i], 'Sequence Type'])
|
|
140 _results.MLSTScheme = (str(r.loc[r.index[i], 'MLST Scheme']))
|
|
141 _results.CarbapenemResistanceGenes = (str(r.loc[r.index[i], 'Carbapenem Resistance Genes']))
|
|
142 _results.OtherAMRGenes = (str(r.loc[r.index[i], 'Other AMR Genes']))
|
|
143 _results.TotalPlasmids = int(r.loc[r.index[i], 'Total Plasmids'])
|
1
|
144 for j in range(0,_results.TotalPlasmids):
|
|
145 _plasmid = plasmidObj()
|
6
|
146 _plasmid.PlasmidsID =(((str(r.loc[r.index[i], 'Plasmids ID'])).split(";"))[j])
|
|
147 _plasmid.Num_Contigs = (((str(r.loc[r.index[i], 'Num_Contigs'])).split(";"))[j])
|
|
148 _plasmid.PlasmidLength = (((str(r.loc[r.index[i], 'Plasmid Length'])).split(";"))[j])
|
|
149 _plasmid.PlasmidRepType = (((str(r.loc[r.index[i], 'Plasmid RepType'])).split(";"))[j])
|
|
150 _plasmid.PlasmidMobility = ((str(r.loc[r.index[i], 'Plasmid Mobility'])).split(";"))[j]
|
|
151 _plasmid.NearestReference = ((str(r.loc[r.index[i], 'Nearest Reference'])).split(";"))[j]
|
1
|
152 _results.plasmids.append(_plasmid)
|
6
|
153 _results.DefinitelyPlasmidContigs = (str(r.loc[r.index[i], 'Definitely Plasmid Contigs']))
|
|
154 _results.LikelyPlasmidContigs = (str(r.loc[r.index[i], 'Likely Plasmid Contigs']))
|
1
|
155 _results.row = "\t".join(str(x) for x in r.ix[i].tolist())
|
|
156 _worflowResult[_results.ID] = _results
|
|
157 return _worflowResult
|
|
158
|
|
159 #endregion
|
|
160
|
|
161 def Main():
|
|
162 metadata = ParseWorkflowResults(metadataPath)
|
|
163 distance = read(distancePath)
|
|
164 treeFile = "".join(read(treePath))
|
|
165
|
6
|
166 distanceDict = {} #store the distance matrix as rowname:list<string>
|
1
|
167 for i in range(len(distance)):
|
|
168 temp = distance[i].split("\t")
|
|
169 distanceDict[temp[0]] = temp[1:]
|
|
170 #region step5: tree construction
|
6
|
171
|
|
172 '''
|
|
173 #region create detailed tree
|
|
174
|
|
175 plasmidCount = 0
|
|
176 for n in t.traverse():
|
|
177 if (n.is_leaf() and not n.name == "Reference"):
|
|
178 mData = metadata[n.name.replace(".fa","")]
|
|
179 face = faces.TextFace(mData.MLSTSpecies,fsize=10,tight_text=True)
|
|
180 face.border.margin = 5
|
|
181 face.margin_left = 10
|
|
182 face.margin_right = 10
|
|
183 n.add_face(face, 0, "aligned")
|
|
184 face = faces.TextFace(mData.SequenceType,fsize=10,tight_text=True)
|
|
185 face.border.margin = 5
|
|
186 face.margin_right = 10
|
|
187 n.add_face(face, 1, "aligned")
|
|
188 face = faces.TextFace(mData.CarbapenemResistanceGenes,fsize=10,tight_text=True)
|
|
189 face.border.margin = 5
|
|
190 face.margin_right = 10
|
|
191 n.add_face(face, 2, "aligned")
|
|
192 index = 3
|
|
193 if (mData.TotalPlasmids > plasmidCount):
|
|
194 plasmidCount = mData.TotalPlasmids
|
|
195 for i in range(0, mData.TotalPlasmids):
|
|
196 face = faces.TextFace(mData.plasmids[i].PlasmidRepType,fsize=10,tight_text=True)
|
|
197 face.border.margin = 5
|
|
198 face.margin_right = 10
|
|
199 n.add_face(face, index, "aligned")
|
|
200 index+=1
|
|
201 face = faces.TextFace(mData.plasmids[i].PlasmidMobility,fsize=10,tight_text=True)
|
|
202 face.border.margin = 5
|
|
203 face.margin_right = 10
|
|
204 n.add_face(face, index, "aligned")
|
|
205 index+=1
|
|
206
|
|
207 face = faces.TextFace("Species",fsize=10,tight_text=True)
|
|
208 face.border.margin = 5
|
|
209 face.margin_right = 10
|
|
210 face.margin_left = 10
|
|
211 (t&"Reference").add_face(face, 0, "aligned")
|
|
212 face = faces.TextFace("Sequence Type",fsize=10,tight_text=True)
|
|
213 face.border.margin = 5
|
|
214 face.margin_right = 10
|
|
215 (t&"Reference").add_face(face, 1, "aligned")
|
|
216 face = faces.TextFace("Carbapenamases",fsize=10,tight_text=True)
|
|
217 face.border.margin = 5
|
|
218 face.margin_right = 10
|
|
219 (t&"Reference").add_face(face, 2, "aligned")
|
|
220 index = 3
|
|
221 for i in range(0, plasmidCount):
|
|
222 face = faces.TextFace("plasmid " + str(i) + " replicons",fsize=10,tight_text=True)
|
|
223 face.border.margin = 5
|
|
224 face.margin_right = 10
|
|
225 (t&"Reference").add_face(face, index, "aligned")
|
|
226 index+=1
|
|
227 face = faces.TextFace("plasmid " + str(i) + " mobility",fsize=10,tight_text=True)
|
|
228 face.border.margin = 5
|
|
229 face.margin_right = 10
|
|
230 (t&"Reference").add_face(face, index, "aligned")
|
|
231 index+=1
|
|
232
|
|
233 t.render("./pipelineTest/tree.png", w=5000,units="mm", tree_style=ts)
|
|
234
|
|
235 #endregion
|
|
236 '''
|
|
237 #region create box tree
|
|
238 #region step5: tree construction
|
|
239 treeFile = "".join(read(treePath))
|
|
240 t = e.Tree(treeFile)
|
1
|
241 t.set_outgroup(t&"Reference")
|
|
242
|
6
|
243 #set the tree style
|
|
244 ts = e.TreeStyle()
|
|
245 ts.show_leaf_name = False
|
1
|
246 ts.show_branch_length = True
|
|
247 ts.scale = 2000 #pixel per branch length unit
|
|
248 ts.branch_vertical_margin = 15 #pixel between branches
|
6
|
249 style2 = e.NodeStyle()
|
1
|
250 style2["fgcolor"] = "#000000"
|
|
251 style2["shape"] = "circle"
|
|
252 style2["vt_line_color"] = "#0000aa"
|
|
253 style2["hz_line_color"] = "#0000aa"
|
|
254 style2["vt_line_width"] = 2
|
|
255 style2["hz_line_width"] = 2
|
|
256 style2["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted
|
|
257 style2["hz_line_type"] = 0
|
|
258 for n in t.traverse():
|
|
259 n.set_style(style2)
|
|
260
|
6
|
261 #find the plasmid origins
|
1
|
262 plasmidIncs = {}
|
|
263 for key in metadata:
|
|
264 for plasmid in metadata[key].plasmids:
|
|
265 for inc in plasmid.PlasmidRepType.split(","):
|
|
266 if (inc.lower().find("inc") > -1):
|
|
267 if not (inc in plasmidIncs):
|
|
268 plasmidIncs[inc] = [metadata[key].ID]
|
|
269 else:
|
|
270 if metadata[key].ID not in plasmidIncs[inc]:
|
|
271 plasmidIncs[inc].append(metadata[key].ID)
|
|
272 #plasmidIncs = sorted(plasmidIncs)
|
6
|
273 for n in t.traverse(): #loop through the nodes of a tree
|
1
|
274 if (n.is_leaf() and n.name == "Reference"):
|
6
|
275 #if its the reference branch, populate the faces with column headers
|
|
276 index = 0
|
|
277 (t&"Reference").add_face(addFace("SampleID"), index, "aligned")
|
|
278 index = index + 1
|
|
279 (t&"Reference").add_face(addFace("New?"), index, "aligned")
|
|
280 index = index + 1
|
1
|
281 for i in range(len(plasmidIncs)): #this loop adds the columns (aka the incs) to the reference node
|
6
|
282 (t&"Reference").add_face(addFace(list(plasmidIncs.keys())[i]), i + index, "aligned")
|
|
283 index = index + len(plasmidIncs)
|
|
284 (t&"Reference").add_face(addFace("MLSTScheme"), index, "aligned")
|
|
285 index = index + 1
|
|
286 (t&"Reference").add_face(addFace("Sequence Type"), index, "aligned")
|
|
287 index = index + 1
|
|
288 (t&"Reference").add_face(addFace("Carbapenamases"), index, "aligned")
|
|
289 index = index + 1
|
|
290 for i in range(len(distanceDict[list(distanceDict.keys())[0]])): #this loop adds the distance matrix
|
|
291 (t&"Reference").add_face(addFace(distanceDict[list(distanceDict.keys())[0]][i]), index + i, "aligned")
|
|
292 index = index + len(distanceDict[list(distanceDict.keys())[0]])
|
|
293 elif (n.is_leaf() and not n.name == "Reference"):
|
|
294 #not reference branches, populate with metadata
|
|
295 index = 0
|
|
296 mData = metadata[n.name.replace(".fa","")]
|
|
297 n.add_face(addFace(mData.ID), index, "aligned")
|
|
298 index = index + 1
|
|
299 if (metadata[n.name.replace(".fa","")].new == True): #new column
|
|
300 face = e.RectFace(30,30,"green","green") # TextFace("Y",fsize=10,tight_text=True)
|
1
|
301 face.border.margin = 5
|
|
302 face.margin_right = 5
|
|
303 face.margin_left = 5
|
|
304 face.vt_align = 1
|
|
305 face.ht_align = 1
|
6
|
306 n.add_face(face, index, "aligned")
|
|
307 index = index + 1
|
1
|
308 for incs in plasmidIncs: #this loop adds presence/absence to the sample nodes
|
|
309 if (n.name.replace(".fa","") in plasmidIncs[incs]):
|
6
|
310 face = e.RectFace(30,30,"black","black") # TextFace("Y",fsize=10,tight_text=True)
|
1
|
311 face.border.margin = 5
|
|
312 face.margin_right = 5
|
|
313 face.margin_left = 5
|
|
314 face.vt_align = 1
|
|
315 face.ht_align = 1
|
6
|
316 n.add_face(face, list(plasmidIncs.keys()).index(incs) + index, "aligned")
|
|
317 index = index + len(plasmidIncs)
|
|
318 n.add_face(addFace(mData.MLSTSpecies), index, "aligned")
|
|
319 index = index + 1
|
|
320 n.add_face(addFace(mData.SequenceType), index, "aligned")
|
|
321 index = index + 1
|
|
322 n.add_face(addFace(mData.CarbapenemResistanceGenes), index, "aligned")
|
|
323 index = index + 1
|
1
|
324 for i in range(len(distanceDict[list(distanceDict.keys())[0]])): #this loop adds distance matrix
|
6
|
325 n.add_face(addFace(list(distanceDict[n.name])[i]), index + i, "aligned")
|
|
326
|
|
327 t.render("./tree.png", w=5000,units="mm", tree_style=ts) #save it as a png. or an phyloxml
|
1
|
328
|
|
329 #endregion
|
|
330 #endregion
|
|
331
|
|
332
|
|
333 start = time.time()#time the analysis
|
|
334
|
|
335 #analysis time
|
|
336 Main()
|
|
337
|
|
338 end = time.time()
|
|
339 print("Finished!\nThe analysis used: " + str(end-start) + " seconds") |