JAL-1355
[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           al.setDataset(null);
148
149           jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
150                   FirstSeq, false, predMap);
151
152         }
153         else
154         {
155           throw (new Exception(MessageManager.formatMessage("exception.unknown_format_for_file", new String[]{format,result.getAligfile()})));
156         }
157       }
158       else
159       {
160         al = new Alignment(preds);
161         FirstSeq = prediction.getQuerySeqPosition();
162         if (predMap != null)
163         {
164           char gc = getGapChar();
165           SequenceI[] sqs = (SequenceI[]) ((java.lang.Object[]) input
166                   .getAlignmentAndColumnSelection(gc))[0];
167           if (this.msaIndex >= sqs.length)
168           {
169             throw new Error(MessageManager.getString("error.implementation_error_invalid_msa_index_for_job"));
170           }
171
172           // ///
173           // Uses RemoveGapsCommand
174           // ///
175           new jalview.commands.RemoveGapsCommand(MessageManager.getString("label.remove_gaps"),
176                   new SequenceI[]
177                   { sqs[msaIndex] }, currentView);
178
179           SequenceI profileseq = al.getSequenceAt(FirstSeq);
180           profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
181         }
182
183         if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
184                 al.getSequenceAt(FirstSeq), SequenceInfo))
185         {
186           throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
187         }
188         else
189         {
190           al.setDataset(null);
191           jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
192                   FirstSeq, true, predMap);
193           SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
194           alignToProfileSeq(al, profileseq);
195           if (predMap != null)
196           {
197             // Adjust input view for gaps
198             // propagate insertions into profile
199             alcsel = ColumnSelection.propagateInsertions(profileseq, al,
200                     input);
201           }
202         }
203       }
204       return new Object[]
205       { al, alcsel }; // , FirstSeq, noMsa};
206     }
207
208     /**
209      * Given an alignment where all other sequences except profileseq are
210      * aligned to the ungapped profileseq, insert gaps in the other sequences to
211      * realign them with the residues in profileseq
212      * 
213      * @param al
214      * @param profileseq
215      */
216     private void alignToProfileSeq(Alignment al, SequenceI profileseq)
217     {
218       char gc = al.getGapCharacter();
219       int[] gapMap = profileseq.gapMap();
220       // insert gaps into profile
221       for (int lp = 0, r = 0; r < gapMap.length; r++)
222       {
223         if (gapMap[r] - lp > 1)
224         {
225           StringBuffer sb = new StringBuffer();
226           for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
227           {
228             sb.append(gc);
229           }
230           for (int s = 1, ns = al.getHeight(); s < ns; s++)
231           {
232             String sq = al.getSequenceAt(s).getSequenceAsString();
233             int diff = gapMap[r] - sq.length();
234             if (diff > 0)
235             {
236               // pad gaps
237               sq = sq + sb;
238               while ((diff = gapMap[r] - sq.length()) > 0)
239               {
240                 sq = sq
241                         + ((diff >= sb.length()) ? sb.toString() : sb
242                                 .substring(0, diff));
243               }
244               al.getSequenceAt(s).setSequence(sq);
245             }
246             else
247             {
248               al.getSequenceAt(s).setSequence(
249                       sq.substring(0, gapMap[r]) + sb.toString()
250                               + sq.substring(gapMap[r]));
251             }
252           }
253         }
254         lp = gapMap[r];
255       }
256     }
257
258     public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
259     {
260       super();
261       this.predMap = delMap;
262       String sq = AlignSeq.extractGaps(Comparison.GapChars,
263               seq.getSequenceAsString());
264       if (sq.length() >= 20)
265       {
266         this.SequenceInfo = SequenceInfo;
267         sequence = new vamsas.objects.simple.Sequence();
268         sequence.setId(seq.getName());
269         sequence.setSeq(sq);
270       }
271       else
272       {
273         errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
274       }
275     }
276
277     public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
278     {
279       this(SequenceInfo, msf[0], delMap);
280       if (sequence != null)
281       {
282         if (msf.length > 1)
283         {
284           msa = new vamsas.objects.simple.Msfalignment();
285           jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
286           msa.setMsf(pileup.print(msf));
287         }
288       }
289     }
290
291     String errorMessage = "";
292
293     public String getValidationMessages()
294     {
295       return errorMessage + "\n";
296     }
297   }
298
299   ext.vamsas.Jpred server;
300
301   String altitle = "";
302
303   JPredThread(WebserviceInfo wsinfo, String altitle,
304           ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
305           AlignFrame alframe)
306   {
307     super(alframe, wsinfo, alview, wsurl);
308     this.altitle = altitle;
309     this.server = server;
310   }
311
312   JPredThread(WebserviceInfo wsinfo, String altitle,
313           ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
314           SequenceI seq, int[] delMap, AlignmentView alview,
315           AlignFrame alframe)
316   {
317     this(wsinfo, altitle, server, wsurl, alview, alframe);
318     JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
319     if (job.hasValidInput())
320     {
321       OutputHeader = wsInfo.getProgressText();
322       jobs = new WSJob[]
323       { job };
324       job.setJobnum(0);
325     }
326     else
327     {
328       wsInfo.appendProgressText(job.getValidationMessages());
329     }
330   }
331
332   JPredThread(WebserviceInfo wsinfo, String altitle,
333           ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
334           int[] delMap, AlignmentView alview, AlignFrame alframe,
335           String wsurl)
336   {
337     this(wsinfo, altitle, server, wsurl, alview, alframe);
338     JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
339     if (job.hasValidInput())
340     {
341       jobs = new WSJob[]
342       { job };
343       OutputHeader = wsInfo.getProgressText();
344       job.setJobnum(0);
345     }
346     else
347     {
348       wsInfo.appendProgressText(job.getValidationMessages());
349     }
350   }
351
352   public void StartJob(AWsJob j)
353   {
354     if (!(j instanceof JPredJob))
355     {
356       throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
357     }
358     try
359     {
360       JPredJob job = (JPredJob) j;
361       if (job.msa != null)
362       {
363         job.setJobId(server.predictOnMsa(job.msa));
364       }
365       else if (job.sequence != null)
366       {
367         job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
368         // "/jobs/www-jpred/jp_Yatat29";//
369       }
370
371       if (job.getJobId() != null)
372       {
373         if (job.getJobId().startsWith("Broken"))
374         {
375           job.result = (vamsas.objects.simple.Result) new JpredResult();
376           job.result.setInvalid(true);
377           job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
378           throw new Exception(job.getJobId());
379         }
380         else
381         {
382           job.setSubmitted(true);
383           job.setSubjobComplete(false);
384           Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
385         }
386       }
387       else
388       {
389         throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
390       }
391     } catch (Exception e)
392     {
393       // kill the whole job.
394       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
395       if (e.getMessage().indexOf("Exception") > -1)
396       {
397         wsInfo.setStatus(j.getJobnum(),
398                 WebserviceInfo.STATE_STOPPED_SERVERERROR);
399         wsInfo.setProgressText(
400                 j.getJobnum(),
401                 "Failed to submit the prediction. (Just close the window)\n"
402                         + "It is most likely that there is a problem with the server.\n");
403         System.err
404                 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
405                         + e.getMessage() + "\n");
406
407         jalview.bin.Cache.log.warn("Server Exception", e);
408       }
409       else
410       {
411         wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
412         // JBPNote - this could be a popup informing the user of the problem.
413         wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
414
415         jalview.bin.Cache.log.debug(
416                 "Failed Submission of job " + j.getJobnum(), e);
417
418       }
419       j.setAllowedServerExceptions(-1);
420       j.setSubjobComplete(true);
421     }
422   }
423
424   public void parseResult()
425   {
426     int results = 0; // number of result sets received
427     JobStateSummary finalState = new JobStateSummary();
428     try
429     {
430       for (int j = 0; j < jobs.length; j++)
431       {
432         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
433         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
434                 && jobs[j].hasResults())
435         {
436           results++;
437         }
438       }
439     } catch (Exception ex)
440     {
441
442       Cache.log.error("Unexpected exception when processing results for "
443               + altitle, ex);
444       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
445     }
446     if (results > 0)
447     {
448       wsInfo.showResultsNewFrame
449               .addActionListener(new java.awt.event.ActionListener()
450               {
451                 public void actionPerformed(java.awt.event.ActionEvent evt)
452                 {
453                   displayResults(true);
454                 }
455               });
456       wsInfo.mergeResults
457               .addActionListener(new java.awt.event.ActionListener()
458               {
459                 public void actionPerformed(java.awt.event.ActionEvent evt)
460                 {
461                   displayResults(false);
462                 }
463               });
464       wsInfo.setResultsReady();
465     }
466     else
467     {
468       wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
469       wsInfo.appendInfoText("No jobs ran.");
470       wsInfo.setFinishedNoResults();
471     }
472   }
473
474   void displayResults(boolean newWindow)
475   {
476     // TODO: cope with multiple subjobs.
477     if (jobs != null)
478     {
479       Object[] res = null;
480       boolean msa = false;
481       for (int jn = 0; jn < jobs.length; jn++)
482       {
483         Object[] jobres = null;
484         JPredJob j = (JPredJob) jobs[jn];
485
486         if (j.hasResults())
487         {
488           // hack - we only deal with all single seuqence predictions or all
489           // profile predictions
490           msa = (j.msa != null) ? true : msa;
491           try
492           {
493             jalview.bin.Cache.log.debug("Parsing output of job " + jn);
494             jobres = j.getResultSet();
495             jalview.bin.Cache.log.debug("Finished parsing output.");
496             if (jobs.length == 1)
497             {
498               res = jobres;
499             }
500             else
501             {
502               // do merge with other job results
503               throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
504             }
505           } catch (Exception e)
506           {
507             jalview.bin.Cache.log.error(
508                     "JNet Client: JPred Annotation Parse Error", e);
509             wsInfo.setStatus(j.getJobnum(),
510                     WebserviceInfo.STATE_STOPPED_ERROR);
511             wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
512             j.result.setBroken(true);
513           }
514         }
515       }
516
517       if (res != null)
518       {
519         if (newWindow)
520         {
521           AlignFrame af;
522           if (input == null)
523           {
524             if (res[1] != null)
525             {
526               af = new AlignFrame((Alignment) res[0],
527                       (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
528                       AlignFrame.DEFAULT_HEIGHT);
529             }
530             else
531             {
532               af = new AlignFrame((Alignment) res[0],
533                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
534             }
535           }
536           else
537           {
538             /*
539              * java.lang.Object[] alandcolsel =
540              * input.getAlignmentAndColumnSelection
541              * (alignFrame.getViewport().getGapCharacter()); if
542              * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
543              * if (msa) { throw new Error("Implementation Error! ColumnSelection
544              * from input alignment will not map to result alignment!"); } } if
545              * (!msa) { // update hidden regions to account for loss of gaps in
546              * profile. - if any // gapMap returns insert list, interpreted as
547              * delete list by pruneDeletions //((ColumnSelection)
548              * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
549              * alandcolsel[0])[0].gapMap())); }
550              */
551
552             af = new AlignFrame((Alignment) res[0],
553                     (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
554                     AlignFrame.DEFAULT_HEIGHT);
555           }
556           Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
557                   AlignFrame.DEFAULT_HEIGHT);
558         }
559         else
560         {
561           Cache.log.info("Append results onto existing alignment.");
562         }
563       }
564     }
565   }
566
567   public void pollJob(AWsJob job) throws Exception
568   {
569     ((JPredJob) job).result = server.getresult(job.getJobId());
570   }
571
572   public boolean isCancellable()
573   {
574     return false;
575   }
576
577   public void cancelJob()
578   {
579     throw new Error(MessageManager.getString("error.implementation_error"));
580   }
581
582   public boolean canMergeResults()
583   {
584     return false;
585   }
586
587 }