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