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