926256d5542376f03600da909a5f2ee1f23be999
[jalview.git] / src / jalview / ws / jws2 / JabawsAlignCalcWorker.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, 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.jws2;
19
20 import jalview.analysis.AlignSeq;
21 import jalview.analysis.SeqsetUtils;
22 import jalview.api.AlignViewportI;
23 import jalview.api.AlignmentViewPanel;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.AnnotatedCollectionI;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.IProgressIndicator;
31 import jalview.workers.AlignCalcWorker;
32 import jalview.ws.jws2.dm.JabaWsParamSet;
33 import jalview.ws.jws2.jabaws2.Jws2Instance;
34 import jalview.ws.params.WsParamSetI;
35
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41
42 import compbio.data.msa.SequenceAnnotation;
43 import compbio.data.sequence.FastaSequence;
44 import compbio.data.sequence.Score;
45 import compbio.data.sequence.ScoreManager;
46 import compbio.metadata.Argument;
47 import compbio.metadata.ChunkHolder;
48 import compbio.metadata.JobStatus;
49 import compbio.metadata.JobSubmissionException;
50 import compbio.metadata.Option;
51 import compbio.metadata.ResultNotAvailableException;
52 import compbio.metadata.WrongParameterException;
53
54 public abstract class JabawsAlignCalcWorker extends AlignCalcWorker
55 {
56   Jws2Instance service;
57
58   @SuppressWarnings("unchecked")
59   protected SequenceAnnotation aaservice;
60
61   protected ScoreManager scoremanager;
62
63   protected WsParamSetI preset;
64
65   protected List<Argument> arguments;
66
67   public JabawsAlignCalcWorker(AlignViewportI alignViewport,
68           AlignmentViewPanel alignPanel)
69   {
70     super(alignViewport, alignPanel);
71   }
72
73   IProgressIndicator guiProgress;
74
75   public JabawsAlignCalcWorker(Jws2Instance service, AlignFrame alignFrame,
76           WsParamSetI preset, List<Argument> paramset)
77   {
78     this(alignFrame.getCurrentView(), alignFrame.alignPanel);
79     this.guiProgress = alignFrame;
80     this.preset = preset;
81     this.arguments = paramset;
82     this.service = service;
83     aaservice = (SequenceAnnotation) service.service;
84
85   }
86
87   public WsParamSetI getPreset()
88   {
89     return preset;
90   }
91
92   public List<Argument> getArguments()
93   {
94     return arguments;
95   }
96
97   /**
98    * reconfigure and restart the AAConClient. This method will spawn a new
99    * thread that will wait until any current jobs are finished, modify the
100    * parameters and restart the conservation calculation with the new values.
101    * 
102    * @param newpreset
103    * @param newarguments
104    */
105   public void updateParameters(final WsParamSetI newpreset,
106           final List<Argument> newarguments)
107   {
108     preset = newpreset;
109     arguments = newarguments;
110     calcMan.startWorker(this);
111   }
112
113   public List<Option> getJabaArguments()
114   {
115     List<Option> newargs = new ArrayList<Option>();
116     if (preset != null && preset instanceof JabaWsParamSet)
117     {
118       newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
119     }
120     if (arguments != null && arguments.size() > 0)
121     {
122       for (Argument rg : arguments)
123       {
124         if (Option.class.isAssignableFrom(rg.getClass()))
125         {
126           newargs.add((Option) rg);
127         }
128       }
129     }
130     return newargs;
131   }
132
133   @Override
134   public void run()
135   {
136     if (aaservice == null)
137     {
138       return;
139     }
140     long progressId = -1;
141
142     int serverErrorsLeft = 3;
143
144     String rslt = "JOB NOT DEFINED";
145     StringBuffer msg = new StringBuffer();
146     try
147     {
148       if (checkDone())
149       {
150         return;
151       }
152       List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(alignViewport
153               .getAlignment(), bySequence ? alignViewport.getSelectionGroup() : null);
154
155       if (seqs == null)
156       {
157         calcMan.workerComplete(this);
158         return;
159       }
160
161       AlignmentAnnotation[] aa = alignViewport.getAlignment()
162               .getAlignmentAnnotation();
163       if (guiProgress != null)
164       {
165         guiProgress.setProgressBar("JABA " + getServiceActionText(),
166                 progressId = System.currentTimeMillis());
167       }
168       if (preset == null && arguments == null)
169       {
170         rslt = aaservice.analize(seqs);
171       }
172       else
173       {
174         try
175         {
176           rslt = aaservice.customAnalize(seqs, getJabaArguments());
177         } catch (WrongParameterException x)
178         {
179           throw new JobSubmissionException(
180                   "Invalid parameter set. Check Jalview implementation.", x);
181
182         }
183       }
184       boolean finished = false;
185       long rpos = 0;
186       do
187       {
188         JobStatus status = aaservice.getJobStatus(rslt);
189         if (status.equals(JobStatus.FINISHED))
190         {
191           finished = true;
192         }
193         if (calcMan.isPending(this) && this instanceof AAConClient)
194         {
195           finished = true;
196           // cancel this job and yield to the new job
197           try
198           {
199             if (aaservice.cancelJob(rslt))
200             {
201               System.err.println("Cancelled AACon job: " + rslt);
202             }
203             else
204             {
205               System.err.println("FAILED TO CANCEL AACon job: " + rslt);
206             }
207
208           } catch (Exception x)
209           {
210
211           }
212
213           return;
214         }
215         long cpos;
216         ChunkHolder stats = null;
217         do
218         {
219           cpos = rpos;
220           boolean retry = false;
221           do
222           {
223             try
224             {
225               stats = aaservice.pullExecStatistics(rslt, rpos);
226             } catch (Exception x)
227             {
228
229               if (x.getMessage().contains(
230                       "Position in a file could not be negative!"))
231               {
232                 // squash index out of bounds exception- seems to happen for
233                 // disorder predictors which don't (apparently) produce any
234                 // progress information and JABA server throws an exception
235                 // because progress length is -1.
236                 stats = null;
237               }
238               else
239               {
240                 if (--serverErrorsLeft > 0)
241                 {
242                   retry = true;
243                   try
244                   {
245                     Thread.sleep(200);
246                   } catch (InterruptedException q)
247                   {
248                   }
249                   ;
250                 }
251                 else
252                 {
253                   throw x;
254                 }
255               }
256             }
257           } while (retry);
258           if (stats != null)
259           {
260             System.out.print(stats.getChunk());
261             msg.append(stats);
262             rpos = stats.getNextPosition();
263           }
264         } while (stats != null && rpos > cpos);
265
266         if (!finished && status.equals(JobStatus.FAILED))
267         {
268           try
269           {
270             Thread.sleep(200);
271           } catch (InterruptedException x)
272           {
273           }
274           ;
275         }
276       } while (!finished);
277       if (serverErrorsLeft > 0)
278       {
279         try
280         {
281           Thread.sleep(200);
282         } catch (InterruptedException x)
283         {
284         }
285         ;
286         scoremanager = aaservice.getAnnotation(rslt);
287         if (scoremanager != null)
288         {
289           jalview.bin.Cache.log
290                   .debug("Updating result annotation from Job " + rslt
291                           + " at " + service.getUri());
292           updateResultAnnotation(true);
293           ap.adjustAnnotationHeight();
294         }
295       }
296     }
297
298     catch (JobSubmissionException x)
299     {
300
301       System.err.println("submission error with " + getServiceActionText()
302               + " :");
303       x.printStackTrace();
304       calcMan.workerCannotRun(this);
305     } catch (ResultNotAvailableException x)
306     {
307       System.err.println("collection error:\nJob ID: " + rslt);
308       x.printStackTrace();
309       calcMan.workerCannotRun(this);
310
311     } catch (OutOfMemoryError error)
312     {
313       calcMan.workerCannotRun(this);
314
315       // consensus = null;
316       // hconsensus = null;
317       ap.raiseOOMWarning(getServiceActionText(), error);
318     } catch (Exception x)
319     {
320       calcMan.workerCannotRun(this);
321
322       // consensus = null;
323       // hconsensus = null;
324       System.err
325               .println("Blacklisting worker due to unexpected exception:");
326       x.printStackTrace();
327     } finally
328     {
329
330       calcMan.workerComplete(this);
331       if (ap != null)
332       {
333         calcMan.workerComplete(this);
334         if (guiProgress != null && progressId != -1)
335         {
336           guiProgress.setProgressBar("", progressId);
337         }
338         ap.paintAlignment(true);
339       }
340       if (msg.length() > 0)
341       {
342         // TODO: stash message somewhere in annotation or alignment view.
343         // code below shows result in a text box popup
344         /*
345          * jalview.gui.CutAndPasteTransfer cap = new
346          * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
347          * jalview.gui.Desktop.addInternalFrame(cap,
348          * "Job Status for "+getServiceActionText(), 600, 400);
349          */
350       }
351     }
352
353   }
354
355   @Override
356   public void updateAnnotation()
357   {
358     updateResultAnnotation(false);
359   }
360
361   public abstract void updateResultAnnotation(boolean immediate);
362
363   public abstract String getServiceActionText();
364
365   boolean submitGaps = true;
366
367   boolean alignedSeqs = true;
368
369   boolean nucleotidesAllowed = false;
370
371   boolean proteinAllowed = false;
372
373   /**
374    * record sequences for mapping result back to afterwards
375    */
376   protected boolean bySequence = false;
377
378   Map<String, SequenceI> seqNames;
379
380   boolean[] gapMap;
381
382   int realw;
383   
384   int start,end;
385
386   public List<FastaSequence> getInputSequences(AlignmentI alignment, AnnotatedCollectionI inputSeqs)
387   {
388     if (alignment == null || alignment.getWidth() <= 0
389             || alignment.getSequences() == null
390             // || (alignedSeqs && !alignment.isAligned() && !submitGaps)
391             || alignment.isNucleotide() ? !nucleotidesAllowed
392             : !proteinAllowed)
393     {
394       return null;
395     }
396     if (inputSeqs==null || inputSeqs.getWidth()<=0 || inputSeqs.getSequences()==null || inputSeqs.getSequences().size()<1)
397     {
398       inputSeqs = alignment;
399     }
400     
401     List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
402
403     int minlen = 10;
404     int ln = -1;
405     if (bySequence)
406     {
407       seqNames = new HashMap<String, SequenceI>();
408     }
409     gapMap = new boolean[0];
410     start=inputSeqs.getStartRes();
411     end=inputSeqs.getEndRes();
412     
413     for (SequenceI sq : (List<SequenceI>) inputSeqs.getSequences())
414     {
415       if (sq.findPosition(end+1) -sq.findPosition(start+1) > minlen - 1)
416       {
417         String newname = SeqsetUtils.unique_name(seqs.size() + 1);
418         // make new input sequence with or without gaps
419         if (seqNames != null)
420         {
421           seqNames.put(newname, sq);
422         }
423         FastaSequence seq;
424         if (submitGaps)
425         {
426           seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
427                   sq.getSequenceAsString()));
428           if (gapMap == null || gapMap.length < seq.getSequence().length())
429           {
430             boolean[] tg = gapMap;
431             gapMap = new boolean[seq.getLength()];
432             System.arraycopy(tg, 0, gapMap, 0, tg.length);
433             for (int p = tg.length; p < gapMap.length; p++)
434             {
435               gapMap[p] = false; // init as a gap
436             }
437           }
438           for (int apos : sq.gapMap())
439           {
440             gapMap[apos] = true; // aligned.
441           }
442         }
443         else
444         {
445           seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
446                   AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
447                           sq.getSequenceAsString(start,end+1))));
448         }
449         if (seq.getSequence().length() > ln)
450         {
451           ln = seq.getSequence().length();
452         }
453       }
454     }
455     if (alignedSeqs && submitGaps)
456     {
457       realw = 0;
458       for (int i = 0; i < gapMap.length; i++)
459       {
460         if (gapMap[i])
461         {
462           realw++;
463         }
464       }
465       // try real hard to return something submittable
466       // TODO: some of AAcon measures need a minimum of two or three amino
467       // acids at each position, and AAcon doesn't gracefully degrade.
468       for (int p = 0; p < seqs.size(); p++)
469       {
470         FastaSequence sq = seqs.get(p);
471         int l = sq.getSequence().length();
472         // strip gapped columns
473         char[] padded = new char[realw], orig = sq.getSequence()
474                 .toCharArray();
475         for (int i = 0, pp = 0; i < realw; pp++)
476         {
477           if (gapMap[pp])
478           {
479             if (orig.length > pp)
480             {
481               padded[i++] = orig[pp];
482             }
483             else
484             {
485               padded[i++] = '-';
486             }
487           }
488         }
489         seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
490                 new String(padded)));
491       }
492     }
493     return seqs;
494   }
495
496   /**
497    * notify manager that we have started, and wait for a free calculation slot
498    * 
499    * @return true if slot is obtained and work still valid, false if another
500    *         thread has done our work for us.
501    */
502   boolean checkDone()
503   {
504     calcMan.notifyStart(this);
505     ap.paintAlignment(false);
506     while (!calcMan.notifyWorking(this))
507     {
508       if (calcMan.isWorking(this))
509       {
510         return true;
511       }
512       try
513       {
514         if (ap != null)
515         {
516           ap.paintAlignment(false);
517         }
518
519         Thread.sleep(200);
520       } catch (Exception ex)
521       {
522         ex.printStackTrace();
523       }
524     }
525     if (alignViewport.isClosed())
526     {
527       abortAndDestroy();
528       return true;
529     }
530     return false;
531   }
532
533   protected void createAnnotationRowsForScores(
534           List<AlignmentAnnotation> ourAnnot, String calcId, int alWidth,
535           Score scr)
536   {
537     // simple annotation row
538     AlignmentAnnotation annotation = alignViewport.getAlignment()
539             .findOrCreateAnnotation(scr.getMethod(), calcId, true, null,
540                     null);
541     if (alWidth == gapMap.length) // scr.getScores().size())
542     {
543       constructAnnotationFromScore(annotation, 0, alWidth, scr);
544       ourAnnot.add(annotation);
545     }
546   }
547
548   protected AlignmentAnnotation createAnnotationRowsForScores(
549           List<AlignmentAnnotation> ourAnnot, String typeName,
550           String calcId, SequenceI dseq, int base, Score scr)
551   {
552     System.out.println("Creating annotation on dseq:" + dseq.getStart()
553             + " base is " + base + " and length=" + dseq.getLength()
554             + " == " + scr.getScores().size());
555     // AlignmentAnnotation annotation = new AlignmentAnnotation(
556     // scr.getMethod(), typeName, new Annotation[]
557     // {}, 0, -1, AlignmentAnnotation.LINE_GRAPH);
558     // annotation.setCalcId(calcId);
559     AlignmentAnnotation annotation = alignViewport.getAlignment()
560             .findOrCreateAnnotation(typeName, calcId, false, dseq, null);
561     constructAnnotationFromScore(annotation, 0, dseq.getLength(), scr);
562     annotation.createSequenceMapping(dseq, base, false);
563     annotation.adjustForAlignment();
564     dseq.addAlignmentAnnotation(annotation);
565     ourAnnot.add(annotation);
566     return annotation;
567   }
568
569   private void constructAnnotationFromScore(AlignmentAnnotation annotation,
570           int base, int alWidth, Score scr)
571   {
572     Annotation[] elm = new Annotation[alWidth];
573     Iterator<Float> vals = scr.getScores().iterator();
574     float m = 0f, x = 0f;
575     for (int i = 0; vals.hasNext(); i++)
576     {
577       float val = vals.next().floatValue();
578       if (i == 0)
579       {
580         m = val;
581         x = val;
582       }
583       else
584       {
585         if (m > val)
586         {
587           m = val;
588         }
589         ;
590         if (x < val)
591         {
592           x = val;
593         }
594       }
595       // if we're at a gapped column then skip to next ungapped position
596       if (gapMap != null && gapMap.length > 0)
597       {
598         while (!gapMap[i])
599         {
600           elm[i++] = new Annotation("", "", ' ', Float.NaN);
601         }
602       }
603       elm[i] = new Annotation("", "" + val, ' ', val);
604     }
605
606     annotation.annotations = elm;
607     annotation.belowAlignment = true;
608     if (x < 0)
609     {
610       x = 0;
611     }
612     x += (x - m) * 0.1;
613     annotation.graphMax = x;
614     annotation.graphMin = m;
615     annotation.validateRangeAndDisplay();
616   }
617
618   protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
619   {
620     List<AlignmentAnnotation> our = ourAnnots;
621     ourAnnots = ourAnnot;
622     AlignmentI alignment = alignViewport.getAlignment();
623     if (our != null)
624     {
625       if (our.size() > 0)
626       {
627         for (AlignmentAnnotation an : our)
628         {
629           if (!ourAnnots.contains(an))
630           {
631             // remove the old annotation
632             alignment.deleteAnnotation(an);
633           }
634         }
635       }
636       our.clear();
637
638       ap.adjustAnnotationHeight();
639     }
640   }
641 }