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