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