refactored and ensured alCodonMappings are propagated to new alignments
[jalview.git] / src / jalview / ws / JPredThread.java
1 package jalview.ws;\r
2 \r
3 import java.util.*;\r
4 \r
5 import jalview.analysis.*;\r
6 import jalview.bin.*;\r
7 import jalview.datamodel.*;\r
8 import jalview.datamodel.Alignment;\r
9 import jalview.gui.*;\r
10 import jalview.io.*;\r
11 import jalview.util.*;\r
12 import vamsas.objects.simple.JpredResult;\r
13 \r
14 class JPredThread\r
15     extends WSThread implements WSClientI\r
16 {\r
17   // TODO: put mapping between JPredJob input and input data here - JNetAnnotation adding is done after result parsing.\r
18   class JPredJob\r
19       extends WSThread.WSJob\r
20   {\r
21     // TODO: make JPredJob deal only with what was sent to and received from a JNet service\r
22     int[] predMap = null; // mapping from sequence(i) to the original sequence(predMap[i]) being predicted on\r
23     vamsas.objects.simple.Sequence sequence;\r
24     vamsas.objects.simple.Msfalignment msa;\r
25     java.util.Hashtable SequenceInfo = null;\r
26     int msaIndex = 0; // the position of the original sequence in the array of Sequences in the input object that this job holds a prediction for\r
27     /**\r
28      *\r
29      * @return true if getResultSet will return a valid alignment and prediction result.\r
30      */\r
31     public boolean hasResults()\r
32     {\r
33       if (subjobComplete && result != null && result.isFinished()\r
34           && ( (JpredResult) result).getPredfile() != null &&\r
35           ( (JpredResult) result).getAligfile() != null)\r
36       {\r
37         return true;\r
38       }\r
39       return false;\r
40     }\r
41 \r
42     boolean hasValidInput()\r
43     {\r
44       if (sequence != null)\r
45       {\r
46         return true;\r
47       }\r
48       return false;\r
49     }\r
50 \r
51     /**\r
52      *\r
53      * @return null or Object[] { annotated alignment for this prediction, ColumnSelection for this prediction} or null if no results available.\r
54      * @throws Exception\r
55      */\r
56     public Object[] getResultSet()\r
57         throws Exception\r
58     {\r
59       if (result == null || !result.isFinished())\r
60       {\r
61         return null;\r
62       }\r
63       Alignment al = null;\r
64       ColumnSelection alcsel = null;\r
65       int FirstSeq = -1; // the position of the query sequence in Alignment al\r
66 \r
67       JpredResult result = (JpredResult)this.result;\r
68 \r
69       jalview.bin.Cache.log.debug("Parsing output from JNet job.");\r
70       // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
71       jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.\r
72           getPredfile(),\r
73           "Paste");\r
74       SequenceI[] preds = prediction.getSeqsAsArray();\r
75       jalview.bin.Cache.log.debug("Got prediction profile.");\r
76 \r
77       if ( (this.msa != null) && (result.getAligfile() != null))\r
78       {\r
79         jalview.bin.Cache.log.debug("Getting associated alignment.");\r
80         // we ignore the returned alignment if we only predicted on a single sequence\r
81         String format = new jalview.io.IdentifyFile().Identify(result.\r
82             getAligfile(),\r
83             "Paste");\r
84 \r
85         if (jalview.io.FormatAdapter.isValidFormat(format))\r
86         {\r
87           SequenceI sqs[];\r
88           if (predMap != null)\r
89           {\r
90             Object[] alandcolsel = input.getAlignmentAndColumnSelection(\r
91                 alignFrame.getViewport().getGapCharacter());\r
92             sqs = (SequenceI[]) alandcolsel[0];\r
93             al = new Alignment(sqs);\r
94             alcsel = (ColumnSelection) alandcolsel[1];\r
95           }\r
96           else\r
97           {\r
98             al = new FormatAdapter().readFile(result.getAligfile(),\r
99                                               "Paste", format);\r
100             sqs = new SequenceI[al.getHeight()];\r
101 \r
102             for (int i = 0, j = al.getHeight(); i < j; i++)\r
103             {\r
104               sqs[i] = al.getSequenceAt(i);\r
105             }\r
106             if (!jalview.analysis.SeqsetUtils.deuniquify( (Hashtable)\r
107                 SequenceInfo, sqs))\r
108             {\r
109               throw (new Exception(\r
110                   "Couldn't recover sequence properties for alignment."));\r
111             }\r
112           }\r
113           FirstSeq = 0;\r
114           al.setDataset(null);\r
115 \r
116           jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,\r
117               FirstSeq,\r
118               false, predMap);\r
119 \r
120         }\r
121         else\r
122         {\r
123           throw (new Exception(\r
124               "Unknown format " + format + " for file : \n" +\r
125               result.getAligfile()));\r
126         }\r
127       }\r
128       else\r
129       {\r
130         al = new Alignment(preds);\r
131         FirstSeq = prediction.getQuerySeqPosition();\r
132         if (predMap != null)\r
133         {\r
134           char gc = alignFrame.getViewport().getGapCharacter();\r
135           SequenceI[] sqs = (SequenceI[]) ( (java.lang.Object[]) input.\r
136                                            getAlignmentAndColumnSelection(gc))[\r
137               0];\r
138           if (this.msaIndex >= sqs.length)\r
139           {\r
140             throw new Error("Implementation Error! Invalid msaIndex for JPredJob on parent MSA input object!");\r
141           }\r
142 \r
143           /////\r
144           //Uses RemoveGapsCommand\r
145           /////\r
146           new jalview.commands.RemoveGapsCommand("Remove Gaps",\r
147                                                  new SequenceI[]\r
148                                                  {sqs[msaIndex]},\r
149                                                  alignFrame.getCurrentView().\r
150                                                  getAlignment());\r
151 \r
152           SequenceI profileseq = al.getSequenceAt(FirstSeq);\r
153           profileseq.setSequence(sqs[msaIndex].getSequenceAsString());\r
154         }\r
155 \r
156         if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(\r
157             al.getSequenceAt(FirstSeq), SequenceInfo))\r
158         {\r
159           throw (new Exception(\r
160               "Couldn't recover sequence properties for JNet Query sequence!"));\r
161         }\r
162         else\r
163         {\r
164           al.setDataset(null);\r
165           jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,\r
166               FirstSeq,\r
167               true, predMap);\r
168           SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.\r
169           alignToProfileSeq(al, profileseq);\r
170           if (predMap != null)\r
171           {\r
172             // Adjust input view for gaps\r
173             // propagate insertions into profile\r
174             alcsel = propagateInsertions(profileseq, al, input);\r
175           }\r
176         }\r
177       }\r
178       return new Object[]\r
179           {\r
180           al, alcsel}; // , FirstSeq, noMsa};\r
181     }\r
182 \r
183     /**\r
184      * Given an alignment where all other sequences except profileseq are aligned to the ungapped profileseq, insert gaps in the other sequences to realign them with the residues in profileseq\r
185      * @param al\r
186      * @param profileseq\r
187      */\r
188     private void alignToProfileSeq(Alignment al, SequenceI profileseq)\r
189     {\r
190       char gc = al.getGapCharacter();\r
191       int[] gapMap = profileseq.gapMap();\r
192       // insert gaps into profile\r
193       for (int lp = 0, r = 0; r < gapMap.length; r++)\r
194       {\r
195         if (gapMap[r] - lp > 1)\r
196         {\r
197           StringBuffer sb = new StringBuffer();\r
198           for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)\r
199           {\r
200             sb.append(gc);\r
201           }\r
202           for (int s = 1, ns = al.getHeight(); s < ns; s++)\r
203           {\r
204             String sq = al.getSequenceAt(s).getSequenceAsString();\r
205             int diff = gapMap[r] - sq.length();\r
206             if (diff > 0)\r
207             {\r
208               // pad gaps\r
209               sq = sq + sb;\r
210               while ( (diff = gapMap[r] - sq.length()) > 0)\r
211               {\r
212                 sq = sq +\r
213                     ( (diff >= sb.length()) ? sb.toString() :\r
214                      sb.substring(0, diff));\r
215               }\r
216               al.getSequenceAt(s).setSequence(sq);\r
217             }\r
218             else\r
219             {\r
220               al.getSequenceAt(s).setSequence(sq.substring(0, gapMap[r]) +\r
221                                               sb.toString() +\r
222                                               sq.substring(gapMap[r]));\r
223             }\r
224           }\r
225         }\r
226         lp = gapMap[r];\r
227       }\r
228     }\r
229 \r
230     /**\r
231      * Add gaps into the sequences aligned to profileseq under the given AlignmentView\r
232      * @param profileseq\r
233      * @param al\r
234      * @param input\r
235      */\r
236     private ColumnSelection propagateInsertions(SequenceI profileseq,\r
237                                                 Alignment al,\r
238                                                 AlignmentView input)\r
239     {\r
240       char gc = al.getGapCharacter();\r
241       Object[] alandcolsel = input.getAlignmentAndColumnSelection(gc);\r
242       ColumnSelection nview = (ColumnSelection) alandcolsel[1];\r
243       SequenceI origseq;\r
244       nview.pruneDeletions(ShiftList.parseMap( (origseq = ( (SequenceI[])\r
245           alandcolsel[0])[0]).gapMap())); // recover original prediction sequence's mapping to view.\r
246       int[] viscontigs = nview.getVisibleContigs(0, profileseq.getLength());\r
247       int spos = 0;\r
248       int offset = 0;\r
249       //  input.pruneDeletions(ShiftList.parseMap(((SequenceI[]) alandcolsel[0])[0].gapMap()))\r
250       // add profile to visible contigs\r
251       for (int v = 0; v < viscontigs.length; v += 2)\r
252       {\r
253         if (viscontigs[v] > spos)\r
254         {\r
255           StringBuffer sb = new StringBuffer();\r
256           for (int s = 0, ns = viscontigs[v] - spos; s < ns; s++)\r
257           {\r
258             sb.append(gc);\r
259           }\r
260           for (int s = 0, ns = al.getHeight(); s < ns; s++)\r
261           {\r
262             SequenceI sqobj = al.getSequenceAt(s);\r
263             if (sqobj != profileseq)\r
264             {\r
265               String sq = al.getSequenceAt(s).getSequenceAsString();\r
266               if (sq.length() <= spos + offset)\r
267               {\r
268                 // pad sequence\r
269                 int diff = spos + offset - sq.length() - 1;\r
270                 if (diff > 0)\r
271                 {\r
272                   // pad gaps\r
273                   sq = sq + sb;\r
274                   while ( (diff = spos + offset - sq.length() - 1) > 0)\r
275                   {\r
276                     sq = sq +\r
277                         ( (diff >= sb.length()) ? sb.toString() :\r
278                          sb.substring(0, diff));\r
279                   }\r
280                 }\r
281                 sq += sb.toString();\r
282               }\r
283               else\r
284               {\r
285                 al.getSequenceAt(s).setSequence(sq.substring(0, spos + offset) +\r
286                                                 sb.toString() +\r
287                                                 sq.substring(spos + offset));\r
288               }\r
289             }\r
290           }\r
291           //offset+=sb.length();\r
292         }\r
293         spos = viscontigs[v + 1] + 1;\r
294       }\r
295       if ( (offset + spos) < profileseq.getLength())\r
296       {\r
297         StringBuffer sb = new StringBuffer();\r
298         for (int s = 0, ns = profileseq.getLength() - spos - offset; s < ns; s++)\r
299         {\r
300           sb.append(gc);\r
301         }\r
302         for (int s = 1, ns = al.getHeight(); s < ns; s++)\r
303         {\r
304           String sq = al.getSequenceAt(s).getSequenceAsString();\r
305           // pad sequence\r
306           int diff = origseq.getLength() - sq.length();\r
307           while (diff > 0)\r
308           {\r
309             sq = sq +\r
310                 ( (diff >= sb.length()) ? sb.toString() : sb.substring(0, diff));\r
311             diff = origseq.getLength() - sq.length();\r
312           }\r
313         }\r
314       }\r
315       return nview;\r
316     }\r
317 \r
318     public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)\r
319     {\r
320       super();\r
321       this.predMap = delMap;\r
322       String sq = AlignSeq.extractGaps(Comparison.GapChars,\r
323                                        seq.getSequenceAsString());\r
324       if (sq.length() >= 20)\r
325       {\r
326         this.SequenceInfo = SequenceInfo;\r
327         sequence = new vamsas.objects.simple.Sequence();\r
328         sequence.setId(seq.getName());\r
329         sequence.setSeq(sq);\r
330       }\r
331     }\r
332 \r
333     public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)\r
334     {\r
335       this(SequenceInfo, msf[0], delMap);\r
336       if (sequence != null)\r
337       {\r
338         if (msf.length > 1)\r
339         {\r
340           msa = new vamsas.objects.simple.Msfalignment();\r
341           jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();\r
342           msa.setMsf(pileup.print(msf));\r
343         }\r
344       }\r
345     }\r
346   }\r
347 \r
348   ext.vamsas.Jpred server;\r
349   String altitle = "";\r
350   JPredThread(WebserviceInfo wsinfo, String altitle, ext.vamsas.Jpred server,\r
351               String wsurl, AlignmentView alview, AlignFrame alframe)\r
352   {\r
353     super(alframe, wsinfo, alview, wsurl);\r
354     this.altitle = altitle;\r
355     this.server = server;\r
356   }\r
357 \r
358   JPredThread(WebserviceInfo wsinfo, String altitle, ext.vamsas.Jpred server,\r
359               String wsurl, Hashtable SequenceInfo, SequenceI seq, int[] delMap,\r
360               AlignmentView alview, AlignFrame alframe)\r
361   {\r
362     this(wsinfo, altitle, server, wsurl, alview, alframe);\r
363     JPredJob job = new JPredJob(SequenceInfo, seq, delMap);\r
364     if (job.hasValidInput())\r
365     {\r
366       OutputHeader = wsInfo.getProgressText();\r
367       jobs = new WSJob[]\r
368           {\r
369           job};\r
370       job.jobnum = 0;\r
371     }\r
372   }\r
373 \r
374   JPredThread(WebserviceInfo wsinfo, String altitle, ext.vamsas.Jpred server,\r
375               Hashtable SequenceInfo, SequenceI[] msf, int[] delMap,\r
376               AlignmentView alview, AlignFrame alframe, String wsurl)\r
377   {\r
378     this(wsinfo, altitle, server, wsurl, alview, alframe);\r
379     JPredJob job = new JPredJob(SequenceInfo, msf, delMap);\r
380     if (job.hasValidInput())\r
381     {\r
382       jobs = new WSJob[]\r
383           {\r
384           job};\r
385       OutputHeader = wsInfo.getProgressText();\r
386       job.jobnum = 0;\r
387     }\r
388   }\r
389 \r
390   void StartJob(WSJob j)\r
391   {\r
392     if (! (j instanceof JPredJob))\r
393     {\r
394       throw new Error("Implementation error - StartJob(JpredJob) called on " +\r
395                       j.getClass());\r
396     }\r
397     try\r
398     {\r
399       JPredJob job = (JPredJob) j;\r
400       if (job.msa != null)\r
401       {\r
402         job.jobId = server.predictOnMsa(job.msa);\r
403       }\r
404       else\r
405       if (job.sequence != null)\r
406       {\r
407         job.jobId = server.predict(job.sequence); // debug like : job.jobId = "/jobs/www-jpred/jp_Yatat29";//\r
408       }\r
409 \r
410       if (job.jobId != null)\r
411       {\r
412         if (job.jobId.startsWith("Broken"))\r
413         {\r
414           job.result = (vamsas.objects.simple.Result)new JpredResult();\r
415           job.result.setInvalid(true);\r
416           job.result.setStatus("Submission " + job.jobId);\r
417         }\r
418         else\r
419         {\r
420           job.submitted = true;\r
421           job.subjobComplete = false;\r
422           Cache.log.info(WsUrl + " Job Id '" + job.jobId + "'");\r
423         }\r
424       }\r
425       else\r
426       {\r
427         throw new Exception("Server timed out - try again later\n");\r
428       }\r
429     }\r
430     catch (Exception e)\r
431     {\r
432       if (e.getMessage().indexOf("Exception") > -1)\r
433       {\r
434         wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_STOPPED_SERVERERROR);\r
435         wsInfo.setProgressText(j.jobnum,\r
436                                "Failed to submit the prediction. (Just close the window)\n"\r
437                                +\r
438                                "It is most likely that there is a problem with the server.\n");\r
439         System.err.println(\r
440             "JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n" +\r
441             e.getMessage() + "\n");\r
442 \r
443         jalview.bin.Cache.log.warn("Server Exception", e);\r
444       }\r
445       else\r
446       {\r
447         wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_STOPPED_ERROR);\r
448         // JBPNote - this could be a popup informing the user of the problem.\r
449         wsInfo.appendProgressText(j.jobnum,\r
450                                   "Failed to submit the prediction:\n"\r
451                                   + e.getMessage() +\r
452                                   wsInfo.getProgressText());\r
453 \r
454         jalview.bin.Cache.log.debug("Failed Submission of job " + j.jobnum, e);\r
455 \r
456       }\r
457       j.allowedServerExceptions = -1;\r
458       j.subjobComplete = true;\r
459     }\r
460   }\r
461 \r
462   void parseResult()\r
463   {\r
464     int results = 0; // number of result sets received\r
465     JobStateSummary finalState = new JobStateSummary();\r
466     try\r
467     {\r
468       for (int j = 0; j < jobs.length; j++)\r
469       {\r
470         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);\r
471         if (jobs[j].submitted && jobs[j].subjobComplete && jobs[j].hasResults())\r
472         {\r
473           results++;\r
474         }\r
475       }\r
476     }\r
477     catch (Exception ex)\r
478     {\r
479 \r
480       Cache.log.error("Unexpected exception when processing results for " +\r
481                       altitle, ex);\r
482       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
483     }\r
484     if (results > 0)\r
485     {\r
486       wsInfo.showResultsNewFrame\r
487           .addActionListener(new java.awt.event.ActionListener()\r
488       {\r
489         public void actionPerformed(\r
490             java.awt.event.ActionEvent evt)\r
491         {\r
492           displayResults(true);\r
493         }\r
494       });\r
495       wsInfo.mergeResults\r
496           .addActionListener(new java.awt.event.ActionListener()\r
497       {\r
498         public void actionPerformed(\r
499             java.awt.event.ActionEvent evt)\r
500         {\r
501           displayResults(false);\r
502         }\r
503       });\r
504       wsInfo.setResultsReady();\r
505     }\r
506     else\r
507     {\r
508       wsInfo.setFinishedNoResults();\r
509     }\r
510   }\r
511 \r
512   void displayResults(boolean newWindow)\r
513   {\r
514     // TODO: cope with multiple subjobs.\r
515     if (jobs != null)\r
516     {\r
517       Object[] res = null;\r
518       boolean msa = false;\r
519       for (int jn = 0; jn < jobs.length; jn++)\r
520       {\r
521         Object[] jobres = null;\r
522         JPredJob j = (JPredJob) jobs[jn];\r
523 \r
524         if (j.hasResults())\r
525         {\r
526           // hack - we only deal with all single seuqence predictions or all profile predictions\r
527           msa = (j.msa != null) ? true : msa;\r
528           try\r
529           {\r
530             jalview.bin.Cache.log.debug("Parsing output of job " + jn);\r
531             jobres = j.getResultSet();\r
532             jalview.bin.Cache.log.debug("Finished parsing output.");\r
533             if (jobs.length == 1)\r
534             {\r
535               res = jobres;\r
536             }\r
537             else\r
538             {\r
539               // do merge with other job results\r
540               throw new Error(\r
541                   "Multiple JNet subjob merging not yet implemented.");\r
542             }\r
543           }\r
544           catch (Exception e)\r
545           {\r
546             jalview.bin.Cache.log.error(\r
547                 "JNet Client: JPred Annotation Parse Error",\r
548                 e);\r
549             wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_STOPPED_ERROR);\r
550             wsInfo.appendProgressText(j.jobnum,\r
551                                       OutputHeader + "\n" +\r
552                                       j.result.getStatus() +\r
553                                       "\nInvalid JNet job result data!\n" +\r
554                                       e.getMessage());\r
555             j.result.setBroken(true);\r
556           }\r
557         }\r
558       }\r
559 \r
560       if (res != null)\r
561       {\r
562         if (newWindow)\r
563         {\r
564           AlignFrame af;\r
565           if (input == null)\r
566           {\r
567             if (res[1] != null)\r
568             {\r
569               af = new AlignFrame( (Alignment) res[0], (ColumnSelection) res[1],\r
570                                   AlignFrame.DEFAULT_WIDTH,\r
571                                   AlignFrame.DEFAULT_HEIGHT);\r
572             }\r
573             else\r
574             {\r
575               af = new AlignFrame( (Alignment) res[0], AlignFrame.DEFAULT_WIDTH,\r
576                                   AlignFrame.DEFAULT_HEIGHT);\r
577             }\r
578           }\r
579           else\r
580           {\r
581             /*java.lang.Object[] alandcolsel = input.getAlignmentAndColumnSelection(alignFrame.getViewport().getGapCharacter());\r
582              if (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {\r
583               if (msa) {\r
584                 throw new Error("Implementation Error! ColumnSelection from input alignment will not map to result alignment!");\r
585               }\r
586                          }\r
587                          if (!msa) {\r
588               // update hidden regions to account for loss of gaps in profile. - if any\r
589               // gapMap returns insert list, interpreted as delete list by pruneDeletions\r
590               //((ColumnSelection) alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[]) alandcolsel[0])[0].gapMap()));\r
591                          }*/\r
592 \r
593             af = new AlignFrame( (Alignment) res[0], (ColumnSelection) res[1],\r
594                                 AlignFrame.DEFAULT_WIDTH,\r
595                                 AlignFrame.DEFAULT_HEIGHT);\r
596           }\r
597           Desktop.addInternalFrame(af, altitle,\r
598                                    AlignFrame.DEFAULT_WIDTH,\r
599                                    AlignFrame.DEFAULT_HEIGHT);\r
600         }\r
601         else\r
602         {\r
603           Cache.log.info("Append results onto existing alignment.");\r
604         }\r
605       }\r
606     }\r
607   }\r
608 \r
609   void pollJob(WSJob job)\r
610       throws Exception\r
611   {\r
612     job.result = server.getresult(job.jobId);\r
613   }\r
614 \r
615   public boolean isCancellable()\r
616   {\r
617     return false;\r
618   }\r
619 \r
620   public void cancelJob()\r
621   {\r
622     throw new Error("Implementation error!");\r
623   }\r
624 \r
625   public boolean canMergeResults()\r
626   {\r
627     return false;\r
628   }\r
629 \r
630 }\r