Formatted source
[jalview.git] / src / jalview / ws / JPredClient.java
1 /*\r
2 * Jalview - A Sequence Alignment Editor and Viewer\r
3 * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle\r
4 *\r
5 * This program is free software; you can redistribute it and/or\r
6 * modify it under the terms of the GNU General Public License\r
7 * as published by the Free Software Foundation; either version 2\r
8 * of the License, or (at your option) any later version.\r
9 *\r
10 * This program is distributed in the hope that it will be useful,\r
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
13 * GNU General Public License for more details.\r
14 *\r
15 * You should have received a copy of the GNU General Public License\r
16 * along with this program; if not, write to the Free Software\r
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\r
18 */\r
19 package jalview.ws;\r
20 \r
21 import ext.vamsas.*;\r
22 \r
23 import jalview.analysis.AlignSeq;\r
24 \r
25 import jalview.datamodel.*;\r
26 \r
27 import jalview.gui.*;\r
28 \r
29 import org.apache.axis.client.*;\r
30 \r
31 import java.awt.*;\r
32 \r
33 import java.util.*;\r
34 \r
35 import javax.swing.*;\r
36 \r
37 import javax.xml.namespace.QName;\r
38 \r
39 \r
40 public class JPredClient extends WSClient {\r
41     ext.vamsas.JPredWS server;\r
42     String altitle = "";\r
43     java.util.Hashtable SequenceInfo = null;\r
44 \r
45     public JPredClient(String title, SequenceI[] msf) {\r
46         wsInfo = setWebService();\r
47 \r
48         SequenceI seq = msf[0];\r
49         altitle = "JNet prediction on " + seq.getName() +\r
50             " using alignment from " + title;\r
51 \r
52         wsInfo.setProgressText("Job details for MSA based prediction (" +\r
53             title + ") on sequence :\n>" + seq.getName() + "\n" +\r
54             AlignSeq.extractGaps("-. ", seq.getSequence()) + "\n");\r
55 \r
56         SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
57 \r
58         if (!locateWebService()) {\r
59             return;\r
60         }\r
61 \r
62         JPredThread jthread = new JPredThread(msf);\r
63         jthread.start();\r
64     }\r
65 \r
66     public JPredClient(String title, SequenceI seq) {\r
67         wsInfo = setWebService();\r
68         wsInfo.setProgressText("Job details for prediction on sequence :\n>" +\r
69             seq.getName() + "\n" +\r
70             AlignSeq.extractGaps("-. ", seq.getSequence()) + "\n");\r
71         altitle = "JNet prediction for sequence " + seq.getName() + " from " +\r
72             title;\r
73 \r
74         SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
75 \r
76         if (!locateWebService()) {\r
77             return;\r
78         }\r
79 \r
80         JPredThread jthread = new JPredThread(seq);\r
81         jthread.start();\r
82     }\r
83 \r
84     private WebserviceInfo setWebService() {\r
85         WebServiceName = "JNetWS";\r
86         WebServiceJobTitle = "JNet secondary structure prediction";\r
87         WebServiceReference = "\"Cuff J. A and Barton G.J (1999) Application of enhanced " +\r
88             "multiple sequence alignment profiles to improve protein secondary structure prediction, " +\r
89             "Proteins 40:502-511\".";\r
90         WsURL = "http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred";\r
91 \r
92         WebserviceInfo wsInfo = new WebserviceInfo(WebServiceJobTitle,\r
93                 WebServiceReference);\r
94 \r
95         return wsInfo;\r
96     }\r
97 \r
98     private boolean locateWebService() {\r
99         JPredWSServiceLocator loc = new JPredWSServiceLocator(); // Default\r
100 \r
101         try {\r
102             this.server = loc.getjpred(new java.net.URL(WsURL)); // JBPNote will be set from properties\r
103             ((JpredSoapBindingStub) this.server).setTimeout(60000); // one minute stub\r
104         } catch (Exception ex) {\r
105             JOptionPane.showMessageDialog(Desktop.desktop,\r
106                 "The Secondary Structure Prediction Service named " +\r
107                 WebServiceName + " at " + WsURL + " couldn't be located.",\r
108                 "Internal Jalview Error", JOptionPane.WARNING_MESSAGE);\r
109             wsInfo.setProgressText("Serious! " + WebServiceName +\r
110                 " Service location failed\nfor URL :" + WsURL + "\n" +\r
111                 ex.getMessage());\r
112             wsInfo.setStatus(wsInfo.STATE_STOPPED_SERVERERROR);\r
113 \r
114             return false;\r
115         }\r
116 \r
117         return true;\r
118     }\r
119 \r
120     class JPredThread extends Thread {\r
121         String OutputHeader;\r
122         ext.vamsas.JpredResult result;\r
123         ext.vamsas.Sequence sequence;\r
124         ext.vamsas.Msfalignment msa;\r
125         String jobId;\r
126         boolean jobComplete = false;\r
127         int allowedServerExceptions = 3; // thread dies if too many exceptions.\r
128 \r
129         JPredThread(SequenceI seq) {\r
130             OutputHeader = wsInfo.getProgressText();\r
131             this.sequence = new ext.vamsas.Sequence();\r
132             this.sequence.setId(seq.getName());\r
133             this.sequence.setSeq(AlignSeq.extractGaps("-. ", seq.getSequence()));\r
134         }\r
135 \r
136         JPredThread(SequenceI[] msf) {\r
137             OutputHeader = wsInfo.getProgressText();\r
138             this.sequence = new ext.vamsas.Sequence();\r
139             this.sequence.setId(msf[0].getName());\r
140             this.sequence.setSeq(AlignSeq.extractGaps("-. ",\r
141                     msf[0].getSequence()));\r
142 \r
143             jalview.io.PileUpfile mwrite = new jalview.io.PileUpfile();\r
144             this.msa = new ext.vamsas.Msfalignment();\r
145             msa.setMsf(mwrite.print(msf));\r
146         }\r
147 \r
148         public void run() {\r
149             StartJob();\r
150 \r
151             while (!jobComplete && (allowedServerExceptions > 0)) {\r
152                 try {\r
153                     if ((result = server.getresult(jobId)) == null) {\r
154                         throw (new Exception(\r
155                             "Timed out when communicating with server\nTry again later.\n"));\r
156                     }\r
157 \r
158                     if (result.isRunning()) {\r
159                         wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);\r
160                     } else if (result.isQueued()) {\r
161                         wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);\r
162                     }\r
163 \r
164                     if (result.isFinished()) {\r
165                         parseResult();\r
166                         jobComplete = true;\r
167                         jobsRunning--;\r
168                     } else {\r
169                         wsInfo.setProgressText(OutputHeader + "\n" +\r
170                             result.getStatus());\r
171 \r
172                         if (!(result.isJobFailed() || result.isServerError())) {\r
173                             try {\r
174                                 Thread.sleep(5000);\r
175                             } catch (InterruptedException ex1) {\r
176                             }\r
177 \r
178                             //  System.out.println("I'm alive "+seqid+" "+jobid);\r
179                         } else {\r
180                             wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
181                         }\r
182                     }\r
183                 } catch (Exception ex) {\r
184                     allowedServerExceptions--;\r
185                     wsInfo.appendProgressText("\nJPredWS Server exception!\n" +\r
186                         ex.getMessage());\r
187 \r
188                     try {\r
189                         if (allowedServerExceptions > 0) {\r
190                             Thread.sleep(5000);\r
191                         }\r
192                     } catch (InterruptedException ex1) {\r
193                     }\r
194                 }\r
195             }\r
196 \r
197             if (!(result.isJobFailed() || result.isServerError())) {\r
198                 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);\r
199             } else {\r
200                 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
201             }\r
202         }\r
203 \r
204         void StartJob() {\r
205             try {\r
206                 if (msa != null) {\r
207                     jobId = server.predictOnMsa(msa);\r
208                 } else {\r
209                     jobId = server.predict(sequence);\r
210                 }\r
211 \r
212                 if (jobId != null) {\r
213                     if (jobId.startsWith("Broken")) {\r
214                         throw new Exception("Submission " + jobId);\r
215                     } else {\r
216                         System.out.println(WsURL + " Job Id '" + jobId + "'");\r
217                     }\r
218                 } else {\r
219                     throw new Exception("Server timed out - try again later\n");\r
220                 }\r
221             } catch (Exception e) {\r
222                 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);\r
223                 allowedServerExceptions = 0;\r
224                 jobComplete = false;\r
225                 wsInfo.appendProgressText("Failed to submit the prediction: " +\r
226                     e.toString() + "\nJust close the window\n");\r
227                 System.err.println(\r
228                     "JPredWS Client: Failed to submit the prediction\n" +\r
229                     e.toString() + "\n");\r
230 \r
231                 // e.printStackTrace(); TODO: JBPNote DEBUG\r
232             }\r
233         }\r
234 \r
235         private void addFloatAnnotations(Alignment al, int[] gapmap,\r
236             Vector values, String Symname, String Visname, float min,\r
237             float max, int winLength) {\r
238             Annotation[] annotations = new Annotation[al.getWidth()];\r
239 \r
240             for (int j = 0; j < values.size(); j++) {\r
241                 float value = Float.parseFloat(values.get(j).toString());\r
242                 annotations[gapmap[j]] = new Annotation("", value + "", ' ',\r
243                         value);\r
244             }\r
245 \r
246             al.addAnnotation(new AlignmentAnnotation(Symname, Visname,\r
247                     annotations, min, max, winLength));\r
248         }\r
249 \r
250         void parseResult() {\r
251             // OutputHeader = output.getText();\r
252             if (result.isFailed()) {\r
253                 OutputHeader += "Job failed.\n";\r
254             }\r
255 \r
256             if (result.getStatus() != null) {\r
257                 OutputHeader += ("\n" + result.getStatus());\r
258             }\r
259 \r
260             if (result.getPredfile() != null) {\r
261                 OutputHeader += ("\n" + result.getPredfile());\r
262 \r
263                 // JBPNote The returned files from a webservice could be hidden behind icons in the monitor window that, when clicked, pop up their corresponding data\r
264             }\r
265 \r
266             if (result.getAligfile() != null) {\r
267                 OutputHeader += ("\n" + result.getAligfile());\r
268             }\r
269 \r
270             wsInfo.setProgressText(OutputHeader);\r
271 \r
272             try {\r
273                 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
274                 jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.getPredfile(),\r
275                         "Paste");\r
276                 SequenceI[] preds = prediction.getSeqsAsArray();\r
277                 Alignment al;\r
278                 int FirstSeq; // the position of the query sequence in Alignment al\r
279                 boolean noMsa = true; // set if no MSA has been returned by JPred\r
280 \r
281                 if ((this.msa != null) && (result.getAligfile() != null)) {\r
282                     // we ignore the returned alignment if we only predicted on a single sequence\r
283                     String format = jalview.io.IdentifyFile.Identify(result.getAligfile(),\r
284                             "Paste");\r
285 \r
286                     if (jalview.io.FormatAdapter.formats.contains(format)) {\r
287                         al = new Alignment(jalview.io.FormatAdapter.readFile(\r
288                                     result.getAligfile(), "Paste", format));\r
289                         noMsa = false;\r
290                         FirstSeq = 0;\r
291                     } else {\r
292                         throw (new Exception(\r
293                             "Unknown format 'format' for file : \n" +\r
294                             result.getAligfile()));\r
295                     }\r
296                 } else {\r
297                     al = new Alignment(preds);\r
298                     FirstSeq = prediction.getQuerySeqPosition();\r
299                 }\r
300 \r
301                 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
302                             al.getSequenceAt(FirstSeq), SequenceInfo)) {\r
303                     throw (new Exception(\r
304                         "Couldn't recover sequence properties for JNet Query sequence!"));\r
305                 }\r
306 \r
307                 AlignmentAnnotation annot;\r
308                 Annotation[] annotations = null;\r
309                 int i = 0;\r
310                 int width = preds[0].getSequence().length();\r
311 \r
312                 int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
313 \r
314                 if (gapmap.length != width) {\r
315                     throw (new Exception(\r
316                         "Jnet Client Error\nNumber of residues in supposed query sequence :\n" +\r
317                         al.getSequenceAt(FirstSeq).getName() + "\n" +\r
318                         al.getSequenceAt(FirstSeq).getSequence() +\r
319                         "\nDiffer from number of prediction sites in \n" +\r
320                         result.getPredfile() + "\n"));\r
321                 }\r
322 \r
323                 // JBPNote Should also rename the query sequence sometime...\r
324                 i = 0;\r
325 \r
326                 while (i < preds.length) {\r
327                     String id = preds[i].getName().toUpperCase();\r
328 \r
329                     if (id.startsWith("LUPAS") || id.startsWith("JNET") ||\r
330                             id.startsWith("JPRED")) {\r
331                         annotations = new Annotation[al.getWidth()];\r
332 \r
333                         if (id.equals("JNETPRED") || id.equals("JNETPSSM") ||\r
334                                 id.equals("JNETFREQ") || id.equals("JNETHMM") ||\r
335                                 id.equals("JNETALIGN") || id.equals("JPRED")) {\r
336                             for (int j = 0; j < width; j++) {\r
337                                 annotations[gapmap[j]] = new Annotation("", "",\r
338                                         preds[i].getCharAt(j), 0);\r
339                             }\r
340                         } else if (id.equals("JNETCONF")) {\r
341                             for (int j = 0; j < width; j++) {\r
342                                 float value = Float.parseFloat(preds[i].getCharAt(\r
343                                             j) + "");\r
344                                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
345                                             j) + "", "", preds[i].getCharAt(j),\r
346                                         value);\r
347                             }\r
348                         } else {\r
349                             for (int j = 0; j < width; j++) {\r
350                                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
351                                             j) + "", "", ' ', 0);\r
352                             }\r
353                         }\r
354 \r
355                         if (id.equals("JNETCONF")) {\r
356                             annot = new AlignmentAnnotation(preds[i].getName(),\r
357                                     "JNet Output", annotations, 0f, 10f, 1);\r
358                         }\r
359                         else {\r
360                             annot = new AlignmentAnnotation(preds[i].getName(),\r
361                                     "JNet Output", annotations);\r
362                         }\r
363 \r
364                         al.addAnnotation(annot);\r
365 \r
366                         if (noMsa) {\r
367                             al.deleteSequence(preds[i]);\r
368                         }\r
369                     }\r
370 \r
371                     i++;\r
372                 }\r
373 \r
374                 Hashtable scores = prediction.getScores();\r
375 \r
376                 /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
377                                       "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
378 \r
379                   addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
380                  "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
381 \r
382                   addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
383                                       "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
384                  */\r
385                 AlignFrame af = new AlignFrame(al);\r
386 \r
387                 Desktop.addInternalFrame(af, altitle,\r
388                     AlignFrame.NEW_WINDOW_WIDTH, AlignFrame.NEW_WINDOW_HEIGHT);\r
389             } catch (Exception ex) {\r
390                 ex.printStackTrace();\r
391             }\r
392         }\r
393     }\r
394 }\r