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 // TODO: may not need to paintAlignment again !
376 ap.paintAlignment(false, false);
378 if (msg.length() > 0)
380 // TODO: stash message somewhere in annotation or alignment view.
381 // code below shows result in a text box popup
383 * jalview.gui.CutAndPasteTransfer cap = new
384 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
385 * jalview.gui.Desktop.addInternalFrame(cap,
386 * "Job Status for "+getServiceActionText(), 600, 400);
394 * validate input for dynamic/non-dynamic update context
398 * @return true if input is valid
400 abstract boolean checkValidInputSeqs(boolean dynamic,
401 List<FastaSequence> seqs);
403 abstract String submitToService(
404 List<compbio.data.sequence.FastaSequence> seqs)
405 throws JobSubmissionException;
407 abstract boolean cancelJob(String rslt) throws Exception;
409 abstract JobStatus getJobStatus(String rslt) throws Exception;
411 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
413 abstract boolean collectAnnotationResultsFor(String rslt)
414 throws ResultNotAvailableException;
416 public void cancelCurrentJob()
423 System.err.println("Cancelled job " + id);
427 System.err.println("Job " + id + " couldn't be cancelled.");
429 } catch (Exception q)
436 * Interactive updating. Analysis calculations that work on the currently
437 * displayed alignment data should cancel existing jobs when the input data
440 * @return true if a running job should be cancelled because new input data is
441 * available for analysis
443 abstract boolean isInteractiveUpdate();
445 public List<FastaSequence> getInputSequences(AlignmentI alignment,
446 AnnotatedCollectionI inputSeqs)
448 if (alignment == null || alignment.getWidth() <= 0
449 || alignment.getSequences() == null || alignment.isNucleotide()
450 ? !nucleotidesAllowed
455 if (inputSeqs == null || inputSeqs.getWidth() <= 0
456 || inputSeqs.getSequences() == null
457 || inputSeqs.getSequences().size() < 1)
459 inputSeqs = alignment;
462 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
468 seqNames = new HashMap<>();
470 gapMap = new boolean[0];
471 start = inputSeqs.getStartRes();
472 end = inputSeqs.getEndRes();
474 for (SequenceI sq : (inputSeqs.getSequences()))
477 ? sq.findPosition(end + 1)
478 - sq.findPosition(start + 1) > minlen - 1
479 : sq.getEnd() - sq.getStart() > minlen - 1)
481 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
482 // make new input sequence with or without gaps
483 if (seqNames != null)
485 seqNames.put(newname, sq);
490 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
491 sq.getSequenceAsString()));
492 if (gapMap == null || gapMap.length < seq.getSequence().length())
494 boolean[] tg = gapMap;
495 gapMap = new boolean[seq.getLength()];
496 System.arraycopy(tg, 0, gapMap, 0, tg.length);
497 for (int p = tg.length; p < gapMap.length; p++)
499 gapMap[p] = false; // init as a gap
502 for (int apos : sq.gapMap())
504 char sqc = sq.getCharAt(apos);
505 if (!filterNonStandardResidues
506 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
507 : ResidueProperties.nucleotideIndex[sqc] < 5))
509 gapMap[apos] = true; // aligned and real amino acid residue
516 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
517 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
518 sq.getSequenceAsString(start, end + 1))));
520 if (seq.getSequence().length() > ln)
522 ln = seq.getSequence().length();
526 if (alignedSeqs && submitGaps)
529 for (int i = 0; i < gapMap.length; i++)
536 // try real hard to return something submittable
537 // TODO: some of AAcon measures need a minimum of two or three amino
538 // acids at each position, and AAcon doesn't gracefully degrade.
539 for (int p = 0; p < seqs.size(); p++)
541 FastaSequence sq = seqs.get(p);
542 int l = sq.getSequence().length();
543 // strip gapped columns
544 char[] padded = new char[realw],
545 orig = sq.getSequence().toCharArray();
546 for (int i = 0, pp = 0; i < realw; pp++)
550 if (orig.length > pp)
552 padded[i++] = orig[pp];
560 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
561 new String(padded)));
568 public void updateAnnotation()
570 updateResultAnnotation(false);
573 public abstract void updateResultAnnotation(boolean immediate);
575 public abstract String getServiceActionText();
578 * notify manager that we have started, and wait for a free calculation slot
580 * @return true if slot is obtained and work still valid, false if another
581 * thread has done our work for us.
583 protected boolean checkDone()
585 calcMan.notifyStart(this);
586 ap.paintAlignment(false, false);
587 while (!calcMan.notifyWorking(this))
589 if (calcMan.isWorking(this))
597 ap.paintAlignment(false, false);
601 } catch (Exception ex)
603 ex.printStackTrace();
606 if (alignViewport.isClosed())
614 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
616 List<AlignmentAnnotation> our = ourAnnots;
617 ourAnnots = ourAnnot;
618 AlignmentI alignment = alignViewport.getAlignment();
623 for (AlignmentAnnotation an : our)
625 if (!ourAnnots.contains(an))
627 // remove the old annotation
628 alignment.deleteAnnotation(an);
634 ap.adjustAnnotationHeight();