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