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