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