Improved consistency between JPredWS and MsaWS
[jalview.git] / src / jalview / ws / JPredClient.java
1 package jalview.ws;\r
2 \r
3 import org.apache.axis.client.*;\r
4 import javax.xml.namespace.QName;\r
5 import java.util.*;\r
6 import jalview.datamodel.*;\r
7 import jalview.gui.*;\r
8 import javax.swing.*;\r
9 import java.util.*;\r
10 import java.awt.*;\r
11 import jalview.analysis.AlignSeq;\r
12 import ext.vamsas.*;\r
13 \r
14 \r
15 public class JPredClient extends WSClient\r
16 {\r
17   ext.vamsas.JPredWS server;\r
18   String altitle = "";\r
19   java.util.Hashtable SequenceInfo = null;\r
20   private void setWebService() {\r
21     WebServiceName = "JNetWS";\r
22     WebServiceJobTitle = "JNet secondary structure prediction";\r
23     WebServiceReference="\"Cuff J. A and Barton G.J (1999) Application of enhanced "\r
24         + "multiple sequence alignment profiles to improve protein secondary structure prediction, "\r
25         + "Proteins 40:502-511\".";\r
26     WsURL="http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred";\r
27   }\r
28   public JPredClient(String title, SequenceI[] msf)\r
29   {\r
30     wsInfo = new WebserviceInfo(WebServiceJobTitle, WebServiceReference);\r
31     SequenceI seq = msf[0];\r
32     altitle = "JNet prediction on "+seq.getName()+" using alignment from "+title;\r
33 \r
34     wsInfo.setProgressText("Job details for MSA based prediction ("+title+") on sequence :\n>"\r
35                    + seq.getName() + "\n"\r
36                    + AlignSeq.extractGaps("-. ",seq.getSequence()) + "\n");\r
37 \r
38     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
39 \r
40     JPredWSServiceLocator loc = new JPredWSServiceLocator(); // Default\r
41     // JBPNote url will be set from properties\r
42     try {\r
43       this.server = loc.getjpred(new java.net.URL(WsURL));\r
44     }\r
45     catch (Exception ex) {\r
46       JOptionPane.showMessageDialog(Desktop.desktop, "The Secondary Structure Prediction Service named "\r
47                                     +WebServiceName+" at "+WsURL+" couldn't be located.",\r
48                                     "Internal Jalview Error", JOptionPane.WARNING_MESSAGE);\r
49       wsInfo.setProgressText("Serious! "+WebServiceName+" Service location failed\nfor URL :"\r
50                      +WsURL+"\n"+ex.getMessage());\r
51     }\r
52 \r
53     JPredThread jthread = new JPredThread(msf);\r
54     jthread.start();\r
55   }\r
56 \r
57   public JPredClient(String title, SequenceI seq)\r
58   {\r
59     setWebService();\r
60     wsInfo = new WebserviceInfo(WebServiceJobTitle, WebServiceReference);\r
61     wsInfo.setProgressText("Job details for prediction on sequence :\n>"\r
62                    + seq.getName() + "\n" + AlignSeq.extractGaps("-. ",seq.getSequence()) + "\n");\r
63     altitle = "JNet prediction for sequence "+seq.getName()+" from "+title;\r
64     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
65 \r
66     JPredWSServiceLocator loc = new JPredWSServiceLocator(); // Default\r
67     try {\r
68       this.server = loc.getjpred(new java.net.URL(WsURL)); // JBPNote will be set from properties\r
69     }\r
70     catch (Exception ex) {\r
71       JOptionPane.showMessageDialog(Desktop.desktop, "The Secondary Structure Prediction Service named "\r
72                                     +WebServiceName+" at "+WsURL+" couldn't be located.",\r
73                                     "Internal Jalview Error", JOptionPane.WARNING_MESSAGE);\r
74       wsInfo.setProgressText("Serious! "+WebServiceName+" Service location failed\nfor URL :"\r
75                      +WsURL+"\n"+ex.getMessage());\r
76     }\r
77 \r
78     JPredThread jthread = new JPredThread(seq);\r
79     jthread.start();\r
80   }\r
81 \r
82 \r
83   class JPredThread\r
84       extends Thread\r
85   {\r
86     String OutputHeader;\r
87     ext.vamsas.JpredResult result;\r
88     ext.vamsas.Sequence sequence;\r
89     ext.vamsas.Msfalignment msa;\r
90     String jobId;\r
91     boolean jobComplete = false;\r
92     int allowedServerExceptions = 3; // thread dies if too many exceptions.\r
93     JPredThread(SequenceI seq)\r
94     {\r
95       OutputHeader = wsInfo.getProgressText();\r
96       this.sequence = new ext.vamsas.Sequence();\r
97       this.sequence.setId(seq.getName());\r
98       this.sequence.setSeq(AlignSeq.extractGaps("-. ",seq.getSequence()));\r
99     }\r
100 \r
101     JPredThread(SequenceI[] msf)\r
102     {\r
103       OutputHeader = wsInfo.getProgressText();\r
104       this.sequence = new ext.vamsas.Sequence();\r
105       this.sequence.setId(msf[0].getName());\r
106       this.sequence.setSeq(AlignSeq.extractGaps("-. ",msf[0].getSequence()));\r
107       jalview.io.MSFfile mwrite = new jalview.io.MSFfile();\r
108       this.msa = new ext.vamsas.Msfalignment();\r
109       msa.setMsf(mwrite.print(msf));\r
110     }\r
111 \r
112 \r
113     public void run()\r
114     {\r
115 \r
116       StartJob();\r
117 \r
118       while (!jobComplete && (allowedServerExceptions > 0))\r
119       {\r
120         try\r
121         {\r
122           result = server.getresult(jobId);\r
123 \r
124          if( result.isRunning() )\r
125            wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);\r
126          else if( result.isQueued() )\r
127            wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);\r
128 \r
129           if (result.isFinished())\r
130           {\r
131             parseResult();\r
132             jobComplete = true;\r
133             jobsRunning--;\r
134           }\r
135           else\r
136           {\r
137             wsInfo.setProgressText(OutputHeader + "\n" + result.getStatus());\r
138             if (! (result.isJobFailed() || result.isServerError()))\r
139             {\r
140               Thread.sleep(5000);\r
141               //  System.out.println("I'm alive "+seqid+" "+jobid);\r
142             } else {\r
143               wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
144             }\r
145           }\r
146         }\r
147         catch (Exception ex)\r
148         {\r
149           allowedServerExceptions--;\r
150           wsInfo.appendProgressText("\nJPredWS Server exception!\n" + ex.getMessage());\r
151         }\r
152       }\r
153 \r
154       if (! (result.isJobFailed() || result.isServerError()))\r
155         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);\r
156       else\r
157         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
158     }\r
159 \r
160     void StartJob()\r
161     {\r
162       try\r
163       {\r
164         if (msa!=null)  {\r
165           jobId = server.predictOnMsa(msa);\r
166         } else {\r
167           jobId = server.predict(sequence);\r
168         }\r
169         System.out.println(WsURL+" Job Id '"+jobId+"'");\r
170       }\r
171       catch (Exception e)\r
172       {\r
173         System.out.println("JPredWS Client: Failed to submit the prediction\n" +\r
174                            e.toString() + "\n");\r
175         e.printStackTrace();\r
176       }\r
177     }\r
178 \r
179     private void addFloatAnnotations(Alignment al, int[] gapmap, Vector values, String Symname, String Visname, float min, float max, int winLength) {\r
180 \r
181       Annotation[] annotations = new Annotation[al.getWidth()];\r
182       for (int j = 0; j < values.size(); j++)\r
183       {\r
184         float value = Float.parseFloat(values.get(j).toString());\r
185         annotations[gapmap[j]] = new Annotation("", value+"",' ',value);\r
186       }\r
187       al.addAnnotation(new AlignmentAnnotation(Symname, Visname, annotations, min, max, winLength));\r
188     }\r
189 \r
190     void parseResult()\r
191     {\r
192       // OutputHeader = output.getText();\r
193       if (result.isFailed()) {\r
194         OutputHeader +="Job failed.\n";\r
195       }\r
196       if (result.getStatus()!=null) {\r
197         OutputHeader += "\n"+result.getStatus();\r
198       }\r
199       if (result.getPredfile()!=null) {\r
200         OutputHeader += "\n"+result.getPredfile();\r
201       // 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
202       }\r
203       if (result.getAligfile()!=null) {\r
204         OutputHeader += "\n"+result.getAligfile();\r
205       }\r
206       wsInfo.setProgressText(OutputHeader);\r
207       try {\r
208         // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
209         jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.getPredfile(), "Paste");\r
210         SequenceI[] preds = prediction.getSeqsAsArray();\r
211         Alignment al;\r
212         int FirstSeq; // the position of the query sequence in Alignment al\r
213         boolean noMsa = true; // set if no MSA has been returned by JPred\r
214 \r
215         if (this.msa!=null && result.getAligfile()!=null) {\r
216           // we ignore the returned alignment if we only predicted on a single sequence\r
217           String format = jalview.io.IdentifyFile.Identify(result.getAligfile(), "Paste");\r
218           if (jalview.io.FormatAdapter.formats.contains(format))\r
219           {\r
220             al = new Alignment(jalview.io.FormatAdapter.readFile(result.getAligfile(),"Paste",format));\r
221             noMsa = false;\r
222             FirstSeq = 0;\r
223           }\r
224           else\r
225           {\r
226             throw (new Exception("Unknown format 'format' for file : \n" +\r
227                              result.getAligfile()));\r
228           }\r
229 \r
230         } else {\r
231           al = new Alignment(preds);\r
232           FirstSeq = prediction.getQuerySeqPosition();\r
233         }\r
234 \r
235         if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(al.getSequenceAt(FirstSeq), SequenceInfo))\r
236           throw (new Exception("Couldn't recover sequence properties for JNet Query sequence!"));\r
237 \r
238         AlignmentAnnotation annot;\r
239         Annotation [] annotations = null;\r
240         int i = 0;\r
241         int width = preds[0].getSequence().length();\r
242 \r
243 \r
244         int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
245 \r
246         if (gapmap.length!=width) {\r
247           throw (new Exception("Jnet Client Error\nNumber of residues in supposed query sequence :\n"\r
248                                +al.getSequenceAt(FirstSeq).getName()+"\n"\r
249                                +al.getSequenceAt(FirstSeq).getSequence()\r
250                                +"\nDiffer from number of prediction sites in \n"+result.getPredfile()+"\n"));\r
251         }\r
252         // JBPNote Should also rename the query sequence sometime...\r
253         i=0;\r
254         while (i < preds.length)\r
255         {\r
256           String id = preds[i].getName().toUpperCase();\r
257           if(id.startsWith("LUPAS") || id.startsWith("JNET") || id.startsWith("JPRED"))\r
258           {\r
259             annotations = new Annotation[al.getWidth()];\r
260 \r
261             if(id.equals("JNETPRED")\r
262                || id.equals("JNETPSSM")\r
263                || id.equals("JNETFREQ")\r
264                || id.equals("JNETHMM")\r
265                || id.equals("JNETALIGN")\r
266                || id.equals("JPRED"))\r
267             {\r
268               for (int j = 0; j < width; j++)\r
269                 annotations[gapmap[j]] = new Annotation("", "", preds[i].getCharAt(j), 0);\r
270             }\r
271             else if(id.equals("JNETCONF"))\r
272             {\r
273               for (int j = 0; j < width; j++)\r
274               {\r
275                 float value = Float.parseFloat(preds[i].getCharAt(j)+"");\r
276                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(j)+"", "",preds[i].getCharAt(j),value);\r
277               }\r
278             }\r
279             else\r
280             {\r
281               for (int j = 0; j < width; j++) {\r
282                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(j)+"", "", ' ', 0);\r
283               }\r
284             }\r
285 \r
286             if(id.equals("JNETCONF"))\r
287               annot = new AlignmentAnnotation(preds[i].getName(),\r
288                                            "JNet Output",\r
289                                            annotations,0f,10f,1);\r
290 \r
291             else   annot = new AlignmentAnnotation(preds[i].getName(),\r
292                                             "JNet Output",\r
293                                             annotations);\r
294             al.addAnnotation(annot);\r
295             if (noMsa)\r
296               al.deleteSequence(preds[i]);\r
297           }\r
298           i++;\r
299         }\r
300 \r
301         Hashtable scores = prediction.getScores();\r
302       /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
303                             "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
304 \r
305         addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
306                             "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
307 \r
308         addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
309                             "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
310        */\r
311         AlignFrame af = new AlignFrame(al);\r
312 \r
313 \r
314         Desktop.addInternalFrame(af,\r
315                                  altitle,\r
316                                  AlignFrame.NEW_WINDOW_WIDTH, AlignFrame.NEW_WINDOW_HEIGHT);\r
317       }catch(Exception ex){ex.printStackTrace();}\r
318 \r
319     }\r
320 \r
321   }\r
322 }\r
323 \r