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