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