removed exception name from server error state (to not alarm the casual user).
[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 \r
226                 wsInfo.appendProgressText("Failed to submit the prediction.\n"\r
227                                           +"It is most likely that there is a problem with the server.\n"\r
228                                           +"Just close the window\n");\r
229                 System.err.println(\r
230                     "JPredWS Client: Failed to submit the prediction (Probably a server error - see below)\n" +\r
231                     e.toString() + "\n");\r
232 \r
233                 // e.printStackTrace(); TODO: JBPNote DEBUG\r
234             }\r
235         }\r
236 \r
237         private void addFloatAnnotations(Alignment al, int[] gapmap,\r
238             Vector values, String Symname, String Visname, float min,\r
239             float max, int winLength) {\r
240             Annotation[] annotations = new Annotation[al.getWidth()];\r
241 \r
242             for (int j = 0; j < values.size(); j++) {\r
243                 float value = Float.parseFloat(values.get(j).toString());\r
244                 annotations[gapmap[j]] = new Annotation("", value + "", ' ',\r
245                         value);\r
246             }\r
247 \r
248             al.addAnnotation(new AlignmentAnnotation(Symname, Visname,\r
249                     annotations, min, max, winLength));\r
250         }\r
251 \r
252         void parseResult() {\r
253             // OutputHeader = output.getText();\r
254             if (result.isFailed()) {\r
255                 OutputHeader += "Job failed.\n";\r
256             }\r
257 \r
258             if (result.getStatus() != null) {\r
259                 OutputHeader += ("\n" + result.getStatus());\r
260             }\r
261 \r
262             if (result.getPredfile() != null) {\r
263                 OutputHeader += ("\n" + result.getPredfile());\r
264 \r
265                 // 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
266             }\r
267 \r
268             if (result.getAligfile() != null) {\r
269                 OutputHeader += ("\n" + result.getAligfile());\r
270             }\r
271 \r
272             wsInfo.setProgressText(OutputHeader);\r
273 \r
274             try {\r
275                 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
276                 jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.getPredfile(),\r
277                         "Paste");\r
278                 SequenceI[] preds = prediction.getSeqsAsArray();\r
279                 Alignment al;\r
280                 int FirstSeq; // the position of the query sequence in Alignment al\r
281                 boolean noMsa = true; // set if no MSA has been returned by JPred\r
282 \r
283                 if ((this.msa != null) && (result.getAligfile() != null)) {\r
284                     // we ignore the returned alignment if we only predicted on a single sequence\r
285                     String format = jalview.io.IdentifyFile.Identify(result.getAligfile(),\r
286                             "Paste");\r
287 \r
288                     if (jalview.io.FormatAdapter.formats.contains(format)) {\r
289                         al = new Alignment(jalview.io.FormatAdapter.readFile(\r
290                                     result.getAligfile(), "Paste", format));\r
291                         noMsa = false;\r
292                         FirstSeq = 0;\r
293                     } else {\r
294                         throw (new Exception(\r
295                             "Unknown format 'format' for file : \n" +\r
296                             result.getAligfile()));\r
297                     }\r
298                 } else {\r
299                     al = new Alignment(preds);\r
300                     FirstSeq = prediction.getQuerySeqPosition();\r
301                 }\r
302 \r
303                 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
304                             al.getSequenceAt(FirstSeq), SequenceInfo)) {\r
305                     throw (new Exception(\r
306                         "Couldn't recover sequence properties for JNet Query sequence!"));\r
307                 }\r
308 \r
309                 AlignmentAnnotation annot;\r
310                 Annotation[] annotations = null;\r
311                 int i = 0;\r
312                 int width = preds[0].getSequence().length();\r
313 \r
314                 int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
315 \r
316                 if (gapmap.length != width) {\r
317                     throw (new Exception(\r
318                         "Jnet Client Error\nNumber of residues in supposed query sequence :\n" +\r
319                         al.getSequenceAt(FirstSeq).getName() + "\n" +\r
320                         al.getSequenceAt(FirstSeq).getSequence() +\r
321                         "\nDiffer from number of prediction sites in \n" +\r
322                         result.getPredfile() + "\n"));\r
323                 }\r
324 \r
325                 // JBPNote Should also rename the query sequence sometime...\r
326                 i = 0;\r
327 \r
328                 while (i < preds.length) {\r
329                     String id = preds[i].getName().toUpperCase();\r
330 \r
331                     if (id.startsWith("LUPAS") || id.startsWith("JNET") ||\r
332                             id.startsWith("JPRED")) {\r
333                         annotations = new Annotation[al.getWidth()];\r
334 \r
335                         if (id.equals("JNETPRED") || id.equals("JNETPSSM") ||\r
336                                 id.equals("JNETFREQ") || id.equals("JNETHMM") ||\r
337                                 id.equals("JNETALIGN") || id.equals("JPRED")) {\r
338                             for (int j = 0; j < width; j++) {\r
339                                 annotations[gapmap[j]] = new Annotation("", "",\r
340                                         preds[i].getCharAt(j), 0);\r
341                             }\r
342                         } else if (id.equals("JNETCONF")) {\r
343                             for (int j = 0; j < width; j++) {\r
344                                 float value = Float.parseFloat(preds[i].getCharAt(\r
345                                             j) + "");\r
346                                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
347                                             j) + "", "", preds[i].getCharAt(j),\r
348                                         value);\r
349                             }\r
350                         } else {\r
351                             for (int j = 0; j < width; j++) {\r
352                                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
353                                             j) + "", "", ' ', 0);\r
354                             }\r
355                         }\r
356 \r
357                         if (id.equals("JNETCONF")) {\r
358                             annot = new AlignmentAnnotation(preds[i].getName(),\r
359                                     "JNet Output", annotations, 0f, 10f, 1);\r
360                         }\r
361                         else {\r
362                             annot = new AlignmentAnnotation(preds[i].getName(),\r
363                                     "JNet Output", annotations);\r
364                         }\r
365 \r
366                         al.addAnnotation(annot);\r
367 \r
368                         if (noMsa) {\r
369                             al.deleteSequence(preds[i]);\r
370                         }\r
371                     }\r
372 \r
373                     i++;\r
374                 }\r
375 \r
376                 Hashtable scores = prediction.getScores();\r
377 \r
378                 /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
379                                       "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
380 \r
381                   addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
382                  "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
383 \r
384                   addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
385                                       "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
386                  */\r
387                 AlignFrame af = new AlignFrame(al);\r
388 \r
389                 Desktop.addInternalFrame(af, altitle,\r
390                     AlignFrame.NEW_WINDOW_WIDTH, AlignFrame.NEW_WINDOW_HEIGHT);\r
391             } catch (Exception ex) {\r
392                 ex.printStackTrace();\r
393             }\r
394         }\r
395     }\r
396 }\r