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