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