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 java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
28 import compbio.data.sequence.FastaSequence;
29 import compbio.metadata.Argument;
30 import compbio.metadata.ChunkHolder;
31 import compbio.metadata.JobStatus;
32 import compbio.metadata.JobSubmissionException;
33 import compbio.metadata.Option;
34 import compbio.metadata.ResultNotAvailableException;
35 import jalview.analysis.AlignSeq;
36 import jalview.analysis.SeqsetUtils;
37 import jalview.api.AlignViewportI;
38 import jalview.api.AlignmentViewPanel;
39 import jalview.bin.Console;
40 import jalview.datamodel.AlignmentAnnotation;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.AnnotatedCollectionI;
43 import jalview.datamodel.SequenceI;
44 import jalview.gui.AlignFrame;
45 import jalview.gui.IProgressIndicator;
46 import jalview.gui.IProgressIndicatorHandler;
47 import jalview.schemes.ResidueProperties;
48 import jalview.util.IdUtils;
49 import jalview.util.IdUtils.IdType;
50 import jalview.workers.AlignCalcWorker;
51 import jalview.ws.jws2.dm.AAConSettings;
52 import jalview.ws.jws2.dm.JabaWsParamSet;
53 import jalview.ws.jws2.jabaws2.Jws2Instance;
54 import jalview.ws.params.WsParamSetI;
56 public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
59 protected Jws2Instance service;
61 protected WsParamSetI preset;
63 protected List<Argument> arguments;
65 protected IProgressIndicator guiProgress;
67 protected boolean submitGaps = true;
70 * by default, we filter out non-standard residues before submission
72 protected boolean filterNonStandardResidues = true;
75 * Recover any existing parameters for this service
77 protected void initViewportParams()
79 if (getCalcId() != null)
81 ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
83 new AAConSettings(true, service, this.preset,
85 ? JabaParamStore.getJwsArgsfromJaba(arguments)
93 * @return null or a string used to recover all annotation generated by this
96 public abstract String getCalcId();
98 public WsParamSetI getPreset()
103 public List<Argument> getArguments()
109 * reconfigure and restart the AAConClient. This method will spawn a new
110 * thread that will wait until any current jobs are finished, modify the
111 * parameters and restart the conservation calculation with the new values.
114 * @param newarguments
116 public void updateParameters(final WsParamSetI newpreset,
117 final List<Argument> newarguments)
120 arguments = newarguments;
121 calcMan.startWorker(this);
122 initViewportParams();
125 public List<Option> getJabaArguments()
127 List<Option> newargs = new ArrayList<>();
128 if (preset != null && preset instanceof JabaWsParamSet)
130 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
132 if (arguments != null && arguments.size() > 0)
134 for (Argument rg : arguments)
136 if (Option.class.isAssignableFrom(rg.getClass()))
138 newargs.add((Option) rg);
145 protected boolean alignedSeqs = true;
147 protected boolean nucleotidesAllowed = false;
149 protected boolean proteinAllowed = false;
152 * record sequences for mapping result back to afterwards
154 protected boolean bySequence = false;
156 protected Map<String, SequenceI> seqNames;
158 protected boolean[] gapMap;
166 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
167 AlignmentViewPanel alignPanel)
169 super(alignViewport, alignPanel);
172 public AbstractJabaCalcWorker(Jws2Instance service, AlignFrame alignFrame,
173 WsParamSetI preset, List<Argument> paramset)
175 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
176 this.guiProgress = alignFrame;
177 this.preset = preset;
178 this.arguments = paramset;
179 this.service = service;
184 * @return true if the submission thread should attempt to submit data
186 abstract boolean hasService();
188 volatile String rslt = "JOB NOT DEFINED";
197 long progressId = -1;
199 int serverErrorsLeft = 3;
201 StringBuffer msg = new StringBuffer();
208 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(
209 alignViewport.getAlignment(),
210 bySequence ? alignViewport.getSelectionGroup() : null);
212 if (seqs == null || !checkValidInputSeqs(true, seqs))
214 calcMan.workerComplete(this);
218 AlignmentAnnotation[] aa = alignViewport.getAlignment()
219 .getAlignmentAnnotation();
220 if (guiProgress != null)
222 guiProgress.setProgressBar("JABA " + getServiceActionText(),
223 progressId = IdUtils.newId(IdType.PROGRESS));
225 rslt = submitToService(seqs);
226 if (guiProgress != null)
228 guiProgress.registerHandler(progressId,
229 new IProgressIndicatorHandler()
233 public boolean cancelActivity(long id)
240 public boolean canCancel()
246 boolean finished = false;
250 JobStatus status = getJobStatus(rslt);
251 if (status.equals(JobStatus.FINISHED))
255 if (calcMan.isPending(this) && isInteractiveUpdate())
258 // cancel this job and yield to the new job
264 .errPrintln("Cancelled AACon job: " + rslt);
269 .errPrintln("FAILED TO CANCEL AACon job: " + rslt);
272 } catch (Exception x)
276 rslt = "CANCELLED JOB";
280 ChunkHolder stats = null;
284 boolean retry = false;
289 stats = pullExecStatistics(rslt, rpos);
290 } catch (Exception x)
293 if (x.getMessage().contains(
294 "Position in a file could not be negative!"))
296 // squash index out of bounds exception- seems to happen for
297 // disorder predictors which don't (apparently) produce any
298 // progress information and JABA server throws an exception
299 // because progress length is -1.
304 if (--serverErrorsLeft > 0)
310 } catch (InterruptedException q)
324 System.out.print(stats.getChunk());
326 rpos = stats.getNextPosition();
328 } while (stats != null && rpos > cpos);
330 if (!finished && status.equals(JobStatus.FAILED))
335 } catch (InterruptedException x)
341 if (serverErrorsLeft > 0)
346 } catch (InterruptedException x)
349 if (collectAnnotationResultsFor(rslt))
351 Console.debug("Updating result annotation from Job " + rslt
352 + " at " + service.getUri());
353 updateResultAnnotation(true);
354 ap.adjustAnnotationHeight();
359 catch (JobSubmissionException x)
362 jalview.bin.Console.errPrintln(
363 "submission error with " + getServiceActionText() + " :");
365 calcMan.disableWorker(this);
366 } catch (ResultNotAvailableException x)
368 jalview.bin.Console.errPrintln("collection error:\nJob ID: " + rslt);
370 calcMan.disableWorker(this);
372 } catch (OutOfMemoryError error)
374 calcMan.disableWorker(this);
377 // hconsensus = null;
378 ap.raiseOOMWarning(getServiceActionText(), error);
379 } catch (Exception x)
381 calcMan.disableWorker(this);
384 // hconsensus = null;
386 .println("Blacklisting worker due to unexpected exception:");
391 calcMan.workerComplete(this);
394 calcMan.workerComplete(this);
395 if (guiProgress != null && progressId != -1)
397 guiProgress.setProgressBar("", progressId);
399 // TODO: may not need to paintAlignment again !
400 ap.paintAlignment(false, false);
402 if (msg.length() > 0)
404 // TODO: stash message somewhere in annotation or alignment view.
405 // code below shows result in a text box popup
407 * jalview.gui.CutAndPasteTransfer cap = new
408 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
409 * jalview.gui.Desktop.addInternalFrame(cap,
410 * "Job Status for "+getServiceActionText(), 600, 400);
418 * validate input for dynamic/non-dynamic update context
422 * @return true if input is valid
424 abstract boolean checkValidInputSeqs(boolean dynamic,
425 List<FastaSequence> seqs);
427 abstract String submitToService(
428 List<compbio.data.sequence.FastaSequence> seqs)
429 throws JobSubmissionException;
431 abstract boolean cancelJob(String rslt) throws Exception;
433 abstract JobStatus getJobStatus(String rslt) throws Exception;
435 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
437 abstract boolean collectAnnotationResultsFor(String rslt)
438 throws ResultNotAvailableException;
440 public void cancelCurrentJob()
447 jalview.bin.Console.errPrintln("Cancelled job " + id);
452 .errPrintln("Job " + id + " couldn't be cancelled.");
454 } catch (Exception q)
461 * Interactive updating. Analysis calculations that work on the currently
462 * displayed alignment data should cancel existing jobs when the input data
465 * @return true if a running job should be cancelled because new input data is
466 * available for analysis
468 abstract boolean isInteractiveUpdate();
470 public List<FastaSequence> getInputSequences(AlignmentI alignment,
471 AnnotatedCollectionI inputSeqs)
473 if (alignment == null || alignment.getWidth() <= 0
474 || alignment.getSequences() == null || alignment.isNucleotide()
475 ? !nucleotidesAllowed
480 if (inputSeqs == null || inputSeqs.getWidth() <= 0
481 || inputSeqs.getSequences() == null
482 || inputSeqs.getSequences().size() < 1)
484 inputSeqs = alignment;
487 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
493 seqNames = new HashMap<>();
495 gapMap = new boolean[0];
496 start = inputSeqs.getStartRes();
497 end = inputSeqs.getEndRes();
499 for (SequenceI sq : (inputSeqs.getSequences()))
502 ? sq.findPosition(end + 1)
503 - sq.findPosition(start + 1) > minlen - 1
504 : sq.getEnd() - sq.getStart() > minlen - 1)
506 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
507 // make new input sequence with or without gaps
508 if (seqNames != null)
510 seqNames.put(newname, sq);
515 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
516 sq.getSequenceAsString()));
517 if (gapMap == null || gapMap.length < seq.getSequence().length())
519 boolean[] tg = gapMap;
520 gapMap = new boolean[seq.getLength()];
521 System.arraycopy(tg, 0, gapMap, 0, tg.length);
522 for (int p = tg.length; p < gapMap.length; p++)
524 gapMap[p] = false; // init as a gap
527 for (int apos : sq.gapMap())
529 char sqc = sq.getCharAt(apos);
530 if (!filterNonStandardResidues
531 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
532 : ResidueProperties.nucleotideIndex[sqc] < 5))
534 gapMap[apos] = true; // aligned and real amino acid residue
541 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
542 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
543 sq.getSequenceAsString(start, end + 1))));
545 if (seq.getSequence().length() > ln)
547 ln = seq.getSequence().length();
551 if (alignedSeqs && submitGaps)
554 for (int i = 0; i < gapMap.length; i++)
561 // try real hard to return something submittable
562 // TODO: some of AAcon measures need a minimum of two or three amino
563 // acids at each position, and AAcon doesn't gracefully degrade.
564 for (int p = 0; p < seqs.size(); p++)
566 FastaSequence sq = seqs.get(p);
567 int l = sq.getSequence().length();
568 // strip gapped columns
569 char[] padded = new char[realw],
570 orig = sq.getSequence().toCharArray();
571 for (int i = 0, pp = 0; i < realw; pp++)
575 if (orig.length > pp)
577 padded[i++] = orig[pp];
585 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
586 new String(padded)));
593 public void updateAnnotation()
595 updateResultAnnotation(false);
598 public abstract void updateResultAnnotation(boolean immediate);
600 public abstract String getServiceActionText();
603 * notify manager that we have started, and wait for a free calculation slot
605 * @return true if slot is obtained and work still valid, false if another
606 * thread has done our work for us.
608 protected boolean checkDone()
610 calcMan.notifyStart(this);
611 ap.paintAlignment(false, false);
612 while (!calcMan.notifyWorking(this))
614 if (calcMan.isWorking(this))
622 ap.paintAlignment(false, false);
626 } catch (Exception ex)
628 ex.printStackTrace();
631 if (alignViewport.isClosed())
639 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
641 List<AlignmentAnnotation> our = ourAnnots;
642 ourAnnots = ourAnnot;
643 AlignmentI alignment = alignViewport.getAlignment();
648 for (AlignmentAnnotation an : our)
650 if (!ourAnnots.contains(an))
652 // remove the old annotation
653 alignment.deleteAnnotation(an);
659 ap.adjustAnnotationHeight();