JAL-1925 update source version in license
[jalview.git] / src / jalview / ws / jws1 / SeqSearchWSThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9.0b2)
3  * Copyright (C) 2015 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.bin.Cache;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentView;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.Desktop;
30 import jalview.gui.WebserviceInfo;
31 import jalview.io.NewickFile;
32 import jalview.util.MessageManager;
33 import jalview.ws.AWsJob;
34 import jalview.ws.JobStateSummary;
35 import jalview.ws.WSClientI;
36
37 import java.util.HashMap;
38 import java.util.Hashtable;
39 import java.util.Map;
40 import java.util.Vector;
41
42 import vamsas.objects.simple.MsaResult;
43 import vamsas.objects.simple.SeqSearchResult;
44
45 class SeqSearchWSThread extends JWS1Thread implements WSClientI
46 {
47   String dbs = null;
48
49   boolean profile = false;
50
51   class SeqSearchWSJob extends WSJob
52   {
53     // hold special input for this
54     vamsas.objects.simple.SequenceSet seqs = new vamsas.objects.simple.SequenceSet();
55
56     /**
57      * MsaWSJob
58      * 
59      * @param jobNum
60      *          int
61      * @param jobId
62      *          String
63      */
64     public SeqSearchWSJob(int jobNum, SequenceI[] inSeqs)
65     {
66       this.jobnum = jobNum;
67       if (!prepareInput(inSeqs, 2))
68       {
69         submitted = true;
70         subjobComplete = true;
71         result = new MsaResult();
72         result.setFinished(true);
73         result.setStatus(MessageManager.getString("label.job_never_ran"));
74       }
75
76     }
77
78     Hashtable SeqNames = new Hashtable();
79
80     Vector emptySeqs = new Vector();
81
82     /**
83      * prepare input sequences for service
84      * 
85      * @param seqs
86      *          jalview sequences to be prepared
87      * @param minlen
88      *          minimum number of residues required for this MsaWS service
89      * @return true if seqs contains sequences to be submitted to service.
90      */
91     private boolean prepareInput(SequenceI[] seqs, int minlen)
92     {
93       int nseqs = 0;
94       if (minlen < 0)
95       {
96         throw new Error(
97                 MessageManager
98                         .getString("error.implementation_error_minlen_must_be_greater_zero"));
99       }
100       for (int i = 0; i < seqs.length; i++)
101       {
102         if (seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
103         {
104           nseqs++;
105         }
106       }
107       boolean valid = nseqs >= 1; // need at least one sequence for valid input
108       // TODO: generalise
109       vamsas.objects.simple.Sequence[] seqarray = (valid) ? new vamsas.objects.simple.Sequence[nseqs]
110               : null;
111       boolean submitGaps = (nseqs == 1) ? false : true; // profile is submitted
112       // with gaps
113       for (int i = 0, n = 0; i < seqs.length; i++)
114       {
115
116         String newname = jalview.analysis.SeqsetUtils.unique_name(i); // same
117         // for
118         // any
119         // subjob
120         SeqNames.put(newname,
121                 jalview.analysis.SeqsetUtils.SeqCharacterHash(seqs[i]));
122         if (valid && seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
123         {
124           seqarray[n] = new vamsas.objects.simple.Sequence();
125           seqarray[n].setId(newname);
126           seqarray[n++].setSeq((submitGaps) ? seqs[i].getSequenceAsString()
127                   : AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
128                           seqs[i].getSequenceAsString()));
129         }
130         else
131         {
132           String empty = null;
133           if (seqs[i].getEnd() >= seqs[i].getStart())
134           {
135             empty = (submitGaps) ? seqs[i].getSequenceAsString() : AlignSeq
136                     .extractGaps(jalview.util.Comparison.GapChars,
137                             seqs[i].getSequenceAsString());
138           }
139           emptySeqs.add(new String[] { newname, empty });
140         }
141       }
142       if (submitGaps)
143       {
144         // almost certainly have to remove gapped columns here
145       }
146       this.seqs = new vamsas.objects.simple.SequenceSet();
147       this.seqs.setSeqs(seqarray);
148       return valid;
149     }
150
151     /**
152      * 
153      * @return true if getAlignment will return a valid alignment result.
154      */
155     public boolean hasResults()
156     {
157       if (subjobComplete
158               && result != null
159               && result.isFinished()
160               && ((SeqSearchResult) result).getAlignment() != null
161               && ((SeqSearchResult) result).getAlignment().getSeqs() != null)
162       {
163         return true;
164       }
165       return false;
166     }
167
168     /**
169      * return sequence search results for display
170      * 
171      * @return null or { Alignment(+features and annotation), NewickFile)}
172      */
173     public Object[] getAlignment(Alignment dataset, Map featureColours)
174     {
175
176       if (result != null && result.isFinished())
177       {
178         SequenceI[] alseqs = null;
179         // char alseq_gapchar = '-';
180         // int alseq_l = 0;
181         if (((SeqSearchResult) result).getAlignment() != null)
182         {
183           alseqs = getVamsasAlignment(((SeqSearchResult) result)
184                   .getAlignment());
185           // alseq_gapchar = ( (SeqSearchResult)
186           // result).getAlignment().getGapchar().charAt(0);
187           // alseq_l = alseqs.length;
188         }
189         /**
190          * what has to be done. 1 - annotate returned alignment with annotation
191          * file and sequence features file, and associate any tree-nodes. 2.
192          * connect alignment back to any associated dataset: 2.a. deuniquify
193          * recovers sequence information - but additionally, relocations must be
194          * made from the returned aligned sequence back to the dataset.
195          */
196         // construct annotated alignment as it would be done by the jalview
197         // applet
198         jalview.datamodel.Alignment al = new Alignment(alseqs);
199         // al.setDataset(dataset);
200         // make dataset
201         String inFile = null;
202         try
203         {
204           inFile = ((SeqSearchResult) result).getAnnotation();
205           if (inFile != null && inFile.length() > 0)
206           {
207             new jalview.io.AnnotationFile().readAnnotationFile(al, inFile,
208                     jalview.io.AppletFormatAdapter.PASTE);
209           }
210         } catch (Exception e)
211         {
212           System.err
213                   .println("Failed to parse the annotation file associated with the alignment.");
214           System.err.println(">>>EOF" + inFile + "\n<<<EOF\n");
215           e.printStackTrace(System.err);
216         }
217
218         try
219         {
220           inFile = ((SeqSearchResult) result).getFeatures();
221           if (inFile != null && inFile.length() > 0)
222           {
223             jalview.io.FeaturesFile ff = new jalview.io.FeaturesFile(
224                     inFile, jalview.io.AppletFormatAdapter.PASTE);
225             ff.parse(al, featureColours, false);
226           }
227         } catch (Exception e)
228         {
229           System.err
230                   .println("Failed to parse the Features file associated with the alignment.");
231           System.err.println(">>>EOF" + inFile + "\n<<<EOF\n");
232           e.printStackTrace(System.err);
233         }
234         jalview.io.NewickFile nf = null;
235         try
236         {
237           inFile = ((SeqSearchResult) result).getNewickTree();
238           if (inFile != null && inFile.length() > 0)
239           {
240             nf = new jalview.io.NewickFile(inFile,
241                     jalview.io.AppletFormatAdapter.PASTE);
242             if (!nf.isValid())
243             {
244               nf.close();
245               nf = null;
246             }
247           }
248         } catch (Exception e)
249         {
250           System.err
251                   .println("Failed to parse the treeFile associated with the alignment.");
252           System.err.println(">>>EOF" + inFile + "\n<<<EOF\n");
253           e.printStackTrace(System.err);
254         }
255
256         /*
257          * TODO: housekeeping w.r.t. recovery of dataset and annotation
258          * references for input sequences, and then dataset sequence creation
259          * for new sequences retrieved from service // finally, attempt to
260          * de-uniquify to recover input sequence identity, and try to map back
261          * onto dataset Note: this
262          * jalview.analysis.SeqsetUtils.deuniquify(SeqNames, alseqs, true); will
263          * NOT WORK - the returned alignment may contain multiple versions of
264          * the input sequence, each being a subsequence of the original.
265          * deuniquify also removes existing annotation and features added in the
266          * previous step... al.setDataset(dataset); // add in new sequences
267          * retrieved from sequence search which are not already in dataset. //
268          * trigger a 'fetchDBids' to annotate sequences with database ids...
269          */
270
271         return new Object[] { al, nf };
272       }
273       return null;
274     }
275
276     /**
277      * mark subjob as cancelled and set result object appropriatly
278      */
279     void cancel()
280     {
281       cancelled = true;
282       subjobComplete = true;
283       result = null;
284     }
285
286     /**
287      * 
288      * @return boolean true if job can be submitted.
289      */
290     public boolean hasValidInput()
291     {
292       if (seqs.getSeqs() != null)
293       {
294         return true;
295       }
296       return false;
297     }
298   }
299
300   String alTitle; // name which will be used to form new alignment window.
301
302   Alignment dataset; // dataset to which the new alignment will be
303
304   // associated.
305
306   ext.vamsas.SeqSearchI server = null;
307
308   private String dbArg;
309
310   /**
311    * set basic options for this (group) of Msa jobs
312    * 
313    * @param subgaps
314    *          boolean
315    * @param presorder
316    *          boolean
317    */
318   SeqSearchWSThread(ext.vamsas.SeqSearchI server, String wsUrl,
319           WebserviceInfo wsinfo, jalview.gui.AlignFrame alFrame,
320           AlignmentView alview, String wsname, String db)
321   {
322     super(alFrame, wsinfo, alview, wsname, wsUrl);
323     this.server = server;
324     this.dbArg = db;
325   }
326
327   /**
328    * create one or more Msa jobs to align visible seuqences in _msa
329    * 
330    * @param title
331    *          String
332    * @param _msa
333    *          AlignmentView
334    * @param subgaps
335    *          boolean
336    * @param presorder
337    *          boolean
338    * @param seqset
339    *          Alignment
340    */
341   SeqSearchWSThread(ext.vamsas.SeqSearchI server, String wsUrl,
342           WebserviceInfo wsinfo, jalview.gui.AlignFrame alFrame,
343           String wsname, String title, AlignmentView _msa, String db,
344           Alignment seqset)
345   {
346     this(server, wsUrl, wsinfo, alFrame, _msa, wsname, db);
347     OutputHeader = wsInfo.getProgressText();
348     alTitle = title;
349     dataset = seqset;
350
351     SequenceI[][] conmsa = _msa.getVisibleContigs('-');
352     if (conmsa != null)
353     {
354       int njobs = conmsa.length;
355       jobs = new SeqSearchWSJob[njobs];
356       for (int j = 0; j < njobs; j++)
357       {
358         if (j != 0)
359         {
360           jobs[j] = new SeqSearchWSJob(wsinfo.addJobPane(), conmsa[j]);
361         }
362         else
363         {
364           jobs[j] = new SeqSearchWSJob(0, conmsa[j]);
365         }
366         if (njobs > 0)
367         {
368           wsinfo.setProgressName("region " + jobs[j].getJobnum(),
369                   jobs[j].getJobnum());
370         }
371         wsinfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
372       }
373     }
374   }
375
376   public boolean isCancellable()
377   {
378     return true;
379   }
380
381   public void cancelJob()
382   {
383     if (!jobComplete && jobs != null)
384     {
385       boolean cancelled = true;
386       for (int job = 0; job < jobs.length; job++)
387       {
388         if (jobs[job].isSubmitted() && !jobs[job].isSubjobComplete())
389         {
390           String cancelledMessage = "";
391           try
392           {
393             vamsas.objects.simple.WsJobId cancelledJob = server
394                     .cancel(jobs[job].getJobId());
395             if (cancelledJob.getStatus() == 2)
396             {
397               // CANCELLED_JOB
398               cancelledMessage = "Job cancelled.";
399               ((SeqSearchWSJob) jobs[job]).cancel();
400               wsInfo.setStatus(jobs[job].getJobnum(),
401                       WebserviceInfo.STATE_CANCELLED_OK);
402             }
403             else if (cancelledJob.getStatus() == 3)
404             {
405               // VALID UNSTOPPABLE JOB
406               cancelledMessage += "Server cannot cancel this job. just close the window.\n";
407               cancelled = false;
408               // wsInfo.setStatus(jobs[job].jobnum,
409               // WebserviceInfo.STATE_RUNNING);
410             }
411
412             if (cancelledJob.getJobId() != null)
413             {
414               cancelledMessage += ("[" + cancelledJob.getJobId() + "]");
415             }
416
417             cancelledMessage += "\n";
418           } catch (Exception exc)
419           {
420             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
421                     + exc + "\n");
422             Cache.log.warn(
423                     "Exception whilst cancelling " + jobs[job].getJobId(),
424                     exc);
425           }
426           wsInfo.setProgressText(jobs[job].getJobnum(), OutputHeader
427                   + cancelledMessage + "\n");
428         }
429       }
430       if (cancelled)
431       {
432         wsInfo.setStatus(WebserviceInfo.STATE_CANCELLED_OK);
433         jobComplete = true;
434       }
435       this.interrupt(); // kick thread to update job states.
436     }
437     else
438     {
439       if (!jobComplete)
440       {
441         wsInfo.setProgressText(OutputHeader
442                 + "Server cannot cancel this job because it has not been submitted properly. just close the window.\n");
443       }
444     }
445   }
446
447   public void pollJob(AWsJob job) throws Exception
448   {
449     ((SeqSearchWSJob) job).result = server.getResult(((SeqSearchWSJob) job)
450             .getJobId());
451   }
452
453   public void StartJob(AWsJob job)
454   {
455     if (!(job instanceof SeqSearchWSJob))
456     {
457       throw new Error(MessageManager.formatMessage(
458               "error.implementation_error_msawbjob_called",
459               new String[] { job.getClass().toString() }));
460     }
461     SeqSearchWSJob j = (SeqSearchWSJob) job;
462     if (j.isSubmitted())
463     {
464       if (Cache.log.isDebugEnabled())
465       {
466         Cache.log.debug("Tried to submit an already submitted job "
467                 + j.getJobId());
468       }
469       return;
470     }
471     if (j.seqs.getSeqs() == null)
472     {
473       // special case - selection consisted entirely of empty sequences...
474       j.setSubmitted(true);
475       j.result = new MsaResult();
476       j.result.setFinished(true);
477       j.result.setStatus(MessageManager
478               .getString("label.empty_alignment_job"));
479       ((MsaResult) j.result).setMsa(null);
480     }
481     try
482     {
483       vamsas.objects.simple.WsJobId jobsubmit = server.search(
484               j.seqs.getSeqs()[0], dbArg);
485
486       if ((jobsubmit != null) && (jobsubmit.getStatus() == 1))
487       {
488         j.setJobId(jobsubmit.getJobId());
489         j.setSubmitted(true);
490         j.setSubjobComplete(false);
491         // System.out.println(WsURL + " Job Id '" + jobId + "'");
492       }
493       else
494       {
495         if (jobsubmit == null)
496         {
497           throw new Exception(MessageManager.formatMessage(
498                   "exception.web_service_returned_null_try_later",
499                   new String[] { WsUrl }));
500         }
501
502         throw new Exception(jobsubmit.getJobId());
503       }
504     } catch (Exception e)
505     {
506       // TODO: JBPNote catch timeout or other fault types explicitly
507       // For unexpected errors
508       System.err
509               .println(WebServiceName
510                       + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
511                       + "When contacting Server:" + WsUrl + "\n"
512                       + e.toString() + "\n");
513       j.setAllowedServerExceptions(0);
514       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
515       wsInfo.setStatus(j.getJobnum(),
516               WebserviceInfo.STATE_STOPPED_SERVERERROR);
517       wsInfo.appendProgressText(j.getJobnum(), MessageManager
518               .getString("info.failed_to_submit_sequences_for_alignment"));
519
520       // e.printStackTrace(); // TODO: JBPNote DEBUG
521     }
522   }
523
524   private jalview.datamodel.Sequence[] getVamsasAlignment(
525           vamsas.objects.simple.Alignment valign)
526   {
527     vamsas.objects.simple.Sequence[] seqs = valign.getSeqs().getSeqs();
528     jalview.datamodel.Sequence[] msa = new jalview.datamodel.Sequence[seqs.length];
529
530     for (int i = 0, j = seqs.length; i < j; i++)
531     {
532       msa[i] = new jalview.datamodel.Sequence(seqs[i].getId(),
533               seqs[i].getSeq());
534     }
535
536     return msa;
537   }
538
539   public void parseResult()
540   {
541     int results = 0; // number of result sets received
542     JobStateSummary finalState = new JobStateSummary();
543     try
544     {
545       for (int j = 0; j < jobs.length; j++)
546       {
547         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
548         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
549                 && jobs[j].hasResults())
550         {
551           results++;
552           vamsas.objects.simple.Alignment valign = ((SeqSearchResult) ((SeqSearchWSJob) jobs[j]).result)
553                   .getAlignment();
554           if (valign != null)
555           {
556             wsInfo.appendProgressText(jobs[j].getJobnum(), MessageManager
557                     .getString("info.alignment_object_method_notes"));
558             String[] lines = valign.getMethod();
559             for (int line = 0; line < lines.length; line++)
560             {
561               wsInfo.appendProgressText(jobs[j].getJobnum(), lines[line]
562                       + "\n");
563             }
564             // JBPNote The returned files from a webservice could be
565             // hidden behind icons in the monitor window that,
566             // when clicked, pop up their corresponding data
567           }
568         }
569       }
570     } catch (Exception ex)
571     {
572
573       Cache.log.error("Unexpected exception when processing results for "
574               + alTitle, ex);
575       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
576     }
577     if (results > 0)
578     {
579       wsInfo.showResultsNewFrame
580               .addActionListener(new java.awt.event.ActionListener()
581               {
582                 public void actionPerformed(java.awt.event.ActionEvent evt)
583                 {
584                   displayResults(true);
585                 }
586               });
587       wsInfo.mergeResults
588               .addActionListener(new java.awt.event.ActionListener()
589               {
590                 public void actionPerformed(java.awt.event.ActionEvent evt)
591                 {
592                   displayResults(false);
593                 }
594               });
595       wsInfo.setResultsReady();
596     }
597     else
598     {
599       wsInfo.setFinishedNoResults();
600     }
601   }
602
603   void displayResults(boolean newFrame)
604   {
605     if (!newFrame)
606     {
607       System.err.println("MERGE WITH OLD FRAME NOT IMPLEMENTED");
608       return;
609     }
610     // each subjob is an independent alignment for the moment
611     // Alignment al[] = new Alignment[jobs.length];
612     // NewickFile nf[] = new NewickFile[jobs.length];
613     for (int j = 0; j < jobs.length; j++)
614     {
615       Map featureColours = new HashMap();
616       Alignment al = null;
617       NewickFile nf = null;
618       if (jobs[j].hasResults())
619       {
620         Object[] res = ((SeqSearchWSJob) jobs[j]).getAlignment(dataset,
621                 featureColours);
622         if (res == null)
623         {
624           continue;
625         }
626         ;
627         al = (Alignment) res[0];
628         nf = (NewickFile) res[1];
629       }
630       else
631       {
632         al = null;
633         nf = null;
634         continue;
635       }
636       /*
637        * We can't map new alignment back with insertions from input's hidden
638        * regions until dataset mapping is sorted out... but basically it goes
639        * like this: 1. Merge each domain hit back onto the visible segments in
640        * the same way as a Jnet prediction is mapped back
641        * 
642        * Object[] newview = input.getUpdatedView(results, orders, getGapChar());
643        * // trash references to original result data for (int j = 0; j <
644        * jobs.length; j++) { results[j] = null; orders[j] = null; } SequenceI[]
645        * alignment = (SequenceI[]) newview[0]; ColumnSelection columnselection =
646        * (ColumnSelection) newview[1]; Alignment al = new Alignment(alignment);
647        * 
648        * if (dataset != null) { al.setDataset(dataset); }
649        * 
650        * propagateDatasetMappings(al); }
651        */
652
653       AlignFrame af = new AlignFrame(al,// columnselection,
654               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
655       if (nf != null)
656       {
657         af.ShowNewickTree(nf, MessageManager.formatMessage(
658                 "label.tree_from", new String[] { this.alTitle }));
659       }
660       // initialise with same renderer settings as in parent alignframe.
661       af.getFeatureRenderer().transferSettings(this.featureSettings);
662       Desktop.addInternalFrame(af, alTitle, AlignFrame.DEFAULT_WIDTH,
663               AlignFrame.DEFAULT_HEIGHT);
664     }
665   }
666
667   public boolean canMergeResults()
668   {
669     return false;
670   }
671 }