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