Client threads for discovered web services.
[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 java.util.*;\r
22 \r
23 import javax.swing.*;\r
24 \r
25 import ext.vamsas.*;\r
26 import jalview.analysis.*;\r
27 import jalview.datamodel.*;\r
28 import jalview.gui.*;\r
29 \r
30 public class JPredClient\r
31     extends WSClient\r
32 {\r
33   ext.vamsas.JPredWS server;\r
34   String altitle = "";\r
35   java.util.Hashtable SequenceInfo = null;\r
36   public JPredClient(ext.vamsas.ServiceHandle sh, String title, SequenceI seq) {\r
37     wsInfo = setWebService(sh);\r
38     startJPredClient(title, seq);\r
39   }\r
40   public JPredClient(ext.vamsas.ServiceHandle sh, String title, SequenceI[] msa) {\r
41     wsInfo = setWebService(sh);\r
42     startJPredClient(title, msa);\r
43   }\r
44 \r
45   public JPredClient(String title, SequenceI[] msf) {\r
46     startJPredClient(title, msf);\r
47   }\r
48 \r
49   public JPredClient(String title, SequenceI seq) {\r
50     startJPredClient(title, seq);\r
51   }\r
52 \r
53   private void startJPredClient(String title, SequenceI[] msf)\r
54   {\r
55     if (wsInfo==null)\r
56       wsInfo = setWebService();\r
57 \r
58     SequenceI seq = msf[0];\r
59     altitle = "JNet prediction on " + seq.getName() +\r
60         " using alignment from " + title;\r
61 \r
62     wsInfo.setProgressText("Job details for MSA based prediction (" +\r
63                            title + ") on sequence :\n>" + seq.getName() + "\n" +\r
64                            AlignSeq.extractGaps("-. ", seq.getSequence()) +\r
65                            "\n");\r
66 \r
67     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
68 \r
69     if (!locateWebService())\r
70     {\r
71       return;\r
72     }\r
73 \r
74     JPredThread jthread = new JPredThread(msf);\r
75     jthread.start();\r
76   }\r
77 \r
78   public void startJPredClient(String title, SequenceI seq)\r
79   {\r
80     if (wsInfo==null)\r
81       wsInfo = setWebService();\r
82     wsInfo.setProgressText("Job details for prediction on sequence :\n>" +\r
83                            seq.getName() + "\n" +\r
84                            AlignSeq.extractGaps("-. ", seq.getSequence()) +\r
85                            "\n");\r
86     altitle = "JNet prediction for sequence " + seq.getName() + " from " +\r
87         title;\r
88 \r
89     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
90 \r
91     if (!locateWebService())\r
92     {\r
93       return;\r
94     }\r
95 \r
96     JPredThread jthread = new JPredThread(seq);\r
97     jthread.start();\r
98   }\r
99 \r
100   private WebserviceInfo setWebService()\r
101   {\r
102     WebServiceName = "JNetWS";\r
103     WebServiceJobTitle = "JNet secondary structure prediction";\r
104     WebServiceReference =\r
105         "\"Cuff J. A and Barton G.J (1999) Application of enhanced " +\r
106         "multiple sequence alignment profiles to improve protein secondary structure prediction, " +\r
107         "Proteins 40:502-511\".";\r
108     WsURL = "http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred";\r
109 \r
110     WebserviceInfo wsInfo = new WebserviceInfo(WebServiceJobTitle,\r
111                                                WebServiceReference);\r
112 \r
113     return wsInfo;\r
114   }\r
115 \r
116   private boolean locateWebService()\r
117   {\r
118     JPredWSServiceLocator loc = new JPredWSServiceLocator(); // Default\r
119 \r
120     try\r
121     {\r
122       this.server = loc.getjpred(new java.net.URL(WsURL)); // JBPNote will be set from properties\r
123       ( (JpredSoapBindingStub)this.server).setTimeout(60000); // one minute stub\r
124     }\r
125     catch (Exception ex)\r
126     {\r
127       JOptionPane.showMessageDialog(Desktop.desktop,\r
128                                     "The Secondary Structure Prediction Service named " +\r
129                                     WebServiceName + " at " + WsURL +\r
130                                     " couldn't be located.",\r
131                                     "Internal Jalview Error",\r
132                                     JOptionPane.WARNING_MESSAGE);\r
133       wsInfo.setProgressText("Serious! " + WebServiceName +\r
134                              " Service location failed\nfor URL :" + WsURL +\r
135                              "\n" +\r
136                              ex.getMessage());\r
137       wsInfo.setStatus(wsInfo.STATE_STOPPED_SERVERERROR);\r
138 \r
139       return false;\r
140     }\r
141 \r
142     return true;\r
143   }\r
144 \r
145   class JPredThread\r
146       extends Thread\r
147   {\r
148     String OutputHeader;\r
149     ext.vamsas.JpredResult result;\r
150     ext.vamsas.Sequence sequence;\r
151     ext.vamsas.Msfalignment msa;\r
152     String jobId;\r
153     boolean jobComplete = false;\r
154     int allowedServerExceptions = 3; // thread dies if too many exceptions.\r
155 \r
156     JPredThread(SequenceI seq)\r
157     {\r
158       OutputHeader = wsInfo.getProgressText();\r
159       this.sequence = new ext.vamsas.Sequence();\r
160       this.sequence.setId(seq.getName());\r
161       this.sequence.setSeq(AlignSeq.extractGaps("-. ", seq.getSequence()));\r
162     }\r
163 \r
164     JPredThread(SequenceI[] msf)\r
165     {\r
166       OutputHeader = wsInfo.getProgressText();\r
167       this.sequence = new ext.vamsas.Sequence();\r
168       this.sequence.setId(msf[0].getName());\r
169       this.sequence.setSeq(AlignSeq.extractGaps("-. ",\r
170                                                 msf[0].getSequence()));\r
171 \r
172       jalview.io.PileUpfile mwrite = new jalview.io.PileUpfile();\r
173       this.msa = new ext.vamsas.Msfalignment();\r
174       msa.setMsf(mwrite.print(msf));\r
175     }\r
176 \r
177     public void run()\r
178     {\r
179       StartJob();\r
180 \r
181       while (!jobComplete && (allowedServerExceptions > 0))\r
182       {\r
183         try\r
184         {\r
185           if ( (result = server.getresult(jobId)) == null)\r
186           {\r
187             throw (new Exception(\r
188                 "Timed out when communicating with server\nTry again later.\n"));\r
189           }\r
190 \r
191           if (result.isRunning())\r
192           {\r
193             wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);\r
194           }\r
195           else if (result.isQueued())\r
196           {\r
197             wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);\r
198           }\r
199 \r
200           if (result.isFinished())\r
201           {\r
202             parseResult();\r
203             jobComplete = true;\r
204             jobsRunning--;\r
205           }\r
206           else\r
207           {\r
208             wsInfo.setProgressText(OutputHeader + "\n" +\r
209                                    result.getStatus());\r
210 \r
211             if (! (result.isJobFailed() || result.isServerError()))\r
212             {\r
213               try\r
214               {\r
215                 Thread.sleep(5000);\r
216               }\r
217               catch (InterruptedException ex1)\r
218               {\r
219               }\r
220 \r
221               //  System.out.println("I'm alive "+seqid+" "+jobid);\r
222             }\r
223             else\r
224             {\r
225               wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
226             }\r
227           }\r
228         }\r
229         catch (Exception ex)\r
230         {\r
231           allowedServerExceptions--;\r
232           wsInfo.appendProgressText("\nJPredWS Server exception!\n" +\r
233                                     ex.getMessage());\r
234 \r
235           try\r
236           {\r
237             if (allowedServerExceptions > 0)\r
238             {\r
239               Thread.sleep(5000);\r
240             }\r
241           }\r
242           catch (InterruptedException ex1)\r
243           {\r
244           }\r
245         }\r
246       }\r
247 \r
248       if (! (result.isJobFailed() || result.isServerError()))\r
249       {\r
250         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);\r
251       }\r
252       else\r
253       {\r
254         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
255       }\r
256     }\r
257 \r
258     void StartJob()\r
259     {\r
260       try\r
261       {\r
262         if (msa != null)\r
263         {\r
264           jobId = server.predictOnMsa(msa);\r
265         }\r
266         else\r
267         {\r
268           jobId = server.predict(sequence);\r
269         }\r
270 \r
271         if (jobId != null)\r
272         {\r
273           if (jobId.startsWith("Broken"))\r
274           {\r
275             throw new Exception("Submission " + jobId);\r
276           }\r
277           else\r
278           {\r
279             System.out.println(WsURL + " Job Id '" + jobId + "'");\r
280           }\r
281         }\r
282         else\r
283         {\r
284           throw new Exception("Server timed out - try again later\n");\r
285         }\r
286       }\r
287       catch (Exception e)\r
288       {\r
289         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);\r
290         allowedServerExceptions = 0;\r
291         jobComplete = false;\r
292 \r
293         wsInfo.appendProgressText("Failed to submit the prediction.\n"\r
294                                   +\r
295                                   "It is most likely that there is a problem with the server.\n"\r
296                                   + "Just close the window\n");\r
297         System.err.println(\r
298             "JPredWS Client: Failed to submit the prediction (Probably a server error - see below)\n" +\r
299             e.toString() + "\n");\r
300 \r
301         // e.printStackTrace(); TODO: JBPNote DEBUG\r
302       }\r
303     }\r
304 \r
305 \r
306 \r
307     private void addFloatAnnotations(Alignment al, int[] gapmap,\r
308                                      Vector values, String Symname,\r
309                                      String Visname, float min,\r
310                                      float max, int winLength)\r
311     {\r
312       Annotation[] annotations = new Annotation[al.getWidth()];\r
313 \r
314       for (int j = 0; j < values.size(); j++)\r
315       {\r
316         float value = Float.parseFloat(values.get(j).toString());\r
317         annotations[gapmap[j]] = new Annotation("", value + "", ' ',\r
318                                                 value);\r
319       }\r
320 \r
321       al.addAnnotation(new AlignmentAnnotation(Symname, Visname,\r
322                                                annotations, min, max, winLength));\r
323     }\r
324 \r
325     void parseResult()\r
326     {\r
327       // OutputHeader = output.getText();\r
328       if (result.isFailed())\r
329       {\r
330         OutputHeader += "Job failed.\n";\r
331       }\r
332 \r
333       if (result.getStatus() != null)\r
334       {\r
335         OutputHeader += ("\n" + result.getStatus());\r
336       }\r
337 \r
338       if (result.getPredfile() != null)\r
339       {\r
340         OutputHeader += ("\n" + result.getPredfile());\r
341 \r
342         // 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
343       }\r
344 \r
345       if (result.getAligfile() != null)\r
346       {\r
347         OutputHeader += ("\n" + result.getAligfile());\r
348       }\r
349 \r
350       wsInfo.setProgressText(OutputHeader);\r
351 \r
352       try\r
353       {\r
354         // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
355         jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.\r
356             getPredfile(),\r
357             "Paste");\r
358         SequenceI[] preds = prediction.getSeqsAsArray();\r
359         Alignment al;\r
360         int FirstSeq; // the position of the query sequence in Alignment al\r
361         boolean noMsa = true; // set if no MSA has been returned by JPred\r
362 \r
363         if ( (this.msa != null) && (result.getAligfile() != null))\r
364         {\r
365           // we ignore the returned alignment if we only predicted on a single sequence\r
366           String format = jalview.io.IdentifyFile.Identify(result.getAligfile(),\r
367               "Paste");\r
368 \r
369           if (jalview.io.FormatAdapter.formats.contains(format))\r
370           {\r
371             al = new Alignment(jalview.io.FormatAdapter.readFile(\r
372                 result.getAligfile(), "Paste", format));\r
373             noMsa = false;\r
374             FirstSeq = 0;\r
375           }\r
376           else\r
377           {\r
378             throw (new Exception(\r
379                 "Unknown format 'format' for file : \n" +\r
380                 result.getAligfile()));\r
381           }\r
382         }\r
383         else\r
384         {\r
385           al = new Alignment(preds);\r
386           FirstSeq = prediction.getQuerySeqPosition();\r
387         }\r
388 \r
389         if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
390             al.getSequenceAt(FirstSeq), SequenceInfo))\r
391         {\r
392           throw (new Exception(\r
393               "Couldn't recover sequence properties for JNet Query sequence!"));\r
394         }\r
395 \r
396         AlignmentAnnotation annot;\r
397         Annotation[] annotations = null;\r
398         int i = 0;\r
399         int width = preds[0].getSequence().length();\r
400 \r
401         int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
402 \r
403         if (gapmap.length != width)\r
404         {\r
405           throw (new Exception(\r
406               "Jnet Client Error\nNumber of residues in supposed query sequence :\n" +\r
407               al.getSequenceAt(FirstSeq).getName() + "\n" +\r
408               al.getSequenceAt(FirstSeq).getSequence() +\r
409               "\nDiffer from number of prediction sites in \n" +\r
410               result.getPredfile() + "\n"));\r
411         }\r
412 \r
413         // JBPNote Should also rename the query sequence sometime...\r
414         i = 0;\r
415 \r
416         while (i < preds.length)\r
417         {\r
418           String id = preds[i].getName().toUpperCase();\r
419 \r
420           if (id.startsWith("LUPAS") || id.startsWith("JNET") ||\r
421               id.startsWith("JPRED"))\r
422           {\r
423             annotations = new Annotation[al.getWidth()];\r
424 \r
425             if (id.equals("JNETPRED") || id.equals("JNETPSSM") ||\r
426                 id.equals("JNETFREQ") || id.equals("JNETHMM") ||\r
427                 id.equals("JNETALIGN") || id.equals("JPRED"))\r
428             {\r
429               for (int j = 0; j < width; j++)\r
430               {\r
431                 annotations[gapmap[j]] = new Annotation("", "",\r
432                     preds[i].getCharAt(j), 0);\r
433               }\r
434             }\r
435             else if (id.equals("JNETCONF"))\r
436             {\r
437               for (int j = 0; j < width; j++)\r
438               {\r
439                 float value = Float.parseFloat(preds[i].getCharAt(\r
440                     j) + "");\r
441                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
442                     j) + "", "", preds[i].getCharAt(j),\r
443                     value);\r
444               }\r
445             }\r
446             else\r
447             {\r
448               for (int j = 0; j < width; j++)\r
449               {\r
450                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
451                     j) + "", "", ' ', 0);\r
452               }\r
453             }\r
454 \r
455             if (id.equals("JNETCONF"))\r
456             {\r
457               annot = new AlignmentAnnotation(preds[i].getName(),\r
458                                               "JNet Output", annotations, 0f,\r
459                                               10f, 1);\r
460             }\r
461             else\r
462             {\r
463               annot = new AlignmentAnnotation(preds[i].getName(),\r
464                                               "JNet Output", annotations);\r
465             }\r
466 \r
467             al.addAnnotation(annot);\r
468 \r
469             if (noMsa)\r
470             {\r
471               al.deleteSequence(preds[i]);\r
472             }\r
473           }\r
474 \r
475           i++;\r
476         }\r
477 \r
478         Hashtable scores = prediction.getScores();\r
479 \r
480         /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
481                               "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
482 \r
483           addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
484          "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
485 \r
486           addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
487                               "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
488          */\r
489         AlignFrame af = new AlignFrame(al);\r
490 \r
491         Desktop.addInternalFrame(af, altitle,\r
492                                  AlignFrame.NEW_WINDOW_WIDTH,\r
493                                  AlignFrame.NEW_WINDOW_HEIGHT);\r
494       }\r
495       catch (Exception ex)\r
496       {\r
497         ex.printStackTrace();\r
498       }\r
499     }\r
500   }\r
501 }\r