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