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