Logger moved to prefs so that class not found error can be handled in main
[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.Jpred 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     SequenceI aln[] = new SequenceI[msf.length];\r
67     for (int i=0,j=msf.length; i<j;i++)\r
68       aln[i] = new jalview.datamodel.Sequence(msf[i]);\r
69     SequenceInfo = jalview.analysis.SeqsetUtils.uniquify(aln, true);\r
70 \r
71     if (!locateWebService())\r
72     {\r
73       return;\r
74     }\r
75 \r
76     JPredThread jthread = new JPredThread(aln);\r
77     jthread.start();\r
78   }\r
79 \r
80   public void startJPredClient(String title, SequenceI seq)\r
81   {\r
82     if (wsInfo==null)\r
83       wsInfo = setWebService();\r
84     wsInfo.setProgressText("Job details for prediction on sequence :\n>" +\r
85                            seq.getName() + "\n" +\r
86                            AlignSeq.extractGaps("-. ", seq.getSequence()) +\r
87                            "\n");\r
88     altitle = "JNet prediction for sequence " + seq.getName() + " from " +\r
89         title;\r
90 \r
91     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
92 \r
93     if (!locateWebService())\r
94     {\r
95       return;\r
96     }\r
97 \r
98     JPredThread jthread = new JPredThread(seq);\r
99     jthread.start();\r
100   }\r
101 \r
102   private WebserviceInfo setWebService()\r
103   {\r
104     WebServiceName = "JNetWS";\r
105     WebServiceJobTitle = "JNet secondary structure prediction";\r
106     WebServiceReference =\r
107         "\"Cuff J. A and Barton G.J (1999) Application of enhanced " +\r
108         "multiple sequence alignment profiles to improve protein secondary structure prediction, " +\r
109         "Proteins 40:502-511\".";\r
110     WsURL = "http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred";\r
111 \r
112     WebserviceInfo wsInfo = new WebserviceInfo(WebServiceJobTitle,\r
113                                                WebServiceReference);\r
114 \r
115     return wsInfo;\r
116   }\r
117 \r
118   private boolean locateWebService()\r
119   {\r
120     ext.vamsas.JpredServiceLocator loc = new JpredServiceLocator(); // Default\r
121 \r
122     try\r
123     {\r
124       this.server = loc.getjpred(new java.net.URL(WsURL)); // JBPNote will be set from properties\r
125       ( (JpredSoapBindingStub)this.server).setTimeout(60000); // one minute stub\r
126     }\r
127     catch (Exception ex)\r
128     {\r
129       JOptionPane.showMessageDialog(Desktop.desktop,\r
130                                     "The Secondary Structure Prediction Service named " +\r
131                                     WebServiceName + " at " + WsURL +\r
132                                     " couldn't be located.",\r
133                                     "Internal Jalview Error",\r
134                                     JOptionPane.WARNING_MESSAGE);\r
135       wsInfo.setProgressText("Serious! " + WebServiceName +\r
136                              " Service location failed\nfor URL :" + WsURL +\r
137                              "\n" +\r
138                              ex.getMessage());\r
139       wsInfo.setStatus(wsInfo.STATE_STOPPED_SERVERERROR);\r
140 \r
141       return false;\r
142     }\r
143 \r
144     return true;\r
145   }\r
146 \r
147   class JPredThread\r
148       extends Thread\r
149   {\r
150     String OutputHeader;\r
151     vamsas.objects.simple.JpredResult result;\r
152     vamsas.objects.simple.Sequence sequence;\r
153     vamsas.objects.simple.Msfalignment msa;\r
154     String jobId;\r
155     boolean jobComplete = false;\r
156     int allowedServerExceptions = 3; // thread dies if too many exceptions.\r
157 \r
158     JPredThread(SequenceI seq)\r
159     {\r
160       OutputHeader = wsInfo.getProgressText();\r
161       this.sequence = new vamsas.objects.simple.Sequence();\r
162       this.sequence.setId(seq.getName());\r
163       this.sequence.setSeq(AlignSeq.extractGaps("-. ", seq.getSequence()));\r
164     }\r
165 \r
166     JPredThread(SequenceI[] msf)\r
167     {\r
168       OutputHeader = wsInfo.getProgressText();\r
169       this.sequence = new vamsas.objects.simple.Sequence();\r
170       this.sequence.setId(msf[0].getName());\r
171       this.sequence.setSeq(AlignSeq.extractGaps("-. ",\r
172                                                 msf[0].getSequence()));\r
173 \r
174       jalview.io.PileUpfile mwrite = new jalview.io.PileUpfile();\r
175       this.msa = new vamsas.objects.simple.Msfalignment();\r
176       msa.setMsf(mwrite.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         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);\r
308         allowedServerExceptions = -1;\r
309         jobComplete = true;\r
310 \r
311         wsInfo.setProgressText("Failed to submit the prediction. (Just close the window)\n"\r
312                                   + ((e.getMessage().indexOf("Exception")>-1) ? (\r
313                                   "It is most likely that there is a problem with the server.\n")\r
314                               : e.getMessage())\r
315                                   +wsInfo.getProgressText());\r
316         System.err.println(\r
317             "JPredWS Client: Failed to submit the prediction (Possibly a server error - see below)\n" +\r
318             e.getMessage() + "\n");\r
319 \r
320         jalview.bin.Cache.log.debug("Failed Submission",e);\r
321       }\r
322     }\r
323 \r
324 \r
325 \r
326     private void addFloatAnnotations(Alignment al, int[] gapmap,\r
327                                      Vector values, String Symname,\r
328                                      String Visname, float min,\r
329                                      float max, int winLength)\r
330     {\r
331       Annotation[] annotations = new Annotation[al.getWidth()];\r
332 \r
333       for (int j = 0; j < values.size(); j++)\r
334       {\r
335         float value = Float.parseFloat(values.get(j).toString());\r
336         annotations[gapmap[j]] = new Annotation("", value + "", ' ',\r
337                                                 value);\r
338       }\r
339 \r
340       al.addAnnotation(new AlignmentAnnotation(Symname, Visname,\r
341                                                annotations, min, max, winLength));\r
342     }\r
343 \r
344     void parseResult()\r
345     {\r
346       // OutputHeader = output.getText();\r
347       if (result.isFailed())\r
348       {\r
349         OutputHeader += "Job failed.\n";\r
350       }\r
351 \r
352       if (result.getStatus() != null)\r
353       {\r
354         OutputHeader += ("\n" + result.getStatus());\r
355       }\r
356 \r
357       if (result.getPredfile() != null)\r
358       {\r
359         OutputHeader += ("\n" + result.getPredfile());\r
360 \r
361         // 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
362       }\r
363 \r
364       if (result.getAligfile() != null)\r
365       {\r
366         OutputHeader += ("\n" + result.getAligfile());\r
367       }\r
368 \r
369       wsInfo.setProgressText(OutputHeader+"Parsing...");\r
370 \r
371       try\r
372       {\r
373         jalview.bin.Cache.log.debug("Parsing output from JNet job.");\r
374         // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
375         jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.\r
376             getPredfile(),\r
377             "Paste");\r
378         SequenceI[] preds = prediction.getSeqsAsArray();\r
379         jalview.bin.Cache.log.debug("Got prediction profile.");\r
380         Alignment al;\r
381         int FirstSeq; // the position of the query sequence in Alignment al\r
382         boolean noMsa = true; // set if no MSA has been returned by JPred\r
383 \r
384         if ( (this.msa != null) && (result.getAligfile() != null))\r
385         {\r
386           jalview.bin.Cache.log.debug("Getting associated alignment.");\r
387           // we ignore the returned alignment if we only predicted on a single sequence\r
388           String format = jalview.io.IdentifyFile.Identify(result.getAligfile(),\r
389               "Paste");\r
390 \r
391           if (jalview.io.FormatAdapter.formats.contains(format))\r
392           {\r
393             al = new Alignment(jalview.io.FormatAdapter.readFile(\r
394                 result.getAligfile(), "Paste", format));\r
395             for (int i=0, j=al.getHeight(); i<j; i++) {\r
396               SequenceI sq = al.getSequenceAt(i);\r
397               if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
398                   sq, (Hashtable) SequenceInfo.get(sq.getName())))\r
399               {\r
400                 throw (new Exception(\r
401                     "Couldn't recover sequence properties for JNet "\r
402                     +((i==0) ? "Query sequence" : "alignment sequence ("+i+")")));\r
403               }\r
404             }\r
405             noMsa = false;\r
406             FirstSeq = 0;\r
407           }\r
408           else\r
409           {\r
410             throw (new Exception(\r
411                 "Unknown format 'format' for file : \n" +\r
412                 result.getAligfile()));\r
413           }\r
414         }\r
415         else\r
416         {\r
417           al = new Alignment(preds);\r
418           FirstSeq = prediction.getQuerySeqPosition();\r
419           if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
420               al.getSequenceAt(FirstSeq), SequenceInfo))\r
421           {\r
422             throw (new Exception(\r
423                 "Couldn't recover sequence properties for JNet Query sequence!"));\r
424           }\r
425         }\r
426 \r
427 \r
428         AlignmentAnnotation annot;\r
429         Annotation[] annotations = null;\r
430         int i = 0;\r
431         int width = preds[0].getSequence().length();\r
432 \r
433         int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
434 \r
435         if (gapmap.length != width)\r
436         {\r
437           throw (new Exception(\r
438               "Jnet Client Error\nNumber of residues in supposed query sequence :\n" +\r
439               al.getSequenceAt(FirstSeq).getName() + "\n" +\r
440               al.getSequenceAt(FirstSeq).getSequence() +\r
441               "\nDiffer from number of prediction sites in \n" +\r
442               result.getPredfile() + "\n"));\r
443         }\r
444 \r
445         // JBPNote Should also rename the query sequence sometime...\r
446         i = 0;\r
447 \r
448         while (i < preds.length)\r
449         {\r
450           String id = preds[i].getName().toUpperCase();\r
451 \r
452           if (id.startsWith("LUPAS") || id.startsWith("JNET") ||\r
453               id.startsWith("JPRED"))\r
454           {\r
455             annotations = new Annotation[al.getWidth()];\r
456 \r
457             if (id.equals("JNETPRED") || id.equals("JNETPSSM") ||\r
458                 id.equals("JNETFREQ") || id.equals("JNETHMM") ||\r
459                 id.equals("JNETALIGN") || id.equals("JPRED"))\r
460             {\r
461               for (int j = 0; j < width; j++)\r
462               {\r
463                 annotations[gapmap[j]] = new Annotation("", "",\r
464                     preds[i].getCharAt(j), 0);\r
465               }\r
466             }\r
467             else if (id.equals("JNETCONF"))\r
468             {\r
469               for (int j = 0; j < width; j++)\r
470               {\r
471                 float value = Float.parseFloat(preds[i].getCharAt(\r
472                     j) + "");\r
473                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
474                     j) + "", "", preds[i].getCharAt(j),\r
475                     value);\r
476               }\r
477             }\r
478             else\r
479             {\r
480               for (int j = 0; j < width; j++)\r
481               {\r
482                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(\r
483                     j) + "", "", ' ', 0);\r
484               }\r
485             }\r
486 \r
487             if (id.equals("JNETCONF"))\r
488             {\r
489               annot = new AlignmentAnnotation(preds[i].getName(),\r
490                                               "JNet Output", annotations, 0f,\r
491                                               10f, 1);\r
492             }\r
493             else\r
494             {\r
495               annot = new AlignmentAnnotation(preds[i].getName(),\r
496                                               "JNet Output", annotations);\r
497             }\r
498 \r
499             al.addAnnotation(annot);\r
500 \r
501             if (noMsa)\r
502             {\r
503               al.deleteSequence(preds[i]);\r
504             }\r
505           }\r
506 \r
507           i++;\r
508         }\r
509 \r
510         Hashtable scores = prediction.getScores();\r
511 \r
512         /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
513                               "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
514 \r
515           addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
516          "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
517 \r
518           addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
519                               "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
520          */\r
521 \r
522         wsInfo.setProgressText(OutputHeader);\r
523         jalview.bin.Cache.log.debug("Finished parsing output.");\r
524         AlignFrame af = new AlignFrame(al);\r
525 \r
526         Desktop.addInternalFrame(af, altitle,\r
527                                  AlignFrame.NEW_WINDOW_WIDTH,\r
528                                  AlignFrame.NEW_WINDOW_HEIGHT);\r
529       }\r
530       catch (Exception ex)\r
531       {\r
532         jalview.bin.Cache.log.warn("Exception whilst parsing JNet style secondary structure prediction.");\r
533         jalview.bin.Cache.log.debug("Exception: ",ex);\r
534       }\r
535     }\r
536   }\r
537 }\r