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