18
|
1 """
|
|
2 * Copyright 2018 University of Liverpool
|
|
3 * Author: John Heap, Computational Biology Facility, UoL
|
|
4 * Based on original scripts of Sara Silva Pereira, Institute of Infection and Global Health, UoL
|
|
5 *
|
|
6 * Licensed under the Apache License, Version 2.0 (the "License");
|
|
7 * you may not use this file except in compliance with the License.
|
|
8 * You may obtain a copy of the License at
|
|
9 *
|
|
10 * http://www.apache.org/licenses/LICENSE-2.0
|
|
11 *
|
|
12 * Unless required by applicable law or agreed to in writing, software
|
|
13 * distributed under the License is distributed on an "AS IS" BASIS,
|
|
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15 * See the License for the specific language governing permissions and
|
|
16 * limitations under the License.
|
|
17 *
|
|
18 """
|
8
|
19
|
18
|
20 import matplotlib as mpl
|
|
21 mpl.use('Agg')
|
8
|
22
|
18
|
23 import subprocess
|
|
24 import shutil
|
|
25 import re
|
|
26 import pandas as pd
|
|
27 import os
|
8
|
28
|
18
|
29 import sys
|
8
|
30
|
18
|
31 import matplotlib.pyplot as plt
|
|
32 from matplotlib.patches import Patch
|
|
33 import seaborn as sns
|
|
34
|
|
35 def assembleWithVelvet(name, kmers, inslen, covcut, fastq1name,fastq2name):
|
|
36 #argString = "velveth " + name + "_k65 65 -shortPaired -fastq " + name + "_R1.fastq " + name + "_R2.fastq"
|
|
37 argString = "velveth " + name + "_k"+ kmers+" "+ kmers + " -shortPaired -fastq " + fastq1name+" "+fastq2name
|
|
38 print(argString)
|
|
39 returncode = subprocess.call(argString, shell=True)
|
|
40 if returncode != 0:
|
|
41 return "Error in velveth"
|
|
42 argString = "velvetg " + name + "_k"+kmers+" -exp_cov auto -ins_length "+inslen+" -clean yes -ins_length_sd 50 -min_pair_count 20"
|
|
43 #argString = "velvetg " + name + "_k"+kmers+" -exp_cov auto -ins_length "+inslen+" -cov_cutoff "+covcut+" -clean yes -ins_length_sd 50 -min_pair_count 20"
|
|
44 #argString = "velvetg " + name + "_k65 -exp_cov auto -ins_length 400 -cov_cutoff 5 -clean yes -ins_length_sd 50 -min_pair_count 20"+quietString
|
|
45 print(argString)
|
|
46 returncode = subprocess.call(argString, shell = True)
|
|
47 if returncode != 0:
|
|
48 return "Error in velvetg"
|
|
49 shutil.copyfile(name + "_k"+kmers+"//contigs.fa",name + ".fa") # my $namechange = "mv ".$input."_k65/contigs.fa ".$input.".fa";
|
|
50 return "ok"
|
8
|
51
|
|
52
|
18
|
53 def blastContigs(test_name,database):
|
|
54 print(test_name)
|
|
55 print(database)
|
|
56 #db_path = os.path.dirname(os.path.realpath(__file__))+database
|
|
57 db_path = database
|
|
58 argString = "blastn -db "+db_path+" -query "+test_name+".fa -outfmt 10 -out "+test_name+"_blast.txt"
|
|
59 print(argString)
|
|
60 returncode = subprocess.call(argString, shell = True)
|
|
61 if returncode != 0:
|
|
62 return "Error in blastall"
|
|
63 blast_df = pd.read_csv(""+test_name+"_blast.txt")
|
|
64 #print (blast_df)
|
|
65 #if ($temp[2] >= 98 & & $temp[3] > 100 & & $temp[10] < 0.001){
|
|
66 #'qaccver saccver pident length mismatch gapopen qstart qend sstart send evalue bitscore'
|
|
67 blast_df.columns = ['qaccver', 'saccver', 'pident', 'length', 'mismatch', 'gapopen', 'qstart', 'qend', 'sstart', 'send', 'evalue','bitscore']
|
|
68 blastResult_df = blast_df[(blast_df['pident']>=98) & (blast_df['length'] > 100) & (blast_df['evalue']<0.001) ]
|
|
69 blastResult_df = blastResult_df[['qaccver', 'saccver', 'pident']] #query accession.version, subject accession.version, Percentage of identical matches
|
|
70
|
|
71 return blastResult_df
|
8
|
72
|
|
73
|
|
74
|
18
|
75 def getCogsPresent(blastResult_df,strain,cogOrBinList):
|
|
76 blastResult_df.sort_values('pident',axis = 0, ascending=False, inplace=True)
|
|
77 nodeList = blastResult_df['qaccver'].tolist()
|
|
78 cogList = blastResult_df['saccver'].tolist()
|
|
79 cogSet = set(cogList) #get unique values
|
|
80 cogList = sorted(cogSet) #sort them
|
8
|
81
|
18
|
82 #print (cogList)
|
|
83 #print (len(cogList))
|
8
|
84
|
18
|
85 thereList = []
|
|
86 dataList = []
|
|
87 #dir_path = os.path.dirname(os.path.realpath(__file__))
|
|
88 fname = cogOrBinList
|
|
89 cnt = 0
|
|
90 with open (fname) as f:
|
|
91 for line in f:
|
|
92 dataList.append(line.rstrip('\n\r '))
|
|
93 if line.rstrip('\n\r ') in cogList:
|
|
94 thereList.append('1')
|
|
95 cnt = cnt+1
|
|
96 else:
|
|
97 thereList.append('0')
|
8
|
98
|
18
|
99 #print (thereList)
|
|
100 #print (cnt)
|
|
101 data = {'Cog': dataList, strain: thereList}
|
|
102 presence_df = pd.DataFrame(data)
|
|
103 #print (presence_df)
|
|
104 return presence_df
|
8
|
105
|
18
|
106 def addToCurrentData(cog_df, name):
|
|
107 dir_path = os.path.dirname(os.path.realpath(__file__))
|
|
108 j_fname = dir_path + r"/data/vivax/TvDatabase.csv"
|
|
109 tv_df = pd.read_csv(j_fname)
|
8
|
110
|
18
|
111 cogList = cog_df[name].tolist()
|
|
112 #cogList.insert(0,'Test')
|
|
113 #print (len(tv_df))
|
|
114 #print(len(cogList))
|
8
|
115
|
18
|
116 #print(cogList)
|
|
117 tv_df.loc[:,name]=cogList
|
|
118 return tv_df
|
8
|
119
|
|
120
|
|
121
|
|
122
|
18
|
123 def createClusterMap(tv_df,name,html_path,pdfExport):
|
|
124 #Retrieve Data
|
|
125 dir_path = os.path.dirname(os.path.realpath(__file__))
|
|
126 j_fname = dir_path+r"/data/vivax/geoTv.csv"
|
|
127 geo_df = pd.read_csv(j_fname)
|
|
128 geo_df.loc[len(geo_df)] =[name,name,'k']
|
|
129 print(geo_df)
|
8
|
130
|
18
|
131 myStrains = tv_df.columns.values.tolist() #beware first entry is COG
|
|
132 myStrains = myStrains[1:]
|
|
133 print(myStrains)
|
|
134 myPal = []
|
|
135 for s in myStrains:
|
|
136 col = geo_df[(geo_df['Strain'] == s)]['colour'].tolist()
|
|
137 myPal.append(col[0])
|
|
138 print(myPal)
|
|
139 mycogmap = ['skyblue', 'orangered'] # blue absent,red present
|
|
140 tv_df.set_index('COG', inplace=True)
|
|
141 tv_df = tv_df[tv_df.columns].astype(float)
|
8
|
142
|
18
|
143 cg = sns.clustermap(tv_df, method='ward', col_colors=myPal, cmap=mycogmap, yticklabels = 1500, row_cluster=False, linewidths = 0)
|
|
144 #cg = sns.clustermap(tv_df, method='ward', row_cluster=False, linewidths = 0)
|
|
145 ax = cg.ax_heatmap
|
|
146 #xasix ticks and labels.
|
|
147 ax.xaxis.tick_top() #set ticks at top
|
|
148 newlabs = []
|
8
|
149
|
18
|
150 labs = ax.xaxis.get_ticklabels()
|
|
151 for i in range(0, len(labs)):
|
|
152 print(labs[i])
|
|
153 # labs[i].set_text(" "+labs[i].get_text()) #make enough room so label sits atop of col_color bars
|
|
154 newlabs.append(" " + labs[i].get_text())
|
|
155 ax.xaxis.set_ticklabels(newlabs)
|
8
|
156
|
18
|
157 #labs = ax.xaxis.get_ticklabels()
|
|
158 #for i in range(0, len(labs)):
|
|
159 # print(labs[i])
|
|
160 # labs[i].set_text(" "+labs[i].get_text()) #make enough room so label sits atop of col_color bars
|
|
161 # print(labs[i])
|
|
162 #ax.xaxis.set_ticklabels(labs)
|
|
163 plt.setp(cg.ax_heatmap.xaxis.get_ticklabels(), rotation=90) # get x labels printed vertically
|
8
|
164
|
18
|
165 cg.cax.set_visible(False)
|
|
166 ax = cg.ax_heatmap
|
|
167 ax.set_yticklabels("")
|
|
168 ax.set_ylabel("")
|
|
169 ax = cg.ax_heatmap
|
|
170 # ax.set_title("Variant antigen profiles of T. vivax genomes.\nDendrogram reflects the VSG repertoire relationships of each strain inferred by the presence and absence of non-universal T. vivax VSG orthologs.", va = "top", wrap = "True")
|
|
171 b = len(tv_df)
|
|
172 print(b)
|
|
173 title = "Figure Legend: The Variant Antigen Profiles of $\itTrypanosoma$ $\itvivax$ " \
|
|
174 "showing the \ncombination of present and absent diagnostic cluster of VSG orthologs " \
|
|
175 "across the sample cohort. \nDendrogram reflects the relationships amongst the VSG" \
|
|
176 " repertoires of each strain. " \
|
|
177 "Strains were isolated \nfrom multiple African countries as shown in the key.\nData was produced with the " \
|
|
178 "'Variant Antigen Profiler' (Silva Pereira et al., 2019)."
|
8
|
179
|
18
|
180 ax.text(-1.5, len(tv_df) + 8,
|
|
181 title,
|
|
182 ha="left", va="top", wrap="True")
|
|
183 col = cg.ax_col_dendrogram.get_position()
|
|
184 cg.ax_col_dendrogram.set_position([col.x0, col.y0*1.08, col.width, col.height*1.1])
|
8
|
185
|
18
|
186 countryList = pd.unique(geo_df['Location'])
|
|
187 colourList = pd.unique(geo_df['colour'])
|
|
188 legend_elements = [Patch(facecolor='orangered', label='COG Present'),
|
|
189 Patch(facecolor='skyblue', label='COG Absent')]
|
8
|
190
|
18
|
191 for i in range(0, len(colourList)):
|
|
192 print("country = %s, colour = %s" % (countryList[i], colourList[i]))
|
|
193 p = Patch(facecolor=str(colourList[i]), label=countryList[i])
|
|
194 legend_elements.append(p)
|
8
|
195
|
18
|
196 ax.legend(handles = legend_elements, bbox_to_anchor=(-0.3,1.2),loc = 'upper left')
|
8
|
197
|
|
198
|
|
199
|
|
200
|
|
201
|
|
202
|
|
203
|
18
|
204 #plt.setp(cg.ax_heatmap.yaxis.get_ticklabels(), rotation=0 ) # get y labels printed horizontally
|
|
205 # cg.dendrogram_col.linkage # linkage matrix for columns
|
|
206 # cg.dendrogram_row.linkage # linkage matrix for rows
|
|
207 # plt.savefig(r"results/" + name + "_heatmap.png")
|
|
208 #plt.savefig(htmlresource + "/heatmap.png")
|
|
209 #if pdf == 'PDF_Yes':
|
|
210 # plt.savefig(htmlresource + "/heatmap.pdf")
|
|
211 # shutil.copyfile("heatmap.pdf",heatmapfn) #
|
|
212 #plt.legend()
|
|
213 fname = html_path+"/"+name+"_clustermap.png"
|
|
214 cg.savefig(fname)
|
|
215 if pdfExport == 'PDF_Yes':
|
|
216 fname = html_path + "/" + name + "_clustermap.pdf"
|
|
217 cg.savefig(fname)
|
|
218 #plt.show()
|
8
|
219
|
18
|
220 def createHTML(name,htmlfn,htmlPath):
|
|
221 #assumes imgs are heatmap.png, dheatmap.png, vapPCA.png and already in htmlresource
|
|
222 htmlString = r"<html><title>T.vivax VAP</title><body><div style='text-align:center'><h2><i>Trypanosoma vivax</i> Variant Antigen Profile</h2><h3>"
|
|
223 htmlString += name
|
8
|
224
|
|
225
|
18
|
226 htmlString += r'<p> <h3>The Heat Map and Dendrogram</h3></p>'
|
|
227 imgString = r"<img src = '"+name+"_clustermap.png' alt='Cog Clustermap' style='max-width:100%'><br><br>"
|
|
228 htmlString += imgString
|
|
229 print(htmlString)
|
8
|
230
|
18
|
231 with open(htmlfn, "w") as htmlfile:
|
|
232 htmlfile.write(htmlString)
|
8
|
233
|
|
234
|
18
|
235 def vivax_assemble(args,dict):
|
|
236 #argdict = {'name': 2, 'pdfexport': 3, 'kmers': 4, 'inslen': 5, 'covcut': 6, 'forward': 7, 'reverse': 8, 'html_file': 9,'html_resource': 10}
|
|
237 #assembleWithVelvet("V2_Test", '65', '400', '5', "data/TviBrRp.1.clean", "data/TviBrRp.2.clean")
|
8
|
238
|
18
|
239 vivaxPath = os.path.dirname(os.path.realpath(__file__))+r"/data/vivax"
|
|
240 assembleWithVelvet(args[dict['name']], args[dict['kmers']], args[dict['inslen']], args[dict['covcut']],
|
|
241 args[dict['forward']], args[dict['reverse']])
|
|
242 blastResult_df = blastContigs(args[dict['name']], vivaxPath+r"/Database/COGs.fas")
|
|
243 orthPresence_df = getCogsPresent(blastResult_df, args[dict['name']], vivaxPath+r"/Database/COGlist.txt")
|
8
|
244
|
18
|
245 binBlastResult_df = blastContigs(args[dict['name']], vivaxPath+r"/Database/Bin_2.fas")
|
|
246 binPresence_df = getCogsPresent(binBlastResult_df, args[dict['name']], vivaxPath+r"/Database/binlist.txt")
|
|
247 cogPresence_df = orthPresence_df.append(binPresence_df, ignore_index=True)
|
8
|
248
|
18
|
249 fname = args[dict['html_resource']] +args[dict['name']]+"_cogspresent.csv"
|
|
250 cogPresence_df.to_csv(fname)
|
|
251 current_df = addToCurrentData(cogPresence_df,args[dict['name']]) # load in Tvdatabase and add cogPresence column to it.
|
|
252 createClusterMap(current_df, args[dict['name']],args[dict['html_resource']],args[dict['pdfexport']])
|
|
253 createHTML(args[dict['name']],args[dict['html_file']],args[dict['html_resource']])
|
8
|
254
|
18
|
255 def test_cluster(args,dict):
|
|
256 print ("name: %s",args[dict['name']])
|
|
257 cogPresence_df = pd.read_csv("test_cogspresent.csv")
|
|
258 print(cogPresence_df)
|
|
259 current_df = addToCurrentData(cogPresence_df,args[dict['name']]) # load in Tvdatabase and add cogPresence column to it.
|
|
260 createClusterMap(current_df, args[dict['name']], args[dict['html_resource']], args[dict['pdfexport']])
|
8
|
261
|
18
|
262 def vivax_contigs(args,dict):
|
|
263 # argdict = {'name': 2, 'pdfexport': 3, 'contigs': 4, 'html_file': 5, 'html_resource': 6}
|
8
|
264
|
18
|
265 #test_cluster(args,dict)
|
|
266 #return;
|
8
|
267
|
18
|
268 #subprocess.call('echo $PATH',shell = True)
|
|
269 #sys.exit(1)
|
|
270
|
|
271 vivaxPath = os.path.dirname(os.path.realpath(__file__))+r"/data/vivax"
|
|
272 shutil.copyfile(args[dict['contigs']], args[dict['name']]+".fa")
|
|
273 blastResult_df = blastContigs(args[dict['name']], vivaxPath+r"/Database/COGs.fas")
|
|
274 orthPresence_df = getCogsPresent(blastResult_df, args[dict['name']], vivaxPath+r"/Database/COGlist.txt")
|
8
|
275
|
18
|
276 binBlastResult_df = blastContigs(args[dict['name']], vivaxPath+r"/Database/Bin_2.fas")
|
|
277 binPresence_df = getCogsPresent(binBlastResult_df, args[dict['name']], vivaxPath+r"/Database/binlist.txt")
|
|
278 cogPresence_df = orthPresence_df.append(binPresence_df, ignore_index=True)
|
8
|
279
|
18
|
280 fname = args[dict['html_resource']]+r"/"+ args[dict['name']]+"_cogspresent.csv"
|
|
281 cogPresence_df.to_csv(fname)
|
|
282 current_df = addToCurrentData(cogPresence_df,args[dict['name']]) # load in Tvdatabase and add cogPresence column to it.
|
|
283 createClusterMap(current_df, args[dict['name']], args[dict['html_resource']], args[dict['pdfexport']])
|
|
284 createHTML(args[dict['name']],args[dict['html_file']],args[dict['html_resource']])
|
8
|
285
|
|
286
|
18
|
287 if __name__ == "__main__":
|
|
288 sys.exit()
|
8
|
289
|
|
290
|
|
291
|
|
292
|