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