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.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 AAConClient. 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 AAConClient)
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                   {
227                     Thread.sleep(200);
228                   } catch (InterruptedException q)
229                   {
230                   }
231                   ;
232                 }
233                 else
234                 {
235                   throw x;
236                 }
237               }
238             }
239           } while (retry);
240           if (stats != null)
241           {
242             System.out.print(stats.getChunk());
243             msg.append(stats);
244             rpos = stats.getNextPosition();
245           }
246         } while (stats != null && rpos > cpos);
247
248         if (!finished && status.equals(JobStatus.FAILED))
249         {
250           try
251           {
252             Thread.sleep(200);
253           } catch (InterruptedException x)
254           {
255           }
256           ;
257         }
258       } while (!finished);
259       if (serverErrorsLeft > 0)
260       {
261         try
262         {
263           Thread.sleep(200);
264         } catch (InterruptedException x)
265         {
266         }
267         ;
268         scoremanager = aaservice.getAnnotation(rslt);
269         if (scoremanager != null)
270         {
271           jalview.bin.Cache.log
272                   .debug("Updating result annotation from Job " + rslt
273                           + " at " + service.getUri());
274           updateResultAnnotation(true);
275           ap.adjustAnnotationHeight();
276         }
277       }
278     }
279
280     catch (JobSubmissionException x)
281     {
282
283       System.err.println("submission error with " + getServiceActionText()
284               + " :");
285       x.printStackTrace();
286       calcMan.workerCannotRun(this);
287     } catch (ResultNotAvailableException x)
288     {
289       System.err.println("collection error:\nJob ID: " + rslt);
290       x.printStackTrace();
291       calcMan.workerCannotRun(this);
292
293     } catch (OutOfMemoryError error)
294     {
295       calcMan.workerCannotRun(this);
296
297       // consensus = null;
298       // hconsensus = null;
299       ap.raiseOOMWarning(getServiceActionText(), error);
300     } catch (Exception x)
301     {
302       calcMan.workerCannotRun(this);
303
304       // consensus = null;
305       // hconsensus = null;
306       System.err
307               .println("Blacklisting worker due to unexpected exception:");
308       x.printStackTrace();
309     } finally
310     {
311
312       calcMan.workerComplete(this);
313       if (ap != null)
314       {
315         calcMan.workerComplete(this);
316         if (guiProgress != null && progressId != -1)
317         {
318           guiProgress.setProgressBar("", progressId);
319         }
320         ap.paintAlignment(true);
321       }
322       if (msg.length() > 0)
323       {
324         // TODO: stash message somewhere in annotation or alignment view.
325         // code below shows result in a text box popup
326         /*
327          * jalview.gui.CutAndPasteTransfer cap = new
328          * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
329          * jalview.gui.Desktop.addInternalFrame(cap,
330          * "Job Status for "+getServiceActionText(), 600, 400);
331          */
332       }
333     }
334
335   }
336
337   @Override
338   public void updateAnnotation()
339   {
340     updateResultAnnotation(false);
341   }
342
343   public abstract void updateResultAnnotation(boolean immediate);
344
345   public abstract String getServiceActionText();
346
347   boolean submitGaps = true;
348
349   boolean alignedSeqs = true;
350
351   boolean nucleotidesAllowed = false;
352
353   boolean proteinAllowed = false;
354
355   /**
356    * record sequences for mapping result back to afterwards
357    */
358   protected boolean bySequence = false;
359
360   Map<String, SequenceI> seqNames;
361
362   boolean[] gapMap;
363
364   int realw;
365
366   public List<FastaSequence> getInputSequences(AlignmentI alignment)
367   {
368     if (alignment == null || alignment.getWidth() <= 0
369             || alignment.getSequences() == null
370             // || (alignedSeqs && !alignment.isAligned() && !submitGaps)
371             || alignment.isNucleotide() ? !nucleotidesAllowed
372             : !proteinAllowed)
373     {
374       return null;
375     }
376     List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
377
378     int minlen = 10;
379     int ln = -1;
380     if (bySequence)
381     {
382       seqNames = new HashMap<String, SequenceI>();
383     }
384     gapMap = new boolean[0];
385     for (SequenceI sq : ((List<SequenceI>) alignment.getSequences()))
386     {
387       if (sq.getEnd() - sq.getStart() > minlen - 1)
388       {
389         String newname = SeqsetUtils.unique_name(seqs.size() + 1);
390         // make new input sequence with or without gaps
391         if (seqNames != null)
392         {
393           seqNames.put(newname, sq);
394         }
395         FastaSequence seq;
396         if (submitGaps)
397         {
398           seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
399                   sq.getSequenceAsString()));
400           if (gapMap == null || gapMap.length < seq.getSequence().length())
401           {
402             boolean[] tg = gapMap;
403             gapMap = new boolean[seq.getLength()];
404             System.arraycopy(tg, 0, gapMap, 0, tg.length);
405             for (int p = tg.length; p < gapMap.length; p++)
406             {
407               gapMap[p] = false; // init as a gap
408             }
409           }
410           for (int apos : sq.gapMap())
411           {
412             gapMap[apos] = true; // aligned.
413           }
414         }
415         else
416         {
417           seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
418                   AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
419                           sq.getSequenceAsString())));
420         }
421         if (seq.getSequence().length() > ln)
422         {
423           ln = seq.getSequence().length();
424         }
425       }
426     }
427     if (alignedSeqs && submitGaps)
428     {
429       realw = 0;
430       for (int i = 0; i < gapMap.length; i++)
431       {
432         if (gapMap[i])
433         {
434           realw++;
435         }
436       }
437       // try real hard to return something submittable
438       // TODO: some of AAcon measures need a minimum of two or three amino
439       // acids at each position, and AAcon doesn't gracefully degrade.
440       for (int p = 0; p < seqs.size(); p++)
441       {
442         FastaSequence sq = seqs.get(p);
443         int l = sq.getSequence().length();
444         // strip gapped columns
445         char[] padded = new char[realw], orig = sq.getSequence()
446                 .toCharArray();
447         for (int i = 0, pp = 0; i < realw; pp++)
448         {
449           if (gapMap[pp])
450           {
451             if (orig.length > pp)
452             {
453               padded[i++] = orig[pp];
454             }
455             else
456             {
457               padded[i++] = '-';
458             }
459           }
460         }
461         seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
462                 new String(padded)));
463       }
464     }
465     return seqs;
466   }
467
468   /**
469    * notify manager that we have started, and wait for a free calculation slot
470    * 
471    * @return true if slot is obtained and work still valid, false if another
472    *         thread has done our work for us.
473    */
474   boolean checkDone()
475   {
476     calcMan.notifyStart(this);
477     ap.paintAlignment(false);
478     while (!calcMan.notifyWorking(this))
479     {
480       if (calcMan.isWorking(this))
481       {
482         return true;
483       }
484       try
485       {
486         if (ap != null)
487         {
488           ap.paintAlignment(false);
489         }
490
491         Thread.sleep(200);
492       } catch (Exception ex)
493       {
494         ex.printStackTrace();
495       }
496     }
497     if (alignViewport.isClosed())
498     {
499       abortAndDestroy();
500       return true;
501     }
502     return false;
503   }
504
505   protected void createAnnotationRowsForScores(
506           List<AlignmentAnnotation> ourAnnot, String calcId, int alWidth,
507           Score scr)
508   {
509     // simple annotation row
510     AlignmentAnnotation annotation = alignViewport.getAlignment()
511             .findOrCreateAnnotation(scr.getMethod(), calcId, true, null,
512                     null);
513     if (alWidth == gapMap.length) // scr.getScores().size())
514     {
515       constructAnnotationFromScore(annotation, 0, alWidth, scr);
516       ourAnnot.add(annotation);
517     }
518   }
519
520   protected AlignmentAnnotation createAnnotationRowsForScores(
521           List<AlignmentAnnotation> ourAnnot, String typeName,
522           String calcId, SequenceI dseq, int base, Score scr)
523   {
524     System.out.println("Creating annotation on dseq:" + dseq.getStart()
525             + " base is " + base + " and length=" + dseq.getLength()
526             + " == " + scr.getScores().size());
527     // AlignmentAnnotation annotation = new AlignmentAnnotation(
528     // scr.getMethod(), typeName, new Annotation[]
529     // {}, 0, -1, AlignmentAnnotation.LINE_GRAPH);
530     // annotation.setCalcId(calcId);
531     AlignmentAnnotation annotation = alignViewport.getAlignment()
532             .findOrCreateAnnotation(typeName, calcId, false, dseq, null);
533     constructAnnotationFromScore(annotation, 0, dseq.getLength(), scr);
534     annotation.createSequenceMapping(dseq, base, false);
535     annotation.adjustForAlignment();
536     dseq.addAlignmentAnnotation(annotation);
537     ourAnnot.add(annotation);
538     return annotation;
539   }
540
541   private void constructAnnotationFromScore(AlignmentAnnotation annotation,
542           int base, int alWidth, Score scr)
543   {
544     Annotation[] elm = new Annotation[alWidth];
545     Iterator<Float> vals = scr.getScores().iterator();
546     float m = 0f, x = 0f;
547     for (int i = 0; vals.hasNext(); i++)
548     {
549       float val = vals.next().floatValue();
550       if (i == 0)
551       {
552         m = val;
553         x = val;
554       }
555       else
556       {
557         if (m > val)
558         {
559           m = val;
560         }
561         ;
562         if (x < val)
563         {
564           x = val;
565         }
566       }
567       // if we're at a gapped column then skip to next ungapped position
568       if (gapMap != null && gapMap.length > 0)
569       {
570         while (!gapMap[i])
571         {
572           elm[i++] = new Annotation("", "", ' ', Float.NaN);
573         }
574       }
575       elm[i] = new Annotation("", "" + val, ' ', val);
576     }
577
578     annotation.annotations = elm;
579     annotation.belowAlignment = true;
580     if (x < 0)
581     {
582       x = 0;
583     }
584     x += (x - m) * 0.1;
585     annotation.graphMax = x;
586     annotation.graphMin = m;
587     annotation.validateRangeAndDisplay();
588   }
589
590   protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
591   {
592     List<AlignmentAnnotation> our = ourAnnots;
593     ourAnnots = ourAnnot;
594     AlignmentI alignment = alignViewport.getAlignment();
595     if (our != null)
596     {
597       if (our.size() > 0)
598       {
599         for (AlignmentAnnotation an : our)
600         {
601           if (!ourAnnots.contains(an))
602           {
603             // remove the old annotation
604             alignment.deleteAnnotation(an);
605           }
606         }
607       }
608       our.clear();
609
610       ap.adjustAnnotationHeight();
611     }
612   }
613 }