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