JAL-3899 Update usages of uniquify and deuniquify.
[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.Cache;
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       Cache.log.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       Cache.log.debug("Got prediction profile.");
131
132       if ((this.msa != null) && (result.getAligfile() != null))
133       {
134         Cache.log.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           Cache.log.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         jalview.bin.Cache.log.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         jalview.bin.Cache.log
501                 .debug("Failed Submission of job " + j.getJobnum(), e);
502
503       }
504       j.setAllowedServerExceptions(-1);
505       j.setSubjobComplete(true);
506     }
507   }
508
509   @Override
510   public void parseResult()
511   {
512     int results = 0; // number of result sets received
513     JobStateSummary finalState = new JobStateSummary();
514     try
515     {
516       for (int j = 0; j < jobs.length; j++)
517       {
518         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
519         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
520                 && jobs[j].hasResults())
521         {
522           results++;
523         }
524       }
525     } catch (Exception ex)
526     {
527
528       Cache.log.error(
529               "Unexpected exception when processing results for " + altitle,
530               ex);
531       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
532     }
533     if (results > 0)
534     {
535       wsInfo.showResultsNewFrame
536               .addActionListener(new java.awt.event.ActionListener()
537               {
538                 @Override
539                 public void actionPerformed(java.awt.event.ActionEvent evt)
540                 {
541                   displayResults(true);
542                 }
543               });
544       wsInfo.mergeResults
545               .addActionListener(new java.awt.event.ActionListener()
546               {
547                 @Override
548                 public void actionPerformed(java.awt.event.ActionEvent evt)
549                 {
550                   displayResults(false);
551                 }
552               });
553       wsInfo.setResultsReady();
554     }
555     else
556     {
557       wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
558       wsInfo.appendInfoText("No jobs ran.");
559       wsInfo.setFinishedNoResults();
560     }
561   }
562
563   void displayResults(boolean newWindow)
564   {
565     // TODO: cope with multiple subjobs.
566     if (jobs != null)
567     {
568       Object[] res = null;
569       boolean msa = false;
570       for (int jn = 0; jn < jobs.length; jn++)
571       {
572         Object[] jobres = null;
573         JPredJob j = (JPredJob) jobs[jn];
574
575         if (j.hasResults())
576         {
577           // hack - we only deal with all single seuqence predictions or all
578           // profile predictions
579           msa = (j.msa != null) ? true : msa;
580           try
581           {
582             jalview.bin.Cache.log.debug("Parsing output of job " + jn);
583             jobres = j.getResultSet();
584             jalview.bin.Cache.log.debug("Finished parsing output.");
585             if (jobs.length == 1)
586             {
587               res = jobres;
588             }
589             else
590             {
591               // do merge with other job results
592               throw new Error(MessageManager.getString(
593                       "error.multiple_jnet_subjob_merge_not_implemented"));
594             }
595           } catch (Exception e)
596           {
597             jalview.bin.Cache.log
598                     .error("JNet Client: JPred Annotation Parse Error", e);
599             wsInfo.setStatus(j.getJobnum(),
600                     WebserviceInfo.STATE_STOPPED_ERROR);
601             wsInfo.appendProgressText(j.getJobnum(),
602                     MessageManager.formatMessage(
603                             "info.invalid_jnet_job_result_data",
604                             new String[]
605                             { OutputHeader.toString(), j.result.getStatus(),
606                                 e.getMessage() }));
607             j.result.setBroken(true);
608           }
609         }
610       }
611
612       if (res != null)
613       {
614         if (newWindow)
615         {
616           AlignFrame af;
617           ((AlignmentI) res[0])
618                   .setSeqrep(((AlignmentI) res[0]).getSequenceAt(0));
619           if (input == null)
620           {
621             if (res[1] != null)
622             {
623               af = new AlignFrame((Alignment) res[0],
624                       (HiddenColumns) res[1], AlignFrame.DEFAULT_WIDTH,
625                       AlignFrame.DEFAULT_HEIGHT);
626             }
627             else
628             {
629               af = new AlignFrame((Alignment) res[0],
630                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
631             }
632           }
633           else
634           {
635             /*
636              * java.lang.Object[] alandcolsel =
637              * input.getAlignmentAndColumnSelection
638              * (alignFrame.getViewport().getGapCharacter()); if
639              * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
640              * if (msa) { throw new Error("Implementation Error! ColumnSelection
641              * from input alignment will not map to result alignment!"); } } if
642              * (!msa) { // update hidden regions to account for loss of gaps in
643              * profile. - if any // gapMap returns insert list, interpreted as
644              * delete list by pruneDeletions //((ColumnSelection)
645              * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
646              * alandcolsel[0])[0].gapMap())); }
647              */
648
649             af = new AlignFrame((Alignment) res[0], (HiddenColumns) res[1],
650                     AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
651           }
652           Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
653                   AlignFrame.DEFAULT_HEIGHT);
654         }
655         else
656         {
657           Cache.log.info("Append results onto existing alignment.");
658         }
659       }
660     }
661   }
662
663   @Override
664   public void pollJob(AWsJob job) throws Exception
665   {
666     ((JPredJob) job).result = server.getresult(job.getJobId());
667   }
668
669   @Override
670   public boolean isCancellable()
671   {
672     return false;
673   }
674
675   @Override
676   public void cancelJob()
677   {
678     throw new Error(MessageManager.getString("error.implementation_error"));
679   }
680
681   @Override
682   public boolean canMergeResults()
683   {
684     return false;
685   }
686
687 }