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