2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ws.jws2;
23 import jalview.analysis.AlignSeq;
24 import jalview.analysis.SeqsetUtils;
25 import jalview.api.AlignViewportI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.AnnotatedCollectionI;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.AlignFrame;
32 import jalview.gui.IProgressIndicator;
33 import jalview.schemes.ResidueProperties;
34 import jalview.workers.AlignCalcWorker;
35 import jalview.ws.jws2.dm.AAConSettings;
36 import jalview.ws.jws2.dm.JabaWsParamSet;
37 import jalview.ws.jws2.jabaws2.Jws2Instance;
38 import jalview.ws.params.WsParamSetI;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.List;
45 import compbio.data.sequence.FastaSequence;
46 import compbio.metadata.Argument;
47 import compbio.metadata.ChunkHolder;
48 import compbio.metadata.JobStatus;
49 import compbio.metadata.JobSubmissionException;
50 import compbio.metadata.Option;
51 import compbio.metadata.ResultNotAvailableException;
53 public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
56 protected Jws2Instance service;
58 protected WsParamSetI preset;
60 protected List<Argument> arguments;
62 protected IProgressIndicator guiProgress;
64 protected boolean submitGaps = true;
67 * by default, we filter out non-standard residues before submission
69 protected boolean filterNonStandardResidues = true;
72 * Recover any existing parameters for this service
74 protected void initViewportParams()
76 if (getCalcId() != null)
78 ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
80 new AAConSettings(true, service, this.preset,
82 ? JabaParamStore.getJwsArgsfromJaba(arguments)
90 * @return null or a string used to recover all annotation generated by this
93 public abstract String getCalcId();
95 public WsParamSetI getPreset()
100 public List<Argument> getArguments()
106 * reconfigure and restart the AAConClient. This method will spawn a new
107 * thread that will wait until any current jobs are finished, modify the
108 * parameters and restart the conservation calculation with the new values.
111 * @param newarguments
113 public void updateParameters(final WsParamSetI newpreset,
114 final List<Argument> newarguments)
117 arguments = newarguments;
118 calcMan.startWorker(this);
119 initViewportParams();
122 public List<Option> getJabaArguments()
124 List<Option> newargs = new ArrayList<>();
125 if (preset != null && preset instanceof JabaWsParamSet)
127 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
129 if (arguments != null && arguments.size() > 0)
131 for (Argument rg : arguments)
133 if (Option.class.isAssignableFrom(rg.getClass()))
135 newargs.add((Option) rg);
142 protected boolean alignedSeqs = true;
144 protected boolean nucleotidesAllowed = false;
146 protected boolean proteinAllowed = false;
149 * record sequences for mapping result back to afterwards
151 protected boolean bySequence = false;
153 protected Map<String, SequenceI> seqNames;
155 protected boolean[] gapMap;
163 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
164 AlignmentViewPanel alignPanel)
166 super(alignViewport, alignPanel);
169 public AbstractJabaCalcWorker(Jws2Instance service, AlignFrame alignFrame,
170 WsParamSetI preset, List<Argument> paramset)
172 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
173 this.guiProgress = alignFrame;
174 this.preset = preset;
175 this.arguments = paramset;
176 this.service = service;
181 * @return true if the submission thread should attempt to submit data
183 abstract boolean hasService();
185 volatile String rslt = "JOB NOT DEFINED";
194 long progressId = -1;
196 int serverErrorsLeft = 3;
198 StringBuffer msg = new StringBuffer();
205 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(
206 alignViewport.getAlignment(),
207 bySequence ? alignViewport.getSelectionGroup() : null);
209 if (seqs == null || !checkValidInputSeqs(true, seqs))
211 calcMan.workerComplete(this);
215 AlignmentAnnotation[] aa = alignViewport.getAlignment()
216 .getAlignmentAnnotation();
217 if (guiProgress != null)
219 guiProgress.setProgressBar("JABA " + getServiceActionText(),
220 progressId = System.currentTimeMillis());
222 rslt = submitToService(seqs);
224 boolean finished = false;
228 JobStatus status = getJobStatus(rslt);
229 if (status.equals(JobStatus.FINISHED))
233 if (calcMan.isPending(this) && isInteractiveUpdate())
236 // cancel this job and yield to the new job
241 System.err.println("Cancelled AACon job: " + rslt);
245 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
248 } catch (Exception x)
252 rslt = "CANCELLED JOB";
256 ChunkHolder stats = null;
260 boolean retry = false;
265 stats = pullExecStatistics(rslt, rpos);
266 } catch (Exception x)
269 if (x.getMessage().contains(
270 "Position in a file could not be negative!"))
272 // squash index out of bounds exception- seems to happen for
273 // disorder predictors which don't (apparently) produce any
274 // progress information and JABA server throws an exception
275 // because progress length is -1.
280 if (--serverErrorsLeft > 0)
286 } catch (InterruptedException q)
300 System.out.print(stats.getChunk());
302 rpos = stats.getNextPosition();
304 } while (stats != null && rpos > cpos);
306 if (!finished && status.equals(JobStatus.FAILED))
311 } catch (InterruptedException x)
317 if (serverErrorsLeft > 0)
322 } catch (InterruptedException x)
325 if (collectAnnotationResultsFor(rslt))
327 jalview.bin.Cache.log.debug("Updating result annotation from Job "
328 + rslt + " at " + service.getUri());
329 updateResultAnnotation(true);
330 ap.adjustAnnotationHeight();
335 catch (JobSubmissionException x)
339 "submission error with " + getServiceActionText() + " :");
341 calcMan.disableWorker(this);
342 } catch (ResultNotAvailableException x)
344 System.err.println("collection error:\nJob ID: " + rslt);
346 calcMan.disableWorker(this);
348 } catch (OutOfMemoryError error)
350 calcMan.disableWorker(this);
353 // hconsensus = null;
354 ap.raiseOOMWarning(getServiceActionText(), error);
355 } catch (Exception x)
357 calcMan.disableWorker(this);
360 // hconsensus = null;
362 .println("Blacklisting worker due to unexpected exception:");
367 calcMan.workerComplete(this);
370 calcMan.workerComplete(this);
371 if (guiProgress != null && progressId != -1)
373 guiProgress.setProgressBar("", progressId);
375 ap.paintAlignment(true);
377 if (msg.length() > 0)
379 // TODO: stash message somewhere in annotation or alignment view.
380 // code below shows result in a text box popup
382 * jalview.gui.CutAndPasteTransfer cap = new
383 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
384 * jalview.gui.Desktop.addInternalFrame(cap,
385 * "Job Status for "+getServiceActionText(), 600, 400);
393 * validate input for dynamic/non-dynamic update context
397 * @return true if input is valid
399 abstract boolean checkValidInputSeqs(boolean dynamic,
400 List<FastaSequence> seqs);
402 abstract String submitToService(
403 List<compbio.data.sequence.FastaSequence> seqs)
404 throws JobSubmissionException;
406 abstract boolean cancelJob(String rslt) throws Exception;
408 abstract JobStatus getJobStatus(String rslt) throws Exception;
410 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
412 abstract boolean collectAnnotationResultsFor(String rslt)
413 throws ResultNotAvailableException;
415 public void cancelCurrentJob()
422 System.err.println("Cancelled job " + id);
426 System.err.println("Job " + id + " couldn't be cancelled.");
428 } catch (Exception q)
435 * Interactive updating. Analysis calculations that work on the currently
436 * displayed alignment data should cancel existing jobs when the input data
439 * @return true if a running job should be cancelled because new input data is
440 * available for analysis
442 abstract boolean isInteractiveUpdate();
444 public List<FastaSequence> getInputSequences(AlignmentI alignment,
445 AnnotatedCollectionI inputSeqs)
447 if (alignment == null || alignment.getWidth() <= 0
448 || alignment.getSequences() == null || alignment.isNucleotide()
449 ? !nucleotidesAllowed
454 if (inputSeqs == null || inputSeqs.getWidth() <= 0
455 || inputSeqs.getSequences() == null
456 || inputSeqs.getSequences().size() < 1)
458 inputSeqs = alignment;
461 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
467 seqNames = new HashMap<>();
469 gapMap = new boolean[0];
470 start = inputSeqs.getStartRes();
471 end = inputSeqs.getEndRes();
473 for (SequenceI sq : (inputSeqs.getSequences()))
476 ? sq.findPosition(end + 1)
477 - sq.findPosition(start + 1) > minlen - 1
478 : sq.getEnd() - sq.getStart() > minlen - 1)
480 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
481 // make new input sequence with or without gaps
482 if (seqNames != null)
484 seqNames.put(newname, sq);
489 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
490 sq.getSequenceAsString()));
491 if (gapMap == null || gapMap.length < seq.getSequence().length())
493 boolean[] tg = gapMap;
494 gapMap = new boolean[seq.getLength()];
495 System.arraycopy(tg, 0, gapMap, 0, tg.length);
496 for (int p = tg.length; p < gapMap.length; p++)
498 gapMap[p] = false; // init as a gap
501 for (int apos : sq.gapMap())
503 char sqc = sq.getCharAt(apos);
504 if (!filterNonStandardResidues
505 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
506 : ResidueProperties.nucleotideIndex[sqc] < 5))
508 gapMap[apos] = true; // aligned and real amino acid residue
515 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
516 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
517 sq.getSequenceAsString(start, end + 1))));
519 if (seq.getSequence().length() > ln)
521 ln = seq.getSequence().length();
525 if (alignedSeqs && submitGaps)
528 for (int i = 0; i < gapMap.length; i++)
535 // try real hard to return something submittable
536 // TODO: some of AAcon measures need a minimum of two or three amino
537 // acids at each position, and AAcon doesn't gracefully degrade.
538 for (int p = 0; p < seqs.size(); p++)
540 FastaSequence sq = seqs.get(p);
541 int l = sq.getSequence().length();
542 // strip gapped columns
543 char[] padded = new char[realw],
544 orig = sq.getSequence().toCharArray();
545 for (int i = 0, pp = 0; i < realw; pp++)
549 if (orig.length > pp)
551 padded[i++] = orig[pp];
559 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
560 new String(padded)));
567 public void updateAnnotation()
569 updateResultAnnotation(false);
572 public abstract void updateResultAnnotation(boolean immediate);
574 public abstract String getServiceActionText();
577 * notify manager that we have started, and wait for a free calculation slot
579 * @return true if slot is obtained and work still valid, false if another
580 * thread has done our work for us.
582 protected boolean checkDone()
584 calcMan.notifyStart(this);
585 ap.paintAlignment(false);
586 while (!calcMan.notifyWorking(this))
588 if (calcMan.isWorking(this))
596 ap.paintAlignment(false);
600 } catch (Exception ex)
602 ex.printStackTrace();
605 if (alignViewport.isClosed())
613 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
615 List<AlignmentAnnotation> our = ourAnnots;
616 ourAnnots = ourAnnot;
617 AlignmentI alignment = alignViewport.getAlignment();
622 for (AlignmentAnnotation an : our)
624 if (!ourAnnots.contains(an))
626 // remove the old annotation
627 alignment.deleteAnnotation(an);
633 ap.adjustAnnotationHeight();