JAL-2446 merged to spike branch
[jalview.git] / src / jalview / ws / jws1 / JPredThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws.jws1;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.analysis.SeqsetUtils;
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.AlignmentView;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.AlignFrame;
33 import jalview.gui.Desktop;
34 import jalview.gui.WebserviceInfo;
35 import jalview.io.DataSourceType;
36 import jalview.io.FileFormatI;
37 import jalview.io.FormatAdapter;
38 import jalview.io.IdentifyFile;
39 import jalview.io.JPredFile;
40 import jalview.io.JnetAnnotationMaker;
41 import jalview.io.PileUpfile;
42 import jalview.util.Comparison;
43 import jalview.util.MessageManager;
44 import jalview.ws.AWsJob;
45 import jalview.ws.JobStateSummary;
46 import jalview.ws.WSClientI;
47
48 import java.util.Hashtable;
49 import java.util.List;
50
51 import vamsas.objects.simple.JpredResult;
52
53 class JPredThread extends JWS1Thread implements WSClientI
54 {
55   // TODO: put mapping between JPredJob input and input data here -
56   // JNetAnnotation adding is done after result parsing.
57   class JPredJob extends WSJob
58   {
59     // TODO: make JPredJob deal only with what was sent to and received from a
60     // JNet service
61     int[] predMap = null; // mapping from sequence(i) to the original
62
63     // sequence(predMap[i]) being predicted on
64
65     vamsas.objects.simple.Sequence sequence;
66
67     vamsas.objects.simple.Msfalignment msa;
68
69     java.util.Hashtable SequenceInfo = null;
70
71     int msaIndex = 0; // the position of the original sequence in the array of
72
73     // Sequences in the input object that this job holds a
74     // prediction for
75
76     /**
77      * 
78      * @return true if getResultSet will return a valid alignment and prediction
79      *         result.
80      */
81     @Override
82     public boolean hasResults()
83     {
84       if (subjobComplete && result != null && result.isFinished()
85               && ((JpredResult) result).getPredfile() != null
86               && ((JpredResult) result).getAligfile() != null)
87       {
88         return true;
89       }
90       return false;
91     }
92
93     @Override
94     public boolean hasValidInput()
95     {
96       if (sequence != null)
97       {
98         return true;
99       }
100       return false;
101     }
102
103     /**
104      * 
105      * @return null or Object[] { annotated alignment for this prediction,
106      *         ColumnSelection for this prediction} or null if no results
107      *         available.
108      * @throws Exception
109      */
110     public Object[] getResultSet() throws Exception
111     {
112       if (result == null || !result.isFinished())
113       {
114         return null;
115       }
116       AlignmentI al = null;
117       HiddenColumns alhidden = null;
118       int FirstSeq = -1; // the position of the query sequence in Alignment al
119
120       JpredResult result = (JpredResult) this.result;
121
122       Cache.log.debug("Parsing output from JNet job.");
123       // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
124       // "File");
125       JPredFile prediction = new JPredFile(
126               result.getPredfile(), DataSourceType.PASTE);
127       SequenceI[] preds = prediction.getSeqsAsArray();
128       Cache.log.debug("Got prediction profile.");
129
130       if ((this.msa != null) && (result.getAligfile() != null))
131       {
132         Cache.log.debug("Getting associated alignment.");
133         // we ignore the returned alignment if we only predicted on a single
134         // sequence
135         FileFormatI format = new IdentifyFile().identify(
136                 result.getAligfile(), DataSourceType.PASTE);
137
138         if (format != null)
139         {
140           SequenceI sqs[];
141           if (predMap != null)
142           {
143             Object[] alandcolsel = input
144                     .getAlignmentAndHiddenColumns(getGapChar());
145             sqs = (SequenceI[]) alandcolsel[0];
146             al = new Alignment(sqs);
147             alhidden = (HiddenColumns) alandcolsel[1];
148           }
149           else
150           {
151             al = new FormatAdapter().readFile(result.getAligfile(),
152                     DataSourceType.PASTE, format);
153             sqs = new SequenceI[al.getHeight()];
154
155             for (int i = 0, j = al.getHeight(); i < j; i++)
156             {
157               sqs[i] = al.getSequenceAt(i);
158             }
159             if (!SeqsetUtils.deuniquify(SequenceInfo, sqs))
160             {
161               throw (new Exception(
162                       MessageManager
163                               .getString("exception.couldnt_recover_sequence_properties_for_alignment")));
164             }
165           }
166           FirstSeq = 0;
167           if (currentView.getDataset() != null)
168           {
169             al.setDataset(currentView.getDataset());
170
171           }
172           else
173           {
174             al.setDataset(null);
175           }
176           JnetAnnotationMaker.add_annotation(prediction, al,
177                   FirstSeq, false, predMap);
178
179         }
180         else
181         {
182           throw (new Exception(MessageManager.formatMessage(
183                   "exception.unknown_format_for_file", new String[] { "",
184                       result.getAligfile() })));
185         }
186       }
187       else
188       {
189         al = new Alignment(preds);
190         FirstSeq = prediction.getQuerySeqPosition();
191         if (predMap != null)
192         {
193           char gc = getGapChar();
194           SequenceI[] sqs = (SequenceI[]) input
195                   .getAlignmentAndHiddenColumns(gc)[0];
196           if (this.msaIndex >= sqs.length)
197           {
198             throw new Error(
199                     MessageManager
200                             .getString("error.implementation_error_invalid_msa_index_for_job"));
201           }
202
203           // ///
204           // Uses RemoveGapsCommand
205           // ///
206           new jalview.commands.RemoveGapsCommand(
207                   MessageManager.getString("label.remove_gaps"),
208                   new SequenceI[] { sqs[msaIndex] }, currentView);
209
210           SequenceI profileseq = al.getSequenceAt(FirstSeq);
211           profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
212         }
213
214         if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
215                 al.getSequenceAt(FirstSeq), SequenceInfo))
216         {
217           throw (new Exception(
218                   MessageManager
219                           .getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
220         }
221         else
222         {
223           if (currentView.getDataset() != null)
224           {
225             al.setDataset(currentView.getDataset());
226
227           }
228           else
229           {
230             al.setDataset(null);
231           }
232           jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
233                   FirstSeq, true, predMap);
234           SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
235           alignToProfileSeq(al, profileseq);
236           if (predMap != null)
237           {
238             // Adjust input view for gaps
239             // propagate insertions into profile
240             alhidden = HiddenColumns.propagateInsertions(profileseq, al,
241                     input);
242           }
243         }
244       }
245       // transfer to dataset
246       for (AlignmentAnnotation alant : al.getAlignmentAnnotation())
247       {
248         if (alant.sequenceRef != null)
249         {
250           replaceAnnotationOnAlignmentWith(alant, alant.label,
251                   "jalview.jws1.Jpred" + (this.msa == null ? "" : "MSA"),
252                   alant.sequenceRef);
253         }
254       }
255       return new Object[] { al, alhidden }; // , FirstSeq, noMsa};
256     }
257
258     /**
259      * copied from JabawsCalcWorker
260      * 
261      * @param newAnnot
262      * @param typeName
263      * @param calcId
264      * @param aSeq
265      */
266     protected void replaceAnnotationOnAlignmentWith(
267             AlignmentAnnotation newAnnot, String typeName, String calcId,
268             SequenceI aSeq)
269     {
270       SequenceI dsseq = aSeq.getDatasetSequence();
271       while (dsseq.getDatasetSequence() != null)
272       {
273         dsseq = dsseq.getDatasetSequence();
274       }
275       // look for same annotation on dataset and lift this one over
276       List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
277               calcId, typeName);
278       if (dsan != null && dsan.size() > 0)
279       {
280         for (AlignmentAnnotation dssan : dsan)
281         {
282           dsseq.removeAlignmentAnnotation(dssan);
283         }
284       }
285       AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
286       dsseq.addAlignmentAnnotation(dssan);
287       dssan.adjustForAlignment();
288     }
289
290     /**
291      * Given an alignment where all other sequences except profileseq are
292      * aligned to the ungapped profileseq, insert gaps in the other sequences to
293      * realign them with the residues in profileseq
294      * 
295      * @param al
296      * @param profileseq
297      */
298     private void alignToProfileSeq(AlignmentI al, SequenceI profileseq)
299     {
300       char gc = al.getGapCharacter();
301       int[] gapMap = profileseq.gapMap();
302       // insert gaps into profile
303       for (int lp = 0, r = 0; r < gapMap.length; r++)
304       {
305         if (gapMap[r] - lp > 1)
306         {
307           StringBuffer sb = new StringBuffer();
308           for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
309           {
310             sb.append(gc);
311           }
312           for (int s = 1, ns = al.getHeight(); s < ns; s++)
313           {
314             String sq = al.getSequenceAt(s).getSequenceAsString();
315             int diff = gapMap[r] - sq.length();
316             if (diff > 0)
317             {
318               // pad gaps
319               sq = sq + sb;
320               while ((diff = gapMap[r] - sq.length()) > 0)
321               {
322                 sq = sq
323                         + ((diff >= sb.length()) ? sb.toString() : sb
324                                 .substring(0, diff));
325               }
326               al.getSequenceAt(s).setSequence(sq);
327             }
328             else
329             {
330               al.getSequenceAt(s).setSequence(
331                       sq.substring(0, gapMap[r]) + sb.toString()
332                               + sq.substring(gapMap[r]));
333             }
334           }
335         }
336         lp = gapMap[r];
337       }
338     }
339
340     public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
341     {
342       super();
343       this.predMap = delMap;
344       String sq = AlignSeq.extractGaps(Comparison.GapChars,
345               seq.getSequenceAsString());
346       if (sq.length() >= 20)
347       {
348         this.SequenceInfo = SequenceInfo;
349         sequence = new vamsas.objects.simple.Sequence();
350         sequence.setId(seq.getName());
351         sequence.setSeq(sq);
352       }
353       else
354       {
355         errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
356       }
357     }
358
359     public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
360     {
361       this(SequenceInfo, msf[0], delMap);
362       if (sequence != null)
363       {
364         if (msf.length > 1)
365         {
366           msa = new vamsas.objects.simple.Msfalignment();
367           PileUpfile pileup = new PileUpfile();
368           msa.setMsf(pileup.print(msf, true));
369         }
370       }
371     }
372
373     String errorMessage = "";
374
375     public String getValidationMessages()
376     {
377       return errorMessage + "\n";
378     }
379   }
380
381   ext.vamsas.Jpred server;
382
383   String altitle = "";
384
385   JPredThread(WebserviceInfo wsinfo, String altitle,
386           ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
387           AlignFrame alframe)
388   {
389     super(alframe, wsinfo, alview, wsurl);
390     this.altitle = altitle;
391     this.server = server;
392   }
393
394   JPredThread(WebserviceInfo wsinfo, String altitle,
395           ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
396           SequenceI seq, int[] delMap, AlignmentView alview,
397           AlignFrame alframe)
398   {
399     this(wsinfo, altitle, server, wsurl, alview, alframe);
400     JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
401     if (job.hasValidInput())
402     {
403       OutputHeader = wsInfo.getProgressText();
404       jobs = new WSJob[] { job };
405       job.setJobnum(0);
406     }
407     else
408     {
409       wsInfo.appendProgressText(job.getValidationMessages());
410     }
411   }
412
413   JPredThread(WebserviceInfo wsinfo, String altitle,
414           ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
415           int[] delMap, AlignmentView alview, AlignFrame alframe,
416           String wsurl)
417   {
418     this(wsinfo, altitle, server, wsurl, alview, alframe);
419     JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
420     if (job.hasValidInput())
421     {
422       jobs = new WSJob[] { job };
423       OutputHeader = wsInfo.getProgressText();
424       job.setJobnum(0);
425     }
426     else
427     {
428       wsInfo.appendProgressText(job.getValidationMessages());
429     }
430   }
431
432   @Override
433   public void StartJob(AWsJob j)
434   {
435     if (!(j instanceof JPredJob))
436     {
437       throw new Error(MessageManager.formatMessage(
438               "error.implementation_error_startjob_called",
439               new String[] { j.getClass().toString() }));
440     }
441     try
442     {
443       JPredJob job = (JPredJob) j;
444       if (job.msa != null)
445       {
446         job.setJobId(server.predictOnMsa(job.msa));
447       }
448       else if (job.sequence != null)
449       {
450         job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
451         // "/jobs/www-jpred/jp_Yatat29";//
452       }
453
454       if (job.getJobId() != null)
455       {
456         if (job.getJobId().startsWith("Broken"))
457         {
458           job.result = new JpredResult();
459           job.result.setInvalid(true);
460           job.result.setStatus(MessageManager.formatMessage(
461                   "label.submission_params", new String[] { job.getJobId()
462                           .toString() }));
463           throw new Exception(job.getJobId());
464         }
465         else
466         {
467           job.setSubmitted(true);
468           job.setSubjobComplete(false);
469           Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
470         }
471       }
472       else
473       {
474         throw new Exception(
475                 MessageManager
476                         .getString("exception.server_timeout_try_later"));
477       }
478     } catch (Exception e)
479     {
480       // kill the whole job.
481       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
482       if (e.getMessage().indexOf("Exception") > -1)
483       {
484         wsInfo.setStatus(j.getJobnum(),
485                 WebserviceInfo.STATE_STOPPED_SERVERERROR);
486         wsInfo.setProgressText(
487                 j.getJobnum(),
488                 "Failed to submit the prediction. (Just close the window)\n"
489                         + "It is most likely that there is a problem with the server.\n");
490         System.err
491                 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
492                         + e.getMessage() + "\n");
493
494         jalview.bin.Cache.log.warn("Server Exception", e);
495       }
496       else
497       {
498         wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
499         // JBPNote - this could be a popup informing the user of the problem.
500         wsInfo.appendProgressText(j.getJobnum(), MessageManager
501                 .formatMessage(
502                         "info.failed_to_submit_prediction",
503                         new String[] { e.getMessage(),
504                             wsInfo.getProgressText() }));
505
506         jalview.bin.Cache.log.debug(
507                 "Failed Submission of job " + j.getJobnum(), e);
508
509       }
510       j.setAllowedServerExceptions(-1);
511       j.setSubjobComplete(true);
512     }
513   }
514
515   @Override
516   public void parseResult()
517   {
518     int results = 0; // number of result sets received
519     JobStateSummary finalState = new JobStateSummary();
520     try
521     {
522       for (int j = 0; j < jobs.length; j++)
523       {
524         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
525         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
526                 && jobs[j].hasResults())
527         {
528           results++;
529         }
530       }
531     } catch (Exception ex)
532     {
533
534       Cache.log.error("Unexpected exception when processing results for "
535               + altitle, ex);
536       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
537     }
538     if (results > 0)
539     {
540       wsInfo.showResultsNewFrame
541               .addActionListener(new java.awt.event.ActionListener()
542               {
543                 @Override
544                 public void actionPerformed(java.awt.event.ActionEvent evt)
545                 {
546                   displayResults(true);
547                 }
548               });
549       wsInfo.mergeResults
550               .addActionListener(new java.awt.event.ActionListener()
551               {
552                 @Override
553                 public void actionPerformed(java.awt.event.ActionEvent evt)
554                 {
555                   displayResults(false);
556                 }
557               });
558       wsInfo.setResultsReady();
559     }
560     else
561     {
562       wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
563       wsInfo.appendInfoText("No jobs ran.");
564       wsInfo.setFinishedNoResults();
565     }
566   }
567
568   void displayResults(boolean newWindow)
569   {
570     // TODO: cope with multiple subjobs.
571     if (jobs != null)
572     {
573       Object[] res = null;
574       boolean msa = false;
575       for (int jn = 0; jn < jobs.length; jn++)
576       {
577         Object[] jobres = null;
578         JPredJob j = (JPredJob) jobs[jn];
579
580         if (j.hasResults())
581         {
582           // hack - we only deal with all single seuqence predictions or all
583           // profile predictions
584           msa = (j.msa != null) ? true : msa;
585           try
586           {
587             jalview.bin.Cache.log.debug("Parsing output of job " + jn);
588             jobres = j.getResultSet();
589             jalview.bin.Cache.log.debug("Finished parsing output.");
590             if (jobs.length == 1)
591             {
592               res = jobres;
593             }
594             else
595             {
596               // do merge with other job results
597               throw new Error(
598                       MessageManager
599                               .getString("error.multiple_jnet_subjob_merge_not_implemented"));
600             }
601           } catch (Exception e)
602           {
603             jalview.bin.Cache.log.error(
604                     "JNet Client: JPred Annotation Parse Error", e);
605             wsInfo.setStatus(j.getJobnum(),
606                     WebserviceInfo.STATE_STOPPED_ERROR);
607             wsInfo.appendProgressText(j.getJobnum(), MessageManager
608                     .formatMessage("info.invalid_jnet_job_result_data",
609                             new String[] { OutputHeader.toString(),
610                                 j.result.getStatus(), e.getMessage() }));
611             j.result.setBroken(true);
612           }
613         }
614       }
615
616       if (res != null)
617       {
618         if (newWindow)
619         {
620           AlignFrame af;
621           ((AlignmentI) res[0]).setSeqrep(((AlignmentI) res[0])
622                   .getSequenceAt(0));
623           if (input == null)
624           {
625             if (res[1] != null)
626             {
627               af = new AlignFrame((Alignment) res[0],
628                       (HiddenColumns) res[1], AlignFrame.DEFAULT_WIDTH,
629                       AlignFrame.DEFAULT_HEIGHT);
630             }
631             else
632             {
633               af = new AlignFrame((Alignment) res[0],
634                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
635             }
636           }
637           else
638           {
639             /*
640              * java.lang.Object[] alandcolsel =
641              * input.getAlignmentAndColumnSelection
642              * (alignFrame.getViewport().getGapCharacter()); if
643              * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
644              * if (msa) { throw new Error("Implementation Error! ColumnSelection
645              * from input alignment will not map to result alignment!"); } } if
646              * (!msa) { // update hidden regions to account for loss of gaps in
647              * profile. - if any // gapMap returns insert list, interpreted as
648              * delete list by pruneDeletions //((ColumnSelection)
649              * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
650              * alandcolsel[0])[0].gapMap())); }
651              */
652
653             af = new AlignFrame((Alignment) res[0],
654  (HiddenColumns) res[1],
655                     AlignFrame.DEFAULT_WIDTH,
656                     AlignFrame.DEFAULT_HEIGHT);
657           }
658           Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
659                   AlignFrame.DEFAULT_HEIGHT);
660         }
661         else
662         {
663           Cache.log.info("Append results onto existing alignment.");
664         }
665       }
666     }
667   }
668
669   @Override
670   public void pollJob(AWsJob job) throws Exception
671   {
672     ((JPredJob) job).result = server.getresult(job.getJobId());
673   }
674
675   @Override
676   public boolean isCancellable()
677   {
678     return false;
679   }
680
681   @Override
682   public void cancelJob()
683   {
684     throw new Error(MessageManager.getString("error.implementation_error"));
685   }
686
687   @Override
688   public boolean canMergeResults()
689   {
690     return false;
691   }
692
693 }