after merge
[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       jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();\r
177       msa.setMsf(pileup.print(msf));\r
178     }\r
179 \r
180     public void run()\r
181     {\r
182       StartJob();\r
183 \r
184       while (!jobComplete && (allowedServerExceptions > 0))\r
185       {\r
186         try\r
187         {\r
188           if ( (result = server.getresult(jobId)) == null)\r
189           {\r
190             throw (new Exception(\r
191                 "Timed out when communicating with server\nTry again later.\n"));\r
192           }\r
193           if (result.getState()==0)\r
194             jalview.bin.Cache.log.debug("Finished "+jobId);\r
195           if (result.isRunning())\r
196           {\r
197             wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);\r
198           }\r
199           if (result.isQueued())\r
200           {\r
201             wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);\r
202           }\r
203 \r
204           wsInfo.setProgressText(OutputHeader + "\n" +\r
205                                  result.getStatus());\r
206 \r
207           if (result.isFinished())\r
208           {\r
209 \r
210             parseResult();\r
211             jobComplete = true;\r
212             jobsRunning--;\r
213           } else {\r
214             // catch exceptions\r
215             if (! (result.isJobFailed() || result.isServerError()))\r
216             {\r
217               try\r
218               {\r
219                 Thread.sleep(5000);\r
220               }\r
221               catch (InterruptedException ex1)\r
222               {\r
223               }\r
224 \r
225               //  System.out.println("I'm alive "+seqid+" "+jobid);\r
226             }\r
227             else\r
228             {\r
229               wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
230               jobsRunning--;\r
231               jobComplete = true;\r
232             }\r
233           }\r
234         }\r
235         catch (Exception ex)\r
236         {\r
237           allowedServerExceptions--;\r
238           wsInfo.appendProgressText("\nJPredWS Server exception!\n" +\r
239                                     ex.getMessage());\r
240 \r
241           try\r
242           {\r
243             if (allowedServerExceptions > 0)\r
244             {\r
245               Thread.sleep(5000);\r
246             }\r
247           }\r
248           catch (InterruptedException ex1)\r
249           {\r
250           }\r
251         }\r
252         catch (OutOfMemoryError er)\r
253         {\r
254           jobComplete = true;\r
255           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
256           JOptionPane.showInternalMessageDialog(Desktop.desktop,\r
257                                                 "Out of memory handling result!!"\r
258                                                 +\r
259               "\nSee help files for increasing Java Virtual Machine memory."\r
260                                                 , "Out of memory",\r
261                                                 JOptionPane.WARNING_MESSAGE);\r
262           System.out.println("JPredClient: "+er);\r
263           System.gc();\r
264         }\r
265       }\r
266       if (result!=null)\r
267         if (! (result.isJobFailed() || result.isServerError()))\r
268         {\r
269           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);\r
270         }\r
271         else\r
272         {\r
273           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
274         }\r
275     }\r
276 \r
277     void StartJob()\r
278     {\r
279       try\r
280       {\r
281         if (msa != null)\r
282         {\r
283           jobId = server.predictOnMsa(msa);\r
284         }\r
285         else\r
286         {\r
287           jobId = server.predict(sequence);\r
288         }\r
289 \r
290         if (jobId != null)\r
291         {\r
292           if (jobId.startsWith("Broken"))\r
293           {\r
294             throw new Exception("Submission " + jobId);\r
295           }\r
296           else\r
297           {\r
298             System.out.println(WsURL + " Job Id '" + jobId + "'");\r
299           }\r
300         }\r
301         else\r
302         {\r
303           throw new Exception("Server timed out - try again later\n");\r
304         }\r
305       }\r
306       catch (Exception e)\r
307       {\r
308         if (e.getMessage().indexOf("Exception")>-1) {\r
309           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);\r
310           wsInfo.setProgressText(\r
311               "Failed to submit the prediction. (Just close the window)\n"\r
312               +\r
313               "It is most likely that there is a problem with the server.\n");\r
314           System.err.println(\r
315               "JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n" +\r
316               e.getMessage() + "\n");\r
317 \r
318           jalview.bin.Cache.log.warn("Server Exception",e);\r
319         } else {\r
320           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
321           // JBPNote - this could be a popup informing the user of the problem.\r
322           wsInfo.setProgressText("Failed to submit the prediction:\n"\r
323                                  +e.getMessage()+\r
324                                  wsInfo.getProgressText());\r
325 \r
326           jalview.bin.Cache.log.debug("Failed Submission",e);\r
327 \r
328         }\r
329         allowedServerExceptions = -1;\r
330         jobComplete = true;\r
331 \r
332       }\r
333     }\r
334 \r
335 \r
336 \r
337   /*  private void addFloatAnnotations(Alignment al, int[] gapmap,\r
338                                      Vector values, String Symname,\r
339                                      String Visname, float min,\r
340                                      float max, int winLength)\r
341     {\r
342       Annotation[] annotations = new Annotation[al.getWidth()];\r
343 \r
344       for (int j = 0; j < values.size(); j++)\r
345       {\r
346         float value = Float.parseFloat(values.get(j).toString());\r
347         annotations[gapmap[j]] = new Annotation("", value + "", ' ',\r
348                                                 value);\r
349       }\r
350 \r
351       al.addAnnotation(new AlignmentAnnotation(Symname, Visname,\r
352                                                annotations, min, max, winLength));\r
353     }*/\r
354 \r
355     void parseResult()\r
356     {\r
357       // OutputHeader = output.getText();\r
358       if (result.isFailed())\r
359       {\r
360         OutputHeader += "Job failed.\n";\r
361       }\r
362 \r
363       if (result.getStatus() != null)\r
364       {\r
365         OutputHeader += ("\n" + result.getStatus());\r
366       }\r
367 \r
368       if (result.getPredfile() != null)\r
369       {\r
370         OutputHeader += ("\n" + result.getPredfile());\r
371 \r
372         // 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
373       }\r
374 \r
375       if (result.getAligfile() != null)\r
376       {\r
377         OutputHeader += ("\n" + result.getAligfile());\r
378       }\r
379 \r
380       wsInfo.setProgressText(OutputHeader+"Parsing...");\r
381 \r
382       try\r
383       {\r
384         jalview.bin.Cache.log.debug("Parsing output from JNet job.");\r
385         // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
386         jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.\r
387             getPredfile(),\r
388             "Paste");\r
389         SequenceI[] preds = prediction.getSeqsAsArray();\r
390         jalview.bin.Cache.log.debug("Got prediction profile.");\r
391         Alignment al;\r
392         int FirstSeq; // the position of the query sequence in Alignment al\r
393         boolean noMsa = true; // set if no MSA has been returned by JPred\r
394 \r
395         if ( (this.msa != null) && (result.getAligfile() != null))\r
396         {\r
397           jalview.bin.Cache.log.debug("Getting associated alignment.");\r
398           // we ignore the returned alignment if we only predicted on a single sequence\r
399           String format = jalview.io.IdentifyFile.Identify(result.getAligfile(),\r
400               "Paste");\r
401 \r
402           if (jalview.io.FormatAdapter.formats.contains(format))\r
403           {\r
404             al = new Alignment(new FormatAdapter().readFile(\r
405                 result.getAligfile(), "Paste", format));\r
406             for (int i=0, j=al.getHeight(); i<j; i++) {\r
407               SequenceI sq = al.getSequenceAt(i);\r
408               if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
409                   sq, (Hashtable) SequenceInfo.get(sq.getName())))\r
410               {\r
411                 throw (new Exception(\r
412                     "Couldn't recover sequence properties for JNet "\r
413                     +((i==0) ? "Query sequence" : "alignment sequence ("+i+")")));\r
414               }\r
415             }\r
416             noMsa = false;\r
417             FirstSeq = 0;\r
418           }\r
419           else\r
420           {\r
421             throw (new Exception(\r
422                 "Unknown format 'format' for file : \n" +\r
423                 result.getAligfile()));\r
424           }\r
425         }\r
426         else\r
427         {\r
428           al = new Alignment(preds);\r
429           FirstSeq = prediction.getQuerySeqPosition();\r
430           if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
431               al.getSequenceAt(FirstSeq), SequenceInfo))\r
432           {\r
433             throw (new Exception(\r
434                 "Couldn't recover sequence properties for JNet Query sequence!"));\r
435           }\r
436         }\r
437 \r
438 \r
439         AlignmentAnnotation annot;\r
440         Annotation[] annotations = null;\r
441         int i = 0;\r
442         int width = preds[0].getSequence().length();\r
443 \r
444         int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
445 \r
446         if (gapmap.length != width)\r
447         {\r
448           throw (new Exception(\r
449               "Jnet Client Error\nNumber of residues in supposed query sequence :\n" +\r
450               al.getSequenceAt(FirstSeq).getName() + "\n" +\r
451               al.getSequenceAt(FirstSeq).getSequence() +\r
452               "\nDiffer from number of prediction sites in \n" +\r
453               result.getPredfile() + "\n"));\r
454         }\r
455 \r
456         // JBPNote Should also rename the query sequence sometime...\r
457         i = 0;\r
458 \r
459         while (i < preds.length)\r
460         {\r
461           String id = preds[i].getName().toUpperCase();\r
462 \r
463           if (id.startsWith("LUPAS") || id.startsWith("JNET") ||\r
464               id.startsWith("JPRED"))\r
465           {\r
466             annotations = new Annotation[al.getWidth()];\r
467 \r
468             if (id.equals("JNETPRED") || id.equals("JNETPSSM") ||\r
469                 id.equals("JNETFREQ") || id.equals("JNETHMM") ||\r
470                 id.equals("JNETALIGN") || id.equals("JPRED"))\r
471             {\r
472               for (int j = 0; j < width; j++)\r
473               {\r
474                 annotations[gapmap[j]] = new Annotation("", "",\r
475                     preds[i].getCharAt(j), 0);\r
476               }\r
477             }\r
478             else if (id.equals("JNETCONF"))\r
479             {\r
480               for (int j = 0; j < width; j++)\r
481               {\r
482                 float value = Float.parseFloat(preds[i].getCharAt(\r
483                     j) + "");\r
484                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
485                     j) + "", "", preds[i].getCharAt(j),\r
486                     value);\r
487               }\r
488             }\r
489             else\r
490             {\r
491               for (int j = 0; j < width; j++)\r
492               {\r
493                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
494                     j) + "", "", ' ', 0);\r
495               }\r
496             }\r
497 \r
498             if (id.equals("JNETCONF"))\r
499             {\r
500               annot = new AlignmentAnnotation(preds[i].getName(),\r
501                                               "JNet Output", annotations, 0f,\r
502                                               10f, 1);\r
503             }\r
504             else\r
505             {\r
506               annot = new AlignmentAnnotation(preds[i].getName(),\r
507                                               "JNet Output", annotations);\r
508             }\r
509 \r
510             al.addAnnotation(annot);\r
511 \r
512             if (noMsa)\r
513             {\r
514               al.deleteSequence(preds[i]);\r
515             }\r
516           }\r
517 \r
518           i++;\r
519         }\r
520 \r
521         //Hashtable scores = prediction.getScores();\r
522 \r
523         /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
524                               "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
525 \r
526           addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
527          "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
528 \r
529           addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
530                               "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
531          */\r
532 \r
533         wsInfo.setProgressText(OutputHeader);\r
534         jalview.bin.Cache.log.debug("Finished parsing output.");\r
535         AlignFrame af = new AlignFrame(al);\r
536 \r
537         Desktop.addInternalFrame(af, altitle,\r
538                                  AlignFrame.NEW_WINDOW_WIDTH,\r
539                                  AlignFrame.NEW_WINDOW_HEIGHT);\r
540       }\r
541       catch (Exception ex)\r
542       {\r
543         jalview.bin.Cache.log.warn("Exception whilst parsing JNet style secondary structure prediction.");\r
544         jalview.bin.Cache.log.debug("Exception: ",ex);\r
545       }\r
546     }\r
547   }\r
548 }\r