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>
|
7
|
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:]
|
6
|
170
|
|
171 #region create box tree
|
|
172 #region step5: tree construction
|
|
173 treeFile = "".join(read(treePath))
|
|
174 t = e.Tree(treeFile)
|
1
|
175 t.set_outgroup(t&"Reference")
|
|
176
|
6
|
177 #set the tree style
|
|
178 ts = e.TreeStyle()
|
|
179 ts.show_leaf_name = False
|
1
|
180 ts.show_branch_length = True
|
|
181 ts.scale = 2000 #pixel per branch length unit
|
|
182 ts.branch_vertical_margin = 15 #pixel between branches
|
6
|
183 style2 = e.NodeStyle()
|
1
|
184 style2["fgcolor"] = "#000000"
|
|
185 style2["shape"] = "circle"
|
|
186 style2["vt_line_color"] = "#0000aa"
|
|
187 style2["hz_line_color"] = "#0000aa"
|
|
188 style2["vt_line_width"] = 2
|
|
189 style2["hz_line_width"] = 2
|
|
190 style2["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted
|
|
191 style2["hz_line_type"] = 0
|
|
192 for n in t.traverse():
|
|
193 n.set_style(style2)
|
|
194
|
6
|
195 #find the plasmid origins
|
1
|
196 plasmidIncs = {}
|
|
197 for key in metadata:
|
|
198 for plasmid in metadata[key].plasmids:
|
|
199 for inc in plasmid.PlasmidRepType.split(","):
|
|
200 if (inc.lower().find("inc") > -1):
|
|
201 if not (inc in plasmidIncs):
|
|
202 plasmidIncs[inc] = [metadata[key].ID]
|
|
203 else:
|
|
204 if metadata[key].ID not in plasmidIncs[inc]:
|
|
205 plasmidIncs[inc].append(metadata[key].ID)
|
|
206 #plasmidIncs = sorted(plasmidIncs)
|
6
|
207 for n in t.traverse(): #loop through the nodes of a tree
|
1
|
208 if (n.is_leaf() and n.name == "Reference"):
|
6
|
209 #if its the reference branch, populate the faces with column headers
|
|
210 index = 0
|
|
211 (t&"Reference").add_face(addFace("SampleID"), index, "aligned")
|
|
212 index = index + 1
|
|
213 (t&"Reference").add_face(addFace("New?"), index, "aligned")
|
|
214 index = index + 1
|
1
|
215 for i in range(len(plasmidIncs)): #this loop adds the columns (aka the incs) to the reference node
|
6
|
216 (t&"Reference").add_face(addFace(list(plasmidIncs.keys())[i]), i + index, "aligned")
|
|
217 index = index + len(plasmidIncs)
|
|
218 (t&"Reference").add_face(addFace("MLSTScheme"), index, "aligned")
|
|
219 index = index + 1
|
|
220 (t&"Reference").add_face(addFace("Sequence Type"), index, "aligned")
|
|
221 index = index + 1
|
|
222 (t&"Reference").add_face(addFace("Carbapenamases"), index, "aligned")
|
|
223 index = index + 1
|
|
224 for i in range(len(distanceDict[list(distanceDict.keys())[0]])): #this loop adds the distance matrix
|
|
225 (t&"Reference").add_face(addFace(distanceDict[list(distanceDict.keys())[0]][i]), index + i, "aligned")
|
|
226 index = index + len(distanceDict[list(distanceDict.keys())[0]])
|
|
227 elif (n.is_leaf() and not n.name == "Reference"):
|
|
228 #not reference branches, populate with metadata
|
|
229 index = 0
|
|
230 mData = metadata[n.name.replace(".fa","")]
|
|
231 n.add_face(addFace(mData.ID), index, "aligned")
|
|
232 index = index + 1
|
|
233 if (metadata[n.name.replace(".fa","")].new == True): #new column
|
|
234 face = e.RectFace(30,30,"green","green") # TextFace("Y",fsize=10,tight_text=True)
|
1
|
235 face.border.margin = 5
|
|
236 face.margin_right = 5
|
|
237 face.margin_left = 5
|
|
238 face.vt_align = 1
|
|
239 face.ht_align = 1
|
6
|
240 n.add_face(face, index, "aligned")
|
|
241 index = index + 1
|
1
|
242 for incs in plasmidIncs: #this loop adds presence/absence to the sample nodes
|
|
243 if (n.name.replace(".fa","") in plasmidIncs[incs]):
|
6
|
244 face = e.RectFace(30,30,"black","black") # TextFace("Y",fsize=10,tight_text=True)
|
1
|
245 face.border.margin = 5
|
|
246 face.margin_right = 5
|
|
247 face.margin_left = 5
|
|
248 face.vt_align = 1
|
|
249 face.ht_align = 1
|
6
|
250 n.add_face(face, list(plasmidIncs.keys()).index(incs) + index, "aligned")
|
|
251 index = index + len(plasmidIncs)
|
|
252 n.add_face(addFace(mData.MLSTSpecies), index, "aligned")
|
|
253 index = index + 1
|
|
254 n.add_face(addFace(mData.SequenceType), index, "aligned")
|
|
255 index = index + 1
|
|
256 n.add_face(addFace(mData.CarbapenemResistanceGenes), index, "aligned")
|
|
257 index = index + 1
|
1
|
258 for i in range(len(distanceDict[list(distanceDict.keys())[0]])): #this loop adds distance matrix
|
6
|
259 n.add_face(addFace(list(distanceDict[n.name])[i]), index + i, "aligned")
|
|
260
|
8
|
261 t.render("./tree.pdf", w=5000,units="mm", tree_style=ts) #save it as a png. or an phyloxml
|
1
|
262
|
|
263 #endregion
|
|
264 #endregion
|
|
265
|
|
266
|
|
267 start = time.time()#time the analysis
|
|
268
|
|
269 #analysis time
|
|
270 Main()
|
|
271
|
|
272 end = time.time()
|
10
|
273 print("Finished!\nThe analysis used: " + str(end-start) + " seconds")
|