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);
269 ap.adjustAnnotationHeight();
274 catch (JobSubmissionException x)
277 System.err.println("submission error with " + getServiceActionText()
280 calcMan.workerCannotRun(this);
281 } catch (ResultNotAvailableException x)
283 System.err.println("collection error:\nJob ID: " + rslt);
285 calcMan.workerCannotRun(this);
287 } catch (OutOfMemoryError error)
289 calcMan.workerCannotRun(this);
292 // hconsensus = null;
293 ap.raiseOOMWarning(getServiceActionText(), error);
294 } catch (Exception x)
296 calcMan.workerCannotRun(this);
299 // hconsensus = null;
301 .println("Blacklisting worker due to unexpected exception:");
306 calcMan.workerComplete(this);
309 calcMan.workerComplete(this);
310 if (guiProgress != null && progressId != -1)
312 guiProgress.setProgressBar("", progressId);
314 ap.paintAlignment(true);
316 if (msg.length() > 0)
318 // TODO: stash message somewhere in annotation or alignment view.
319 // code below shows result in a text box popup
321 * jalview.gui.CutAndPasteTransfer cap = new
322 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
323 * jalview.gui.Desktop.addInternalFrame(cap,
324 * "Job Status for "+getServiceActionText(), 600, 400);
332 public void updateAnnotation()
334 updateResultAnnotation(false);
337 public abstract void updateResultAnnotation(boolean immediate);
339 public abstract String getServiceActionText();
341 boolean submitGaps = true;
343 boolean alignedSeqs = true;
345 boolean nucleotidesAllowed = false;
347 boolean proteinAllowed = false;
350 * record sequences for mapping result back to afterwards
352 protected boolean bySequence = false;
354 Map<String, SequenceI> seqNames;
360 public List<FastaSequence> getInputSequences(AlignmentI alignment)
362 if (alignment == null || alignment.getWidth() <= 0
363 || alignment.getSequences() == null
364 // || (alignedSeqs && !alignment.isAligned() && !submitGaps)
365 || alignment.isNucleotide() ? !nucleotidesAllowed
370 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
376 seqNames = new HashMap<String, SequenceI>();
378 gapMap = new boolean[0];
379 for (SequenceI sq : ((List<SequenceI>) alignment.getSequences()))
381 if (sq.getEnd() - sq.getStart() > minlen - 1)
383 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
384 // make new input sequence with or without gaps
385 if (seqNames != null)
387 seqNames.put(newname, sq);
392 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
393 sq.getSequenceAsString()));
394 if (gapMap == null || gapMap.length < seq.getSequence().length())
396 boolean[] tg = gapMap;
397 gapMap = new boolean[seq.getLength()];
398 System.arraycopy(tg, 0, gapMap, 0, tg.length);
399 for (int p = tg.length; p < gapMap.length; p++)
401 gapMap[p] = false; // init as a gap
404 for (int apos : sq.gapMap())
406 gapMap[apos] = true; // aligned.
411 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
412 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
413 sq.getSequenceAsString())));
415 if (seq.getSequence().length() > ln)
417 ln = seq.getSequence().length();
421 if (alignedSeqs && submitGaps)
424 for (int i = 0; i < gapMap.length; i++)
431 // try real hard to return something submittable
432 // TODO: some of AAcons measures need a minimum of two or three amino
433 // acids at each position, and aacons doesn't gracefully degrade.
434 for (int p = 0; p < seqs.size(); p++)
436 FastaSequence sq = seqs.get(p);
437 int l = sq.getSequence().length();
438 // strip gapped columns
439 char[] padded = new char[realw], orig = sq.getSequence()
441 for (int i = 0, pp = 0; i < realw; pp++)
445 if (orig.length > pp)
447 padded[i++] = orig[pp];
455 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
456 new String(padded)));
463 * notify manager that we have started, and wait for a free calculation slot
465 * @return true if slot is obtained and work still valid, false if another
466 * thread has done our work for us.
470 calcMan.notifyStart(this);
471 ap.paintAlignment(false);
472 while (!calcMan.notifyWorking(this))
474 if (calcMan.isWorking(this))
482 ap.paintAlignment(false);
486 } catch (Exception ex)
488 ex.printStackTrace();
491 if (alignViewport.isClosed())
499 protected void createAnnotationRowsForScores(
500 List<AlignmentAnnotation> ourAnnot, String calcId, int alWidth,
503 // simple annotation row
504 AlignmentAnnotation annotation = alignViewport.getAlignment()
505 .findOrCreateAnnotation(scr.getMethod(), calcId, true, null,
507 if (alWidth == gapMap.length) // scr.getScores().size())
509 constructAnnotationFromScore(annotation, 0, alWidth, scr);
510 ourAnnot.add(annotation);
514 protected AlignmentAnnotation createAnnotationRowsForScores(
515 List<AlignmentAnnotation> ourAnnot, String typeName,
516 String calcId, SequenceI dseq, int base, Score scr)
518 System.out.println("Creating annotation on dseq:" + dseq.getStart()
519 + " base is " + base + " and length=" + dseq.getLength()
520 + " == " + scr.getScores().size());
521 // AlignmentAnnotation annotation = new AlignmentAnnotation(
522 // scr.getMethod(), typeName, new Annotation[]
523 // {}, 0, -1, AlignmentAnnotation.LINE_GRAPH);
524 // annotation.setCalcId(calcId);
525 AlignmentAnnotation annotation = alignViewport.getAlignment()
526 .findOrCreateAnnotation(typeName, calcId, false, dseq, null);
527 constructAnnotationFromScore(annotation, 0, dseq.getLength(), scr);
528 annotation.createSequenceMapping(dseq, base, false);
529 annotation.adjustForAlignment();
530 dseq.addAlignmentAnnotation(annotation);
531 ourAnnot.add(annotation);
535 private void constructAnnotationFromScore(AlignmentAnnotation annotation,
536 int base, int alWidth, Score scr)
538 Annotation[] elm = new Annotation[alWidth];
539 Iterator<Float> vals = scr.getScores().iterator();
540 float m = 0f, x = 0f;
541 for (int i = 0; vals.hasNext(); i++)
543 float val = vals.next().floatValue();
561 // if we're at a gapped column then skip to next ungapped position
562 if (gapMap != null && gapMap.length > 0)
566 elm[i++] = new Annotation("", "", ' ', Float.NaN);
569 elm[i] = new Annotation("", "" + val, ' ', val);
572 annotation.annotations = elm;
573 annotation.belowAlignment = true;
579 annotation.graphMax = x;
580 annotation.graphMin = m;
581 annotation.validateRangeAndDisplay();
584 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
586 List<AlignmentAnnotation> our = ourAnnots;
587 ourAnnots = ourAnnot;
588 AlignmentI alignment = alignViewport.getAlignment();
593 for (AlignmentAnnotation an : our)
595 if (!ourAnnots.contains(an))
597 // remove the old annotation
598 alignment.deleteAnnotation(an);
604 ap.adjustAnnotationHeight();