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