1 package jalview.ws.jws2;
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;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
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;
36 public abstract class JabawsAlignCalcWorker extends AlignCalcWorker
40 @SuppressWarnings("unchecked")
41 protected SequenceAnnotation aaservice;
43 protected ScoreManager scoremanager;
45 protected WsParamSetI preset;
47 protected List<Argument> arguments;
49 public JabawsAlignCalcWorker(AlignViewportI alignViewport,
50 AlignmentViewPanel alignPanel)
52 super(alignViewport, alignPanel);
55 IProgressIndicator guiProgress;
57 public JabawsAlignCalcWorker(Jws2Instance service, AlignFrame alignFrame,
58 WsParamSetI preset, List<Argument> paramset)
60 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
61 this.guiProgress = alignFrame;
63 this.arguments = paramset;
64 this.service = service;
65 aaservice = (SequenceAnnotation) service.service;
69 public WsParamSetI getPreset()
74 public List<Argument> getArguments()
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.
87 public void updateParameters(final WsParamSetI newpreset,
88 final List<Argument> newarguments)
91 arguments = newarguments;
92 calcMan.startWorker(this);
95 public List<Option> getJabaArguments()
97 List<Option> newargs = new ArrayList<Option>();
98 if (preset != null && preset instanceof JabaWsParamSet)
100 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
102 if (arguments != null && arguments.size() > 0)
104 for (Argument rg : arguments)
106 if (Option.class.isAssignableFrom(rg.getClass()))
108 newargs.add((Option) rg);
118 if (aaservice == null)
122 long progressId = -1;
124 int serverErrorsLeft = 3;
126 String rslt = "JOB NOT DEFINED";
127 StringBuffer msg = new StringBuffer();
134 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(alignViewport
139 calcMan.workerComplete(this);
143 AlignmentAnnotation[] aa = alignViewport.getAlignment()
144 .getAlignmentAnnotation();
145 if (guiProgress != null)
147 guiProgress.setProgressBar("JABA " + getServiceActionText(),
148 progressId = System.currentTimeMillis());
150 if (preset == null && arguments == null)
152 rslt = aaservice.analize(seqs);
158 rslt = aaservice.customAnalize(seqs, getJabaArguments());
159 } catch (WrongParameterException x)
161 throw new JobSubmissionException(
162 "Invalid paremeter set. Check Jalview implementation.", x);
166 boolean finished = false;
170 JobStatus status = aaservice.getJobStatus(rslt);
171 if (status.equals(JobStatus.FINISHED))
175 if (calcMan.isPending(this) && this instanceof AAConsClient)
178 // cancel this job and yield to the new job
181 if (aaservice.cancelJob(rslt))
183 System.err.println("Cancelled AACon job: " + rslt);
187 System.err.println("FAILED TO CANCELL AACon job: " + rslt);
190 } catch (Exception x)
198 ChunkHolder stats = null;
202 boolean retry = false;
207 stats = aaservice.pullExecStatistics(rslt, rpos);
208 } catch (Exception x)
211 if (x.getMessage().contains(
212 "Position in a file could not be negative!"))
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.
222 if (--serverErrorsLeft > 0)
227 } catch (InterruptedException q) {};
236 System.out.print(stats.getChunk());
238 rpos = stats.getNextPosition();
240 } while (stats != null && rpos > cpos);
242 if (!finished && status.equals(JobStatus.FAILED))
247 } catch (InterruptedException x)
253 if (serverErrorsLeft>0)
258 } catch (InterruptedException x)
262 scoremanager = aaservice.getAnnotation(rslt);
263 if (scoremanager != null)
265 jalview.bin.Cache.log
266 .debug("Updating result annotation from Job " + rslt
267 + " at " + service.getUri());
268 updateResultAnnotation(true);
273 catch (JobSubmissionException x)
276 System.err.println("submission error with " + getServiceActionText()
279 calcMan.workerCannotRun(this);
280 } catch (ResultNotAvailableException x)
282 System.err.println("collection error:\nJob ID: " + rslt);
284 calcMan.workerCannotRun(this);
286 } catch (OutOfMemoryError error)
288 calcMan.workerCannotRun(this);
291 // hconsensus = null;
292 ap.raiseOOMWarning(getServiceActionText(), error);
293 } catch (Exception x)
295 calcMan.workerCannotRun(this);
298 // hconsensus = null;
300 .println("Blacklisting worker due to unexpected exception:");
305 calcMan.workerComplete(this);
308 calcMan.workerComplete(this);
309 if (guiProgress != null && progressId != -1)
311 guiProgress.setProgressBar("", progressId);
313 ap.paintAlignment(true);
315 if (msg.length() > 0)
317 // TODO: stash message somewhere in annotation or alignment view.
318 // code below shows result in a text box popup
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);
331 public void updateAnnotation()
333 updateResultAnnotation(false);
336 public abstract void updateResultAnnotation(boolean immediate);
338 public abstract String getServiceActionText();
340 boolean submitGaps = true;
342 boolean alignedSeqs = true;
344 boolean nucleotidesAllowed = false;
346 boolean proteinAllowed = false;
349 * record sequences for mapping result back to afterwards
351 protected boolean bySequence = false;
353 Map<String, SequenceI> seqNames;
359 public List<FastaSequence> getInputSequences(AlignmentI alignment)
361 if (alignment == null || alignment.getWidth() <= 0
362 || alignment.getSequences() == null
363 // || (alignedSeqs && !alignment.isAligned() && !submitGaps)
364 || alignment.isNucleotide() ? !nucleotidesAllowed
369 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
375 seqNames = new HashMap<String, SequenceI>();
377 gapMap = new boolean[0];
378 for (SequenceI sq : ((List<SequenceI>) alignment.getSequences()))
380 if (sq.getEnd() - sq.getStart() > minlen - 1)
382 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
383 // make new input sequence with or without gaps
384 if (seqNames != null)
386 seqNames.put(newname, sq);
391 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
392 sq.getSequenceAsString()));
393 if (gapMap == null || gapMap.length < seq.getSequence().length())
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++)
400 gapMap[p] = false; // init as a gap
403 for (int apos : sq.gapMap())
405 gapMap[apos] = true; // aligned.
410 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
411 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
412 sq.getSequenceAsString())));
414 if (seq.getSequence().length() > ln)
416 ln = seq.getSequence().length();
420 if (alignedSeqs && submitGaps)
423 for (int i = 0; i < gapMap.length; i++)
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++)
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()
440 for (int i = 0, pp = 0; i < realw; pp++)
444 if (orig.length > pp)
446 padded[i++] = orig[pp];
454 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
455 new String(padded)));
462 * notify manager that we have started, and wait for a free calculation slot
464 * @return true if slot is obtained and work still valid, false if another
465 * thread has done our work for us.
469 calcMan.notifyStart(this);
470 ap.paintAlignment(false);
471 while (!calcMan.notifyWorking(this))
473 if (calcMan.isWorking(this))
481 ap.paintAlignment(false);
485 } catch (Exception ex)
487 ex.printStackTrace();
490 if (alignViewport.isClosed())
498 protected void createAnnotationRowsForScores(
499 List<AlignmentAnnotation> ourAnnot, String calcId, int alWidth,
502 // simple annotation row
503 AlignmentAnnotation annotation = alignViewport.getAlignment()
504 .findOrCreateAnnotation(scr.getMethod(), calcId, true, null,
506 if (alWidth == gapMap.length) // scr.getScores().size())
508 constructAnnotationFromScore(annotation, 0, alWidth, scr);
509 ourAnnot.add(annotation);
513 protected AlignmentAnnotation createAnnotationRowsForScores(
514 List<AlignmentAnnotation> ourAnnot, String typeName,
515 String calcId, SequenceI dseq, int base, Score scr)
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);
534 private void constructAnnotationFromScore(AlignmentAnnotation annotation,
535 int base, int alWidth, Score scr)
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++)
542 float val = vals.next().floatValue();
560 // if we're at a gapped column then skip to next ungapped position
561 if (gapMap != null && gapMap.length > 0)
565 elm[i++] = new Annotation("", "", ' ', Float.NaN);
568 elm[i] = new Annotation("", "" + val, ' ', val);
571 annotation.annotations = elm;
572 annotation.belowAlignment = true;
578 annotation.graphMax = x;
579 annotation.graphMin = m;
580 annotation.validateRangeAndDisplay();
583 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
585 List<AlignmentAnnotation> our = ourAnnots;
586 ourAnnots = ourAnnot;
587 AlignmentI alignment = alignViewport.getAlignment();
592 for (AlignmentAnnotation an : our)
594 if (!ourAnnots.contains(an))
596 // remove the old annotation
597 alignment.deleteAnnotation(an);
603 ap.adjustAnnotationHeight();