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