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