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.Cache;
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.Desktop;
34 import jalview.gui.IProgressIndicator;
35 import jalview.gui.IProgressIndicatorHandler;
36 import jalview.gui.JvOptionPane;
37 import jalview.schemes.ResidueProperties;
38 import jalview.util.MessageManager;
39 import jalview.workers.AlignCalcWorker;
40 import jalview.ws.api.CancellableI;
41 import jalview.ws.api.JobId;
42 import jalview.ws.api.WSAnnotationCalcManagerI;
43 import jalview.ws.gui.AnnotationWsJob;
44 import jalview.ws.jws2.dm.AAConSettings;
45 import jalview.ws.jws2.jabaws2.Jws2Instance;
46 import jalview.ws.params.ArgumentI;
47 import jalview.ws.params.WsParamSetI;
49 import java.util.ArrayList;
50 import java.util.HashMap;
51 import java.util.List;
54 public class AbstractJabaCalcWorker extends AlignCalcWorker
55 implements WSAnnotationCalcManagerI
58 protected Jws2Instance service;
60 protected WsParamSetI preset;
62 protected List<ArgumentI> 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, arguments),
89 * @return null or a string used to recover all annotation generated by this
92 public String getCalcId()
94 return service.getAlignAnalysisUI() == null ? null
95 : service.getAlignAnalysisUI().getCalcId();
98 public WsParamSetI getPreset()
103 public List<ArgumentI> 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<ArgumentI> newarguments)
120 arguments = newarguments;
121 calcMan.startWorker(this);
122 initViewportParams();
124 protected boolean alignedSeqs = true;
126 protected boolean nucleotidesAllowed = false;
128 protected boolean proteinAllowed = false;
131 * record sequences for mapping result back to afterwards
133 protected boolean bySequence = false;
135 protected Map<String, SequenceI> seqNames;
137 // TODO: convert to bitset
138 protected boolean[] gapMap;
146 private AlignFrame alignFrame;
148 public boolean[] getGapMap()
153 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
154 AlignmentViewPanel alignPanel)
156 super(alignViewport, alignPanel);
159 public AbstractJabaCalcWorker(Jws2Instance service, AlignFrame alignFrame,
160 WsParamSetI preset, List<ArgumentI> paramset)
162 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
163 // TODO: both these fields needed ?
164 this.alignFrame = alignFrame;
165 this.guiProgress = alignFrame;
166 this.preset = preset;
167 this.arguments = paramset;
168 this.service = service;
171 annotService = (jalview.ws.api.SequenceAnnotationServiceI) service
173 } catch (ClassCastException cce)
175 JvOptionPane.showMessageDialog(Desktop.desktop,
176 MessageManager.formatMessage(
177 "label.service_called_is_not_an_annotation_service",
179 { service.getName() }),
180 MessageManager.getString("label.internal_jalview_error"),
181 JvOptionPane.WARNING_MESSAGE);
184 // configure submission flags
185 if (service.getAlignAnalysisUI() != null)
187 // instantaneous calculation. Right now that's either AACons or RNAAliFold
188 proteinAllowed = service.getAlignAnalysisUI().isPr();
189 nucleotidesAllowed = service.getAlignAnalysisUI().isNa();
190 alignedSeqs = service.getAlignAnalysisUI().isNeedsAlignedSeqs();
191 bySequence = !service.getAlignAnalysisUI().isAA();
192 filterNonStandardResidues = service.getAlignAnalysisUI()
194 min_valid_seqs = service.getAlignAnalysisUI().getMinimumSequences();
195 initViewportParams();
199 // assume disorder prediction : per-sequence protein only no gaps
201 // TODO - move configuration to UIInfo base class for all these flags !
204 filterNonStandardResidues = true;
205 nucleotidesAllowed = false;
206 proteinAllowed = true;
214 * @return true if the submission thread should attempt to submit data
216 public boolean hasService()
218 return annotService != null;
221 protected jalview.ws.api.SequenceAnnotationServiceI annotService = null;
223 volatile JobId rslt = null;
225 AnnotationWsJob running = null;
227 private int min_valid_seqs;
237 long progressId = -1;
239 int serverErrorsLeft = 3;
240 final boolean cancellable = CancellableI.class
241 .isAssignableFrom(annotService.getClass());
242 StringBuffer msg = new StringBuffer();
249 List<SequenceI> seqs = getInputSequences(
250 alignViewport.getAlignment(),
251 bySequence ? alignViewport.getSelectionGroup() : null);
253 if (seqs == null || !checkValidInputSeqs(seqs))
255 jalview.bin.Cache.log.debug(
256 "Sequences for analysis service were null or not valid");
257 calcMan.workerComplete(this);
261 AlignmentAnnotation[] aa = alignViewport.getAlignment()
262 .getAlignmentAnnotation();
263 if (guiProgress != null)
265 guiProgress.setProgressBar(service.getActionText(),
266 progressId = System.currentTimeMillis());
268 jalview.bin.Cache.log.debug("submitted " + seqs.size()
269 + " sequences to " + service.getActionText());
271 rslt = annotService.submitToService(seqs, getPreset(),
277 // TODO: handle job submission error reporting here.
280 // otherwise, construct WsJob and any UI handlers
281 running = new AnnotationWsJob();
282 running.setJobHandle(rslt);
283 running.setSeqNames(seqNames);
284 running.setStartPos(start);
285 running.setSeqs(seqs);
287 if (guiProgress != null)
289 guiProgress.registerHandler(progressId,
290 new IProgressIndicatorHandler()
294 public boolean cancelActivity(long id)
296 ((CancellableI) annotService).cancel(running);
301 public boolean canCancel()
309 // and poll for updates until job finishes, fails or becomes stale
311 boolean finished = false;
315 Cache.log.debug("Updating status for annotation service.");
316 annotService.updateStatus(running);
318 if (running.isFinished())
320 Cache.log.debug("Analysis service job reported finished.");
325 Cache.log.debug("Status now " + running.getState());
328 if (calcMan.isPending(this) && isInteractiveUpdate())
330 Cache.log.debug("Analysis service job is stale. aborting.");
331 // job has become stale.
334 // cancel this job and yield to the new job
338 && ((CancellableI) annotService).cancel(running))
340 System.err.println("Cancelled AACon job: " + rslt);
344 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
347 } catch (Exception x)
352 rslt = running.getJobHandle();
356 // pull any stats - some services need to flush log output before
357 // results are available
358 Cache.log.debug("Updating progress log for annotation service.");
362 annotService.updateJobProgress(running);
363 } catch (Throwable thr)
365 Cache.log.debug("Ignoring exception during progress update.",
368 Cache.log.trace("Result of poll: " + running.getStatus());
370 if (!finished && !running.isFailed())
374 Cache.log.debug("Analysis service job thread sleeping.");
376 Cache.log.debug("Analysis service job thread woke.");
377 } catch (InterruptedException x)
384 // TODO: need to poll/retry
385 if (serverErrorsLeft > 0)
390 } catch (InterruptedException x)
394 // configure job with the associated view's feature renderer, if one
396 // TODO: here one would also grab the 'master feature renderer' in order
398 // features automatically according to user preferences
399 running.setFeatureRenderer(
400 ((jalview.gui.AlignmentPanel) ap).cloneFeatureRenderer());
401 Cache.log.debug("retrieving job results.");
402 List<AlignmentAnnotation> returnedAnnot = annotService
403 .getAlignmentAnnotation(running, this);
404 Cache.log.debug("Obtained " + (returnedAnnot == null ? "no rows"
405 : ("" + returnedAnnot.size())));
406 running.setAnnotation(returnedAnnot);
408 if (running.hasResults())
410 jalview.bin.Cache.log.debug("Updating result annotation from Job "
411 + rslt + " at " + service.getUri());
412 updateResultAnnotation(true);
413 if (running.isTransferSequenceFeatures())
415 jalview.bin.Cache.log.debug(
416 "Updating feature display settings and transferring features from Job "
417 + rslt + " at " + service.getUri());
418 ((jalview.gui.AlignmentPanel) ap)
419 .updateFeatureRendererFrom(running.getFeatureRenderer());
420 // TODO: JAL-1150 - create sequence feature settings API for defining
421 // styles and enabling/disabling feature overlay on alignment panel
423 if (alignFrame.alignPanel == ap)
425 // only do this if the alignFrame is currently showing this view.
426 Desktop.getAlignFrameFor(alignViewport)
427 .setShowSeqFeatures(true);
430 ap.adjustAnnotationHeight();
432 Cache.log.debug("Annotation Service Worker thread finished.");
434 // TODO: use service specitic exception handlers
435 // catch (JobSubmissionException x)
438 // System.err.println(
439 // "submission error with " + getServiceActionText() + " :");
440 // x.printStackTrace();
441 // calcMan.disableWorker(this);
442 // } catch (ResultNotAvailableException x)
444 // System.err.println("collection error:\nJob ID: " + rslt);
445 // x.printStackTrace();
446 // calcMan.disableWorker(this);
448 // } catch (OutOfMemoryError error)
450 // calcMan.disableWorker(this);
452 // ap.raiseOOMWarning(getServiceActionText(), error);
456 calcMan.disableWorker(this);
459 .println("Blacklisting worker due to unexpected exception:");
464 calcMan.workerComplete(this);
467 calcMan.workerComplete(this);
468 if (guiProgress != null && progressId != -1)
470 guiProgress.setProgressBar("", progressId);
472 // TODO: may not need to paintAlignment again !
473 ap.paintAlignment(false, false);
475 if (msg.length() > 0)
477 // TODO: stash message somewhere in annotation or alignment view.
478 // code below shows result in a text box popup
480 * jalview.gui.CutAndPasteTransfer cap = new
481 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
482 * jalview.gui.Desktop.addInternalFrame(cap,
483 * "Job Status for "+getServiceActionText(), 600, 400);
491 * validate input for dynamic/non-dynamic update context TODO: move to
492 * analysis interface ?
495 * @return true if input is valid
497 boolean checkValidInputSeqs(List<SequenceI> seqs)
500 for (SequenceI sq : seqs)
502 if (sq.getStart() <= sq.getEnd()
503 && (sq.isProtein() ? proteinAllowed : nucleotidesAllowed))
506 || sq.getLength() == (sq.getEnd() - sq.getStart() + 1))
512 return nvalid >= min_valid_seqs;
515 public void cancelCurrentJob()
519 String id = running.getJobId();
520 if (((CancellableI) annotService).cancel(running))
522 System.err.println("Cancelled job " + id);
526 System.err.println("Job " + id + " couldn't be cancelled.");
528 } catch (Exception q)
535 * Interactive updating. Analysis calculations that work on the currently
536 * displayed alignment data should cancel existing jobs when the input data
539 * @return true if a running job should be cancelled because new input data is
540 * available for analysis
542 boolean isInteractiveUpdate()
544 return service.isInteractiveUpdate();
548 * decide what sequences will be analysed TODO: refactor to generate
549 * List<SequenceI> for submission to service interface
555 public List<SequenceI> getInputSequences(AlignmentI alignment,
556 AnnotatedCollectionI inputSeqs)
558 if (alignment == null || alignment.getWidth() <= 0
559 || alignment.getSequences() == null || alignment.isNucleotide()
560 ? !nucleotidesAllowed
565 if (inputSeqs == null || inputSeqs.getWidth() <= 0
566 || inputSeqs.getSequences() == null
567 || inputSeqs.getSequences().size() < 1)
569 inputSeqs = alignment;
572 List<SequenceI> seqs = new ArrayList<>();
578 seqNames = new HashMap<>();
580 gapMap = new boolean[0];
581 start = inputSeqs.getStartRes();
582 end = inputSeqs.getEndRes();
583 // TODO: URGENT! unify with JPred / MSA code to handle hidden regions
585 // TODO: push attributes into WsJob instance (so they can be safely
586 // persisted/restored
587 for (SequenceI sq : (inputSeqs.getSequences()))
590 ? sq.findPosition(end + 1)
591 - sq.findPosition(start + 1) > minlen - 1
592 : sq.getEnd() - sq.getStart() > minlen - 1)
594 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
595 // make new input sequence with or without gaps
596 if (seqNames != null)
598 seqNames.put(newname, sq);
603 seqs.add(seq = new jalview.datamodel.Sequence(newname,
604 sq.getSequenceAsString()));
605 if (gapMap == null || gapMap.length < seq.getLength())
607 boolean[] tg = gapMap;
608 gapMap = new boolean[seq.getLength()];
609 System.arraycopy(tg, 0, gapMap, 0, tg.length);
610 for (int p = tg.length; p < gapMap.length; p++)
612 gapMap[p] = false; // init as a gap
615 for (int apos : sq.gapMap())
617 char sqc = sq.getCharAt(apos);
618 if (!filterNonStandardResidues
619 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
620 : ResidueProperties.nucleotideIndex[sqc] < 5))
622 gapMap[apos] = true; // aligned and real amino acid residue
629 // TODO: add ability to exclude hidden regions
630 seqs.add(seq = new jalview.datamodel.Sequence(newname,
631 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
632 sq.getSequenceAsString(start, end + 1))));
633 // for annotation need to also record map to sequence start/end
635 // then transfer back to original sequence on return.
637 if (seq.getLength() > ln)
639 ln = seq.getLength();
643 if (alignedSeqs && submitGaps)
646 for (int i = 0; i < gapMap.length; i++)
653 // try real hard to return something submittable
654 // TODO: some of AAcon measures need a minimum of two or three amino
655 // acids at each position, and AAcon doesn't gracefully degrade.
656 for (int p = 0; p < seqs.size(); p++)
658 SequenceI sq = seqs.get(p);
659 // strip gapped columns
660 char[] padded = new char[realw],
661 orig = sq.getSequence();
662 for (int i = 0, pp = 0; i < realw; pp++)
666 if (orig.length > pp)
668 padded[i++] = orig[pp];
676 seqs.set(p, new jalview.datamodel.Sequence(sq.getName(),
677 new String(padded)));
684 public void updateAnnotation()
686 updateResultAnnotation(false);
689 public void updateResultAnnotation(boolean immediate)
691 if ((immediate || !calcMan.isWorking(this)) && running != null
692 && running.hasResults())
694 List<AlignmentAnnotation> ourAnnot = running.getAnnotation();
695 updateOurAnnots(ourAnnot);
700 * notify manager that we have started, and wait for a free calculation slot
702 * @return true if slot is obtained and work still valid, false if another
703 * thread has done our work for us.
705 protected boolean checkDone()
707 calcMan.notifyStart(this);
708 ap.paintAlignment(false, false);
709 while (!calcMan.notifyWorking(this))
711 if (calcMan.isWorking(this))
719 ap.paintAlignment(false, false);
723 } catch (Exception ex)
725 ex.printStackTrace();
728 if (alignViewport.isClosed())
736 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
738 List<AlignmentAnnotation> our = ourAnnots;
739 ourAnnots = ourAnnot;
740 AlignmentI alignment = alignViewport.getAlignment();
745 for (AlignmentAnnotation an : our)
747 if (!ourAnnots.contains(an))
749 // remove the old annotation
750 alignment.deleteAnnotation(an);
755 // validate rows and update Alignmment state
756 for (AlignmentAnnotation an : ourAnnots)
758 alignViewport.getAlignment().validateAnnotation(an);
760 // TODO: may need a menu refresh after this
761 // af.setMenusForViewport();
762 ap.adjustAnnotationHeight();