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.bin.Console;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.AnnotatedCollectionI;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.AlignFrame;
33 import jalview.gui.IProgressIndicator;
34 import jalview.gui.IProgressIndicatorHandler;
35 import jalview.schemes.ResidueProperties;
36 import jalview.workers.AlignCalcWorker;
37 import jalview.ws.jws2.dm.AAConSettings;
38 import jalview.ws.jws2.dm.JabaWsParamSet;
39 import jalview.ws.jws2.jabaws2.Jws2Instance;
40 import jalview.ws.params.WsParamSetI;
42 import java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.List;
47 import compbio.data.sequence.FastaSequence;
48 import compbio.metadata.Argument;
49 import compbio.metadata.ChunkHolder;
50 import compbio.metadata.JobStatus;
51 import compbio.metadata.JobSubmissionException;
52 import compbio.metadata.Option;
53 import compbio.metadata.ResultNotAvailableException;
55 public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
58 protected Jws2Instance service;
60 protected WsParamSetI preset;
62 protected List<Argument> arguments;
64 protected IProgressIndicator guiProgress;
66 protected boolean submitGaps = true;
69 * by default, we filter out non-standard residues before submission
71 protected boolean filterNonStandardResidues = true;
74 * Recover any existing parameters for this service
76 protected void initViewportParams()
78 if (getCalcId() != null)
80 ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
82 new AAConSettings(true, service, this.preset,
84 ? JabaParamStore.getJwsArgsfromJaba(arguments)
92 * @return null or a string used to recover all annotation generated by this
95 public abstract String getCalcId();
97 public WsParamSetI getPreset()
102 public List<Argument> getArguments()
108 * reconfigure and restart the AAConClient. This method will spawn a new
109 * thread that will wait until any current jobs are finished, modify the
110 * parameters and restart the conservation calculation with the new values.
113 * @param newarguments
115 public void updateParameters(final WsParamSetI newpreset,
116 final List<Argument> newarguments)
119 arguments = newarguments;
120 calcMan.startWorker(this);
121 initViewportParams();
124 public List<Option> getJabaArguments()
126 List<Option> newargs = new ArrayList<>();
127 if (preset != null && preset instanceof JabaWsParamSet)
129 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
131 if (arguments != null && arguments.size() > 0)
133 for (Argument rg : arguments)
135 if (Option.class.isAssignableFrom(rg.getClass()))
137 newargs.add((Option) rg);
144 protected boolean alignedSeqs = true;
146 protected boolean nucleotidesAllowed = false;
148 protected boolean proteinAllowed = false;
151 * record sequences for mapping result back to afterwards
153 protected boolean bySequence = false;
155 protected Map<String, SequenceI> seqNames;
157 protected boolean[] gapMap;
165 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
166 AlignmentViewPanel alignPanel)
168 super(alignViewport, alignPanel);
171 public AbstractJabaCalcWorker(Jws2Instance service, AlignFrame alignFrame,
172 WsParamSetI preset, List<Argument> paramset)
174 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
175 this.guiProgress = alignFrame;
176 this.preset = preset;
177 this.arguments = paramset;
178 this.service = service;
183 * @return true if the submission thread should attempt to submit data
185 abstract boolean hasService();
187 volatile String rslt = "JOB NOT DEFINED";
196 long progressId = -1;
198 int serverErrorsLeft = 3;
200 StringBuffer msg = new StringBuffer();
207 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(
208 alignViewport.getAlignment(),
209 bySequence ? alignViewport.getSelectionGroup() : null);
211 if (seqs == null || !checkValidInputSeqs(true, seqs))
213 calcMan.workerComplete(this);
217 AlignmentAnnotation[] aa = alignViewport.getAlignment()
218 .getAlignmentAnnotation();
219 if (guiProgress != null)
221 guiProgress.setProgressBar("JABA " + getServiceActionText(),
222 progressId = System.currentTimeMillis());
224 rslt = submitToService(seqs);
225 if (guiProgress != null)
227 guiProgress.registerHandler(progressId,
228 new IProgressIndicatorHandler()
232 public boolean cancelActivity(long id)
239 public boolean canCancel()
245 boolean finished = false;
249 JobStatus status = getJobStatus(rslt);
250 if (status.equals(JobStatus.FINISHED))
254 if (calcMan.isPending(this) && isInteractiveUpdate())
257 // cancel this job and yield to the new job
262 jalview.bin.Console.errPrintln("Cancelled AACon job: " + rslt);
266 jalview.bin.Console.errPrintln("FAILED TO CANCEL AACon job: " + rslt);
269 } catch (Exception x)
273 rslt = "CANCELLED JOB";
277 ChunkHolder stats = null;
281 boolean retry = false;
286 stats = pullExecStatistics(rslt, rpos);
287 } catch (Exception x)
290 if (x.getMessage().contains(
291 "Position in a file could not be negative!"))
293 // squash index out of bounds exception- seems to happen for
294 // disorder predictors which don't (apparently) produce any
295 // progress information and JABA server throws an exception
296 // because progress length is -1.
301 if (--serverErrorsLeft > 0)
307 } catch (InterruptedException q)
321 System.out.print(stats.getChunk());
323 rpos = stats.getNextPosition();
325 } while (stats != null && rpos > cpos);
327 if (!finished && status.equals(JobStatus.FAILED))
332 } catch (InterruptedException x)
338 if (serverErrorsLeft > 0)
343 } catch (InterruptedException x)
346 if (collectAnnotationResultsFor(rslt))
348 Console.debug("Updating result annotation from Job " + rslt
349 + " at " + service.getUri());
350 updateResultAnnotation(true);
351 ap.adjustAnnotationHeight();
356 catch (JobSubmissionException x)
359 jalview.bin.Console.errPrintln(
360 "submission error with " + getServiceActionText() + " :");
362 calcMan.disableWorker(this);
363 } catch (ResultNotAvailableException x)
365 jalview.bin.Console.errPrintln("collection error:\nJob ID: " + rslt);
367 calcMan.disableWorker(this);
369 } catch (OutOfMemoryError error)
371 calcMan.disableWorker(this);
374 // hconsensus = null;
375 ap.raiseOOMWarning(getServiceActionText(), error);
376 } catch (Exception x)
378 calcMan.disableWorker(this);
381 // hconsensus = null;
383 .println("Blacklisting worker due to unexpected exception:");
388 calcMan.workerComplete(this);
391 calcMan.workerComplete(this);
392 if (guiProgress != null && progressId != -1)
394 guiProgress.setProgressBar("", progressId);
396 // TODO: may not need to paintAlignment again !
397 ap.paintAlignment(false, false);
399 if (msg.length() > 0)
401 // TODO: stash message somewhere in annotation or alignment view.
402 // code below shows result in a text box popup
404 * jalview.gui.CutAndPasteTransfer cap = new
405 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
406 * jalview.gui.Desktop.addInternalFrame(cap,
407 * "Job Status for "+getServiceActionText(), 600, 400);
415 * validate input for dynamic/non-dynamic update context
419 * @return true if input is valid
421 abstract boolean checkValidInputSeqs(boolean dynamic,
422 List<FastaSequence> seqs);
424 abstract String submitToService(
425 List<compbio.data.sequence.FastaSequence> seqs)
426 throws JobSubmissionException;
428 abstract boolean cancelJob(String rslt) throws Exception;
430 abstract JobStatus getJobStatus(String rslt) throws Exception;
432 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
434 abstract boolean collectAnnotationResultsFor(String rslt)
435 throws ResultNotAvailableException;
437 public void cancelCurrentJob()
444 jalview.bin.Console.errPrintln("Cancelled job " + id);
448 jalview.bin.Console.errPrintln("Job " + id + " couldn't be cancelled.");
450 } catch (Exception q)
457 * Interactive updating. Analysis calculations that work on the currently
458 * displayed alignment data should cancel existing jobs when the input data
461 * @return true if a running job should be cancelled because new input data is
462 * available for analysis
464 abstract boolean isInteractiveUpdate();
466 public List<FastaSequence> getInputSequences(AlignmentI alignment,
467 AnnotatedCollectionI inputSeqs)
469 if (alignment == null || alignment.getWidth() <= 0
470 || alignment.getSequences() == null || alignment.isNucleotide()
471 ? !nucleotidesAllowed
476 if (inputSeqs == null || inputSeqs.getWidth() <= 0
477 || inputSeqs.getSequences() == null
478 || inputSeqs.getSequences().size() < 1)
480 inputSeqs = alignment;
483 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
489 seqNames = new HashMap<>();
491 gapMap = new boolean[0];
492 start = inputSeqs.getStartRes();
493 end = inputSeqs.getEndRes();
495 for (SequenceI sq : (inputSeqs.getSequences()))
498 ? sq.findPosition(end + 1)
499 - sq.findPosition(start + 1) > minlen - 1
500 : sq.getEnd() - sq.getStart() > minlen - 1)
502 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
503 // make new input sequence with or without gaps
504 if (seqNames != null)
506 seqNames.put(newname, sq);
511 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
512 sq.getSequenceAsString()));
513 if (gapMap == null || gapMap.length < seq.getSequence().length())
515 boolean[] tg = gapMap;
516 gapMap = new boolean[seq.getLength()];
517 System.arraycopy(tg, 0, gapMap, 0, tg.length);
518 for (int p = tg.length; p < gapMap.length; p++)
520 gapMap[p] = false; // init as a gap
523 for (int apos : sq.gapMap())
525 char sqc = sq.getCharAt(apos);
526 if (!filterNonStandardResidues
527 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
528 : ResidueProperties.nucleotideIndex[sqc] < 5))
530 gapMap[apos] = true; // aligned and real amino acid residue
537 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
538 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
539 sq.getSequenceAsString(start, end + 1))));
541 if (seq.getSequence().length() > ln)
543 ln = seq.getSequence().length();
547 if (alignedSeqs && submitGaps)
550 for (int i = 0; i < gapMap.length; i++)
557 // try real hard to return something submittable
558 // TODO: some of AAcon measures need a minimum of two or three amino
559 // acids at each position, and AAcon doesn't gracefully degrade.
560 for (int p = 0; p < seqs.size(); p++)
562 FastaSequence sq = seqs.get(p);
563 int l = sq.getSequence().length();
564 // strip gapped columns
565 char[] padded = new char[realw],
566 orig = sq.getSequence().toCharArray();
567 for (int i = 0, pp = 0; i < realw; pp++)
571 if (orig.length > pp)
573 padded[i++] = orig[pp];
581 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
582 new String(padded)));
589 public void updateAnnotation()
591 updateResultAnnotation(false);
594 public abstract void updateResultAnnotation(boolean immediate);
596 public abstract String getServiceActionText();
599 * notify manager that we have started, and wait for a free calculation slot
601 * @return true if slot is obtained and work still valid, false if another
602 * thread has done our work for us.
604 protected boolean checkDone()
606 calcMan.notifyStart(this);
607 ap.paintAlignment(false, false);
608 while (!calcMan.notifyWorking(this))
610 if (calcMan.isWorking(this))
618 ap.paintAlignment(false, false);
622 } catch (Exception ex)
624 ex.printStackTrace();
627 if (alignViewport.isClosed())
635 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
637 List<AlignmentAnnotation> our = ourAnnots;
638 ourAnnots = ourAnnot;
639 AlignmentI alignment = alignViewport.getAlignment();
644 for (AlignmentAnnotation an : our)
646 if (!ourAnnots.contains(an))
648 // remove the old annotation
649 alignment.deleteAnnotation(an);
655 ap.adjustAnnotationHeight();