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