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