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