Jalview 2.6 source licence
[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, jalview.analysis.SeqsetUtils
128                 .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, seqs[i]
144                             .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
378                   .setProgressName("region " + jobs[j].getJobnum(),
379                           jobs[j].getJobnum());
380         }
381         wsinfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
382       }
383     }
384   }
385
386   public boolean isCancellable()
387   {
388     return true;
389   }
390
391   public void cancelJob()
392   {
393     if (!jobComplete && jobs != null)
394     {
395       boolean cancelled = true;
396       for (int job = 0; job < jobs.length; job++)
397       {
398         if (jobs[job].isSubmitted() && !jobs[job].isSubjobComplete())
399         {
400           String cancelledMessage = "";
401           try
402           {
403             vamsas.objects.simple.WsJobId cancelledJob = server
404                     .cancel(jobs[job].getJobId());
405             if (cancelledJob.getStatus() == 2)
406             {
407               // CANCELLED_JOB
408               cancelledMessage = "Job cancelled.";
409               ((SeqSearchWSJob) jobs[job]).cancel();
410               wsInfo.setStatus(jobs[job].getJobnum(),
411                       WebserviceInfo.STATE_CANCELLED_OK);
412             }
413             else if (cancelledJob.getStatus() == 3)
414             {
415               // VALID UNSTOPPABLE JOB
416               cancelledMessage += "Server cannot cancel this job. just close the window.\n";
417               cancelled = false;
418               // wsInfo.setStatus(jobs[job].jobnum,
419               // WebserviceInfo.STATE_RUNNING);
420             }
421
422             if (cancelledJob.getJobId() != null)
423             {
424               cancelledMessage += ("[" + cancelledJob.getJobId() + "]");
425             }
426
427             cancelledMessage += "\n";
428           } catch (Exception exc)
429           {
430             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
431                     + exc + "\n");
432             Cache.log.warn(
433                     "Exception whilst cancelling " + jobs[job].getJobId(), 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
451                 .setProgressText(OutputHeader
452                         + "Server cannot cancel this job because it has not been submitted properly. just close the window.\n");
453       }
454     }
455   }
456
457   public void pollJob(AWsJob job) throws Exception
458   {
459     ((SeqSearchWSJob) job).result = server
460             .getResult(((SeqSearchWSJob) job).getJobId());
461   }
462
463   public void StartJob(AWsJob job)
464   {
465     if (!(job instanceof SeqSearchWSJob))
466     {
467       throw new Error("StartJob(MsaWSJob) called on a WSJobInstance "
468               + job.getClass());
469     }
470     SeqSearchWSJob j = (SeqSearchWSJob) job;
471     if (j.isSubmitted())
472     {
473       if (Cache.log.isDebugEnabled())
474       {
475         Cache.log.debug("Tried to submit an already submitted job "
476                 + j.getJobId());
477       }
478       return;
479     }
480     if (j.seqs.getSeqs() == null)
481     {
482       // special case - selection consisted entirely of empty sequences...
483       j.setSubmitted(true);
484       j.result = new MsaResult();
485       j.result.setFinished(true);
486       j.result.setStatus("Empty Alignment Job");
487       ((MsaResult) j.result).setMsa(null);
488     }
489     try
490     {
491       vamsas.objects.simple.WsJobId jobsubmit = server.search(j.seqs
492               .getSeqs()[0], dbArg);
493
494       if ((jobsubmit != null) && (jobsubmit.getStatus() == 1))
495       {
496         j.setJobId(jobsubmit.getJobId());
497         j.setSubmitted(true);
498         j.setSubjobComplete(false);
499         // System.out.println(WsURL + " Job Id '" + jobId + "'");
500       }
501       else
502       {
503         if (jobsubmit == null)
504         {
505           throw new Exception(
506                   "Server at "
507                           + WsUrl
508                           + " returned null object, it probably cannot be contacted. Try again later ?");
509         }
510
511         throw new Exception(jobsubmit.getJobId());
512       }
513     } catch (Exception e)
514     {
515       // TODO: JBPNote catch timeout or other fault types explicitly
516       // For unexpected errors
517       System.err
518               .println(WebServiceName
519                       + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
520                       + "When contacting Server:" + WsUrl + "\n"
521                       + e.toString() + "\n");
522       j.setAllowedServerExceptions(0);
523       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
524       wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_SERVERERROR);
525       wsInfo
526               .appendProgressText(
527                       j.getJobnum(),
528                       "Failed to submit sequences for alignment.\n"
529                               + "It is most likely that there is a problem with the server.\n"
530                               + "Just close the window\n");
531
532       // e.printStackTrace(); // TODO: JBPNote DEBUG
533     }
534   }
535
536   private jalview.datamodel.Sequence[] getVamsasAlignment(
537           vamsas.objects.simple.Alignment valign)
538   {
539     vamsas.objects.simple.Sequence[] seqs = valign.getSeqs().getSeqs();
540     jalview.datamodel.Sequence[] msa = new jalview.datamodel.Sequence[seqs.length];
541
542     for (int i = 0, j = seqs.length; i < j; i++)
543     {
544       msa[i] = new jalview.datamodel.Sequence(seqs[i].getId(), seqs[i]
545               .getSeq());
546     }
547
548     return msa;
549   }
550
551   public void parseResult()
552   {
553     int results = 0; // number of result sets received
554     JobStateSummary finalState = new JobStateSummary();
555     try
556     {
557       for (int j = 0; j < jobs.length; j++)
558       {
559         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
560         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
561                 && jobs[j].hasResults())
562         {
563           results++;
564           vamsas.objects.simple.Alignment valign = ((SeqSearchResult) ((SeqSearchWSJob)jobs[j]).result)
565                   .getAlignment();
566           if (valign != null)
567           {
568             wsInfo.appendProgressText(jobs[j].getJobnum(),
569                     "\nAlignment Object Method Notes\n");
570             String[] lines = valign.getMethod();
571             for (int line = 0; line < lines.length; line++)
572             {
573               wsInfo.appendProgressText(jobs[j].getJobnum(), lines[line] + "\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 }