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.bin.Cache;
8 import jalview.datamodel.AlignmentAnnotation;
9 import jalview.datamodel.AlignmentI;
10 import jalview.datamodel.AnnotatedCollectionI;
11 import jalview.datamodel.SequenceI;
12 import jalview.gui.AlignFrame;
13 import jalview.gui.AlignViewport;
14 import jalview.gui.IProgressIndicator;
15 import jalview.util.Comparison;
16 import jalview.workers.AlignCalcWorker;
17 import jalview.ws.jws2.dm.AAConSettings;
18 import jalview.ws.jws2.dm.JabaWsParamSet;
19 import jalview.ws.jws2.jabaws2.Jws2Instance;
20 import jalview.ws.params.WsParamSetI;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
27 import compbio.data.sequence.FastaSequence;
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;
35 public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
38 protected Jws2Instance service;
40 protected WsParamSetI preset;
42 protected List<Argument> arguments;
44 protected IProgressIndicator guiProgress;
46 protected boolean submitGaps = true;
49 * Recover any existing parameters for this service
51 protected void initViewportParams()
53 if (getCalcId() != null)
55 ((AlignViewport) alignViewport).setCalcIdSettingsFor(
57 new AAConSettings(true, service, this.preset,
58 (arguments != null) ? JabaParamStore
59 .getJwsArgsfromJaba(arguments) : null), true);
65 * @return null or a string used to recover all annotation generated by this
68 public abstract String getCalcId();
70 public WsParamSetI getPreset()
75 public List<Argument> getArguments()
81 * reconfigure and restart the AAConClient. This method will spawn a new
82 * thread that will wait until any current jobs are finished, modify the
83 * parameters and restart the conservation calculation with the new values.
88 public void updateParameters(final WsParamSetI newpreset,
89 final List<Argument> newarguments)
92 arguments = newarguments;
93 calcMan.startWorker(this);
97 public List<Option> getJabaArguments()
99 List<Option> newargs = new ArrayList<Option>();
100 if (preset != null && preset instanceof JabaWsParamSet)
102 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
104 if (arguments != null && arguments.size() > 0)
106 for (Argument rg : arguments)
108 if (Option.class.isAssignableFrom(rg.getClass()))
110 newargs.add((Option) rg);
117 protected boolean alignedSeqs = true;
119 protected boolean nucleotidesAllowed = false;
121 protected boolean proteinAllowed = false;
124 * record sequences for mapping result back to afterwards
126 protected boolean bySequence = false;
128 protected Map<String, SequenceI> seqNames;
130 protected boolean[] gapMap;
138 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
139 AlignmentViewPanel alignPanel)
141 super(alignViewport, alignPanel);
144 public AbstractJabaCalcWorker(Jws2Instance service,
145 AlignFrame alignFrame, WsParamSetI preset, List<Argument> paramset)
147 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
148 this.guiProgress = alignFrame;
149 this.preset = preset;
150 this.arguments = paramset;
151 this.service = service;
156 * @return true if the submission thread should attempt to submit data
158 abstract boolean hasService();
160 volatile String rslt = "JOB NOT DEFINED";
169 long progressId = -1;
171 int serverErrorsLeft = 3;
173 StringBuffer msg = new StringBuffer();
180 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(
181 alignViewport.getAlignment(),
182 bySequence ? alignViewport.getSelectionGroup() : null);
184 if (seqs == null || !checkValidInputSeqs(true, seqs))
186 calcMan.workerComplete(this);
190 AlignmentAnnotation[] aa = alignViewport.getAlignment()
191 .getAlignmentAnnotation();
192 if (guiProgress != null)
194 guiProgress.setProgressBar("JABA " + getServiceActionText(),
195 progressId = System.currentTimeMillis());
197 rslt = submitToService(seqs);
199 boolean finished = false;
203 JobStatus status = getJobStatus(rslt);
204 if (status.equals(JobStatus.FINISHED))
208 if (calcMan.isPending(this) && isInteractiveUpdate())
211 // cancel this job and yield to the new job
216 System.err.println("Cancelled AACon job: " + rslt);
220 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
223 } catch (Exception x)
227 rslt = "CANCELLED JOB";
231 ChunkHolder stats = null;
235 boolean retry = false;
240 stats = pullExecStatistics(rslt, rpos);
241 } catch (Exception x)
244 if (x.getMessage().contains(
245 "Position in a file could not be negative!"))
247 // squash index out of bounds exception- seems to happen for
248 // disorder predictors which don't (apparently) produce any
249 // progress information and JABA server throws an exception
250 // because progress length is -1.
255 if (--serverErrorsLeft > 0)
261 } catch (InterruptedException q)
275 System.out.print(stats.getChunk());
277 rpos = stats.getNextPosition();
279 } while (stats != null && rpos > cpos);
281 if (!finished && status.equals(JobStatus.FAILED))
286 } catch (InterruptedException x)
292 if (serverErrorsLeft > 0)
297 } catch (InterruptedException x)
300 if (collectAnnotationResultsFor(rslt))
303 .debug("Updating result annotation from Job " + rslt
304 + " at " + service.getUri());
305 updateResultAnnotation(true);
306 ap.adjustAnnotationHeight();
311 catch (JobSubmissionException x)
314 System.err.println("submission error with " + getServiceActionText()
317 calcMan.workerCannotRun(this);
318 } catch (ResultNotAvailableException x)
320 System.err.println("collection error:\nJob ID: " + rslt);
322 calcMan.workerCannotRun(this);
324 } catch (OutOfMemoryError error)
326 calcMan.workerCannotRun(this);
329 // hconsensus = null;
330 ap.raiseOOMWarning(getServiceActionText(), error);
331 } catch (Exception x)
333 calcMan.workerCannotRun(this);
336 // hconsensus = null;
338 .println("Blacklisting worker due to unexpected exception:");
343 calcMan.workerComplete(this);
346 calcMan.workerComplete(this);
347 if (guiProgress != null && progressId != -1)
349 guiProgress.setProgressBar("", progressId);
351 ap.paintAlignment(true);
353 if (msg.length() > 0)
355 // TODO: stash message somewhere in annotation or alignment view.
356 // code below shows result in a text box popup
358 * jalview.gui.CutAndPasteTransfer cap = new
359 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
360 * jalview.gui.Desktop.addInternalFrame(cap,
361 * "Job Status for "+getServiceActionText(), 600, 400);
369 * validate input for dynamic/non-dynamic update context
372 * @return true if input is valid
374 abstract boolean checkValidInputSeqs(boolean dynamic, List<FastaSequence> seqs);
376 abstract String submitToService(
377 List<compbio.data.sequence.FastaSequence> seqs)
378 throws JobSubmissionException;
380 abstract boolean cancelJob(String rslt) throws Exception;
382 abstract JobStatus getJobStatus(String rslt) throws Exception;
384 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
386 abstract boolean collectAnnotationResultsFor(String rslt)
387 throws ResultNotAvailableException;
389 public void cancelCurrentJob()
396 System.err.println("Cancelled job "+id);
400 System.err.println("Job "+id+" couldn't be cancelled.");
402 } catch (Exception q)
409 * Interactive updating. Analysis calculations that work on the currently
410 * displayed alignment data should cancel existing jobs when the input data
413 * @return true if a running job should be cancelled because new input data is
414 * available for analysis
416 abstract boolean isInteractiveUpdate();
418 public List<FastaSequence> getInputSequences(AlignmentI alignment,
419 AnnotatedCollectionI inputSeqs)
421 if (alignment == null || alignment.getWidth() <= 0
422 || alignment.getSequences() == null || alignment.isNucleotide() ? !nucleotidesAllowed
427 if (inputSeqs == null || inputSeqs.getWidth() <= 0
428 || inputSeqs.getSequences() == null
429 || inputSeqs.getSequences().size() < 1)
431 inputSeqs = alignment;
434 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
440 seqNames = new HashMap<String, SequenceI>();
442 gapMap = new boolean[0];
443 start = inputSeqs.getStartRes();
444 end = inputSeqs.getEndRes();
446 for (SequenceI sq : (inputSeqs.getSequences()))
448 if (bySequence ? sq.findPosition(end + 1)
449 - sq.findPosition(start + 1) > minlen - 1 : sq.getEnd()
450 - sq.getStart() > minlen - 1)
452 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
453 // make new input sequence with or without gaps
454 if (seqNames != null)
456 seqNames.put(newname, sq);
461 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
462 sq.getSequenceAsString()));
463 if (gapMap == null || gapMap.length < seq.getSequence().length())
465 boolean[] tg = gapMap;
466 gapMap = new boolean[seq.getLength()];
467 System.arraycopy(tg, 0, gapMap, 0, tg.length);
468 for (int p = tg.length; p < gapMap.length; p++)
470 gapMap[p] = false; // init as a gap
473 for (int apos : sq.gapMap())
475 gapMap[apos] = true; // aligned.
480 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
481 AlignSeq.extractGaps(Comparison.GapChars,
482 sq.getSequenceAsString(start, end + 1))));
484 if (seq.getSequence().length() > ln)
486 ln = seq.getSequence().length();
490 if (alignedSeqs && submitGaps)
493 for (int i = 0; i < gapMap.length; i++)
500 // try real hard to return something submittable
501 // TODO: some of AAcon measures need a minimum of two or three amino
502 // acids at each position, and AAcon doesn't gracefully degrade.
503 for (int p = 0; p < seqs.size(); p++)
505 FastaSequence sq = seqs.get(p);
506 int l = sq.getSequence().length();
507 // strip gapped columns
508 char[] padded = new char[realw], orig = sq.getSequence()
510 for (int i = 0, pp = 0; i < realw; pp++)
514 if (orig.length > pp)
516 padded[i++] = orig[pp];
524 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
525 new String(padded)));
532 public void updateAnnotation()
534 updateResultAnnotation(false);
537 public abstract void updateResultAnnotation(boolean immediate);
539 public abstract String getServiceActionText();
542 * notify manager that we have started, and wait for a free calculation slot
544 * @return true if slot is obtained and work still valid, false if another
545 * thread has done our work for us.
547 protected boolean checkDone()
549 calcMan.notifyStart(this);
550 ap.paintAlignment(false);
551 while (!calcMan.notifyWorking(this))
553 if (calcMan.isWorking(this))
561 ap.paintAlignment(false);
565 } catch (Exception ex)
567 ex.printStackTrace();
570 if (alignViewport.isClosed())
578 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
580 List<AlignmentAnnotation> our = ourAnnots;
581 ourAnnots = ourAnnot;
582 AlignmentI alignment = alignViewport.getAlignment();
587 for (AlignmentAnnotation an : our)
589 if (!ourAnnots.contains(an))
591 // remove the old annotation
592 alignment.deleteAnnotation(an);
598 ap.adjustAnnotationHeight();