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