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