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.gui.IProgressIndicatorHandler;
34 import jalview.schemes.ResidueProperties;
35 import jalview.workers.AlignCalcWorker;
36 import jalview.ws.jws2.dm.AAConSettings;
37 import jalview.ws.jws2.dm.JabaWsParamSet;
38 import jalview.ws.jws2.jabaws2.Jws2Instance;
39 import jalview.ws.params.WsParamSetI;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.List;
46 import compbio.data.sequence.FastaSequence;
47 import compbio.metadata.Argument;
48 import compbio.metadata.ChunkHolder;
49 import compbio.metadata.JobStatus;
50 import compbio.metadata.JobSubmissionException;
51 import compbio.metadata.Option;
52 import compbio.metadata.ResultNotAvailableException;
54 public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
57 protected Jws2Instance service;
59 protected WsParamSetI preset;
61 protected List<Argument> arguments;
63 protected IProgressIndicator guiProgress;
65 protected boolean submitGaps = true;
68 * by default, we filter out non-standard residues before submission
70 protected boolean filterNonStandardResidues = true;
73 * Recover any existing parameters for this service
75 protected void initViewportParams()
77 if (getCalcId() != null)
79 ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
81 new AAConSettings(true, service, this.preset,
83 ? JabaParamStore.getJwsArgsfromJaba(arguments)
91 * @return null or a string used to recover all annotation generated by this
94 public abstract String getCalcId();
96 public WsParamSetI getPreset()
101 public List<Argument> getArguments()
107 * reconfigure and restart the AAConClient. This method will spawn a new
108 * thread that will wait until any current jobs are finished, modify the
109 * parameters and restart the conservation calculation with the new values.
112 * @param newarguments
114 public void updateParameters(final WsParamSetI newpreset,
115 final List<Argument> newarguments)
118 arguments = newarguments;
119 calcMan.startWorker(this);
120 initViewportParams();
123 public List<Option> getJabaArguments()
125 List<Option> newargs = new ArrayList<>();
126 if (preset != null && preset instanceof JabaWsParamSet)
128 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
130 if (arguments != null && arguments.size() > 0)
132 for (Argument rg : arguments)
134 if (Option.class.isAssignableFrom(rg.getClass()))
136 newargs.add((Option) rg);
143 protected boolean alignedSeqs = true;
145 protected boolean nucleotidesAllowed = false;
147 protected boolean proteinAllowed = false;
150 * record sequences for mapping result back to afterwards
152 protected boolean bySequence = false;
154 protected Map<String, SequenceI> seqNames;
156 protected boolean[] gapMap;
164 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
165 AlignmentViewPanel alignPanel)
167 super(alignViewport, alignPanel);
170 public AbstractJabaCalcWorker(Jws2Instance service, AlignFrame alignFrame,
171 WsParamSetI preset, List<Argument> paramset)
173 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
174 this.guiProgress = alignFrame;
175 this.preset = preset;
176 this.arguments = paramset;
177 this.service = service;
182 * @return true if the submission thread should attempt to submit data
184 abstract boolean hasService();
186 volatile String rslt = "JOB NOT DEFINED";
195 long progressId = -1;
197 int serverErrorsLeft = 3;
199 StringBuffer msg = new StringBuffer();
206 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(
207 alignViewport.getAlignment(),
208 bySequence ? alignViewport.getSelectionGroup() : null);
210 if (seqs == null || !checkValidInputSeqs(true, seqs))
212 calcMan.workerComplete(this);
216 AlignmentAnnotation[] aa = alignViewport.getAlignment()
217 .getAlignmentAnnotation();
218 if (guiProgress != null)
220 guiProgress.setProgressBar("JABA " + getServiceActionText(),
221 progressId = System.currentTimeMillis());
223 rslt = submitToService(seqs);
224 if (guiProgress != null)
226 guiProgress.registerHandler(progressId,
227 new IProgressIndicatorHandler()
231 public boolean cancelActivity(long id)
238 public boolean canCancel()
244 boolean finished = false;
248 JobStatus status = getJobStatus(rslt);
249 if (status.equals(JobStatus.FINISHED))
253 if (calcMan.isPending(this) && isInteractiveUpdate())
256 // cancel this job and yield to the new job
261 System.err.println("Cancelled AACon job: " + rslt);
265 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
268 } catch (Exception x)
272 rslt = "CANCELLED JOB";
276 ChunkHolder stats = null;
280 boolean retry = false;
285 stats = pullExecStatistics(rslt, rpos);
286 } catch (Exception x)
289 if (x.getMessage().contains(
290 "Position in a file could not be negative!"))
292 // squash index out of bounds exception- seems to happen for
293 // disorder predictors which don't (apparently) produce any
294 // progress information and JABA server throws an exception
295 // because progress length is -1.
300 if (--serverErrorsLeft > 0)
306 } catch (InterruptedException q)
320 System.out.print(stats.getChunk());
322 rpos = stats.getNextPosition();
324 } while (stats != null && rpos > cpos);
326 if (!finished && status.equals(JobStatus.FAILED))
331 } catch (InterruptedException x)
337 if (serverErrorsLeft > 0)
342 } catch (InterruptedException x)
345 if (collectAnnotationResultsFor(rslt))
347 jalview.bin.Cache.log.debug("Updating result annotation from Job "
348 + rslt + " at " + service.getUri());
349 updateResultAnnotation(true);
350 ap.adjustAnnotationHeight();
355 catch (JobSubmissionException x)
359 "submission error with " + getServiceActionText() + " :");
361 calcMan.disableWorker(this);
362 } catch (ResultNotAvailableException x)
364 System.err.println("collection error:\nJob ID: " + rslt);
366 calcMan.disableWorker(this);
368 } catch (OutOfMemoryError error)
370 calcMan.disableWorker(this);
373 // hconsensus = null;
374 ap.raiseOOMWarning(getServiceActionText(), error);
375 } catch (Exception x)
377 calcMan.disableWorker(this);
380 // hconsensus = null;
382 .println("Blacklisting worker due to unexpected exception:");
387 calcMan.workerComplete(this);
390 calcMan.workerComplete(this);
391 if (guiProgress != null && progressId != -1)
393 guiProgress.setProgressBar("", progressId);
395 // TODO: may not need to paintAlignment again !
396 ap.paintAlignment(false, false);
398 if (msg.length() > 0)
400 // TODO: stash message somewhere in annotation or alignment view.
401 // code below shows result in a text box popup
403 * jalview.gui.CutAndPasteTransfer cap = new
404 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
405 * jalview.gui.Desktop.addInternalFrame(cap,
406 * "Job Status for "+getServiceActionText(), 600, 400);
414 * validate input for dynamic/non-dynamic update context
418 * @return true if input is valid
420 abstract boolean checkValidInputSeqs(boolean dynamic,
421 List<FastaSequence> seqs);
423 abstract String submitToService(
424 List<compbio.data.sequence.FastaSequence> seqs)
425 throws JobSubmissionException;
427 abstract boolean cancelJob(String rslt) throws Exception;
429 abstract JobStatus getJobStatus(String rslt) throws Exception;
431 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
433 abstract boolean collectAnnotationResultsFor(String rslt)
434 throws ResultNotAvailableException;
436 public void cancelCurrentJob()
443 System.err.println("Cancelled job " + id);
447 System.err.println("Job " + id + " couldn't be cancelled.");
449 } catch (Exception q)
456 * Interactive updating. Analysis calculations that work on the currently
457 * displayed alignment data should cancel existing jobs when the input data
460 * @return true if a running job should be cancelled because new input data is
461 * available for analysis
463 abstract boolean isInteractiveUpdate();
465 public List<FastaSequence> getInputSequences(AlignmentI alignment,
466 AnnotatedCollectionI inputSeqs)
468 if (alignment == null || alignment.getWidth() <= 0
469 || alignment.getSequences() == null || alignment.isNucleotide()
470 ? !nucleotidesAllowed
475 if (inputSeqs == null || inputSeqs.getWidth() <= 0
476 || inputSeqs.getSequences() == null
477 || inputSeqs.getSequences().size() < 1)
479 inputSeqs = alignment;
482 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
488 seqNames = new HashMap<>();
490 gapMap = new boolean[0];
491 start = inputSeqs.getStartRes();
492 end = inputSeqs.getEndRes();
494 for (SequenceI sq : (inputSeqs.getSequences()))
497 ? sq.findPosition(end + 1)
498 - sq.findPosition(start + 1) > minlen - 1
499 : sq.getEnd() - sq.getStart() > minlen - 1)
501 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
502 // make new input sequence with or without gaps
503 if (seqNames != null)
505 seqNames.put(newname, sq);
510 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
511 sq.getSequenceAsString()));
512 if (gapMap == null || gapMap.length < seq.getSequence().length())
514 boolean[] tg = gapMap;
515 gapMap = new boolean[seq.getLength()];
516 System.arraycopy(tg, 0, gapMap, 0, tg.length);
517 for (int p = tg.length; p < gapMap.length; p++)
519 gapMap[p] = false; // init as a gap
522 for (int apos : sq.gapMap())
524 char sqc = sq.getCharAt(apos);
525 if (!filterNonStandardResidues
526 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
527 : ResidueProperties.nucleotideIndex[sqc] < 5))
529 gapMap[apos] = true; // aligned and real amino acid residue
536 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
537 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
538 sq.getSequenceAsString(start, end + 1))));
540 if (seq.getSequence().length() > ln)
542 ln = seq.getSequence().length();
546 if (alignedSeqs && submitGaps)
549 for (int i = 0; i < gapMap.length; i++)
556 // try real hard to return something submittable
557 // TODO: some of AAcon measures need a minimum of two or three amino
558 // acids at each position, and AAcon doesn't gracefully degrade.
559 for (int p = 0; p < seqs.size(); p++)
561 FastaSequence sq = seqs.get(p);
562 int l = sq.getSequence().length();
563 // strip gapped columns
564 char[] padded = new char[realw],
565 orig = sq.getSequence().toCharArray();
566 for (int i = 0, pp = 0; i < realw; pp++)
570 if (orig.length > pp)
572 padded[i++] = orig[pp];
580 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
581 new String(padded)));
588 public void updateAnnotation()
590 updateResultAnnotation(false);
593 public abstract void updateResultAnnotation(boolean immediate);
595 public abstract String getServiceActionText();
598 * notify manager that we have started, and wait for a free calculation slot
600 * @return true if slot is obtained and work still valid, false if another
601 * thread has done our work for us.
603 protected boolean checkDone()
605 calcMan.notifyStart(this);
606 ap.paintAlignment(false, false);
607 while (!calcMan.notifyWorking(this))
609 if (calcMan.isWorking(this))
617 ap.paintAlignment(false, false);
621 } catch (Exception ex)
623 ex.printStackTrace();
626 if (alignViewport.isClosed())
634 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
636 List<AlignmentAnnotation> our = ourAnnots;
637 ourAnnots = ourAnnot;
638 AlignmentI alignment = alignViewport.getAlignment();
643 for (AlignmentAnnotation an : our)
645 if (!ourAnnots.contains(an))
647 // remove the old annotation
648 alignment.deleteAnnotation(an);
654 ap.adjustAnnotationHeight();