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.JalviewServiceEndpointProviderI;
42 import jalview.ws.api.JobId;
43 import jalview.ws.api.SequenceAnnotationServiceI;
44 import jalview.ws.api.ServiceWithParameters;
45 import jalview.ws.api.WSAnnotationCalcManagerI;
46 import jalview.ws.gui.AnnotationWsJob;
47 import jalview.ws.jws2.dm.AAConSettings;
48 import jalview.ws.params.ArgumentI;
49 import jalview.ws.params.WsParamSetI;
51 import java.util.ArrayList;
52 import java.util.HashMap;
53 import java.util.List;
56 public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
57 implements WSAnnotationCalcManagerI
60 protected ServiceWithParameters service;
62 protected WsParamSetI preset;
64 protected List<ArgumentI> arguments;
66 protected IProgressIndicator guiProgress;
68 protected boolean submitGaps = true;
71 * by default, we filter out non-standard residues before submission
73 protected boolean filterNonStandardResidues = true;
76 * Recover any existing parameters for this service
78 protected void initViewportParams()
80 if (getCalcId() != null)
82 ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
84 new AAConSettings(true, service, this.preset, arguments),
91 * @return null or a string used to recover all annotation generated by this
94 public String getCalcId()
96 return service.getAlignAnalysisUI() == null ? null
97 : service.getAlignAnalysisUI().getCalcId();
100 public WsParamSetI getPreset()
105 public List<ArgumentI> getArguments()
111 * reconfigure and restart the AAConClient. This method will spawn a new
112 * thread that will wait until any current jobs are finished, modify the
113 * parameters and restart the conservation calculation with the new values.
116 * @param newarguments
118 public void updateParameters(final WsParamSetI newpreset,
119 final List<ArgumentI> newarguments)
122 arguments = newarguments;
123 calcMan.startWorker(this);
124 initViewportParams();
126 protected boolean alignedSeqs = true;
128 protected boolean nucleotidesAllowed = false;
130 protected boolean proteinAllowed = false;
133 * record sequences for mapping result back to afterwards
135 protected boolean bySequence = false;
137 protected Map<String, SequenceI> seqNames;
139 // TODO: convert to bitset
140 protected boolean[] gapMap;
148 private AlignFrame alignFrame;
150 public boolean[] getGapMap()
155 public SeqAnnotationServiceCalcWorker(AlignViewportI alignViewport,
156 AlignmentViewPanel alignPanel)
158 super(alignViewport, alignPanel);
161 public SeqAnnotationServiceCalcWorker(ServiceWithParameters service,
162 AlignFrame alignFrame,
163 WsParamSetI preset, List<ArgumentI> paramset)
165 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
166 // TODO: both these fields needed ?
167 this.alignFrame = alignFrame;
168 this.guiProgress = alignFrame;
169 this.preset = preset;
170 this.arguments = paramset;
171 this.service = service;
174 annotService = (jalview.ws.api.SequenceAnnotationServiceI) ((JalviewServiceEndpointProviderI) service)
176 } catch (ClassCastException cce)
178 JvOptionPane.showMessageDialog(Desktop.desktop,
179 MessageManager.formatMessage(
180 "label.service_called_is_not_an_annotation_service",
182 { service.getName() }),
183 MessageManager.getString("label.internal_jalview_error"),
184 JvOptionPane.WARNING_MESSAGE);
187 // configure submission flags
188 proteinAllowed = service.isProteinService();
189 nucleotidesAllowed = service.isNucleotideService();
190 alignedSeqs = service.isNeedsAlignedSequences();
191 bySequence = !service.isAlignmentAnalysis();
192 filterNonStandardResidues = service.isFilterSymbols();
193 min_valid_seqs = service.getMinimumInputSequences();
195 if (service.isInteractiveUpdate())
197 initViewportParams();
203 * @return true if the submission thread should attempt to submit data
205 public boolean hasService()
207 return annotService != null;
210 protected jalview.ws.api.SequenceAnnotationServiceI annotService = null;
212 volatile JobId rslt = null;
214 AnnotationWsJob running = null;
216 private int min_valid_seqs;
226 long progressId = -1;
228 int serverErrorsLeft = 3;
229 final boolean cancellable = CancellableI.class
230 .isAssignableFrom(annotService.getClass());
231 StringBuffer msg = new StringBuffer();
238 List<SequenceI> seqs = getInputSequences(
239 alignViewport.getAlignment(),
240 bySequence ? alignViewport.getSelectionGroup() : null);
242 if (seqs == null || !checkValidInputSeqs(seqs))
244 jalview.bin.Cache.log.debug(
245 "Sequences for analysis service were null or not valid");
246 calcMan.workerComplete(this);
250 if (guiProgress != null)
252 guiProgress.setProgressBar(service.getActionText(),
253 progressId = System.currentTimeMillis());
255 jalview.bin.Cache.log.debug("submitted " + seqs.size()
256 + " sequences to " + service.getActionText());
258 rslt = annotService.submitToService(seqs, getPreset(),
264 // TODO: handle job submission error reporting here.
267 // otherwise, construct WsJob and any UI handlers
268 running = new AnnotationWsJob();
269 running.setJobHandle(rslt);
270 running.setSeqNames(seqNames);
271 running.setStartPos(start);
272 running.setSeqs(seqs);
274 if (guiProgress != null)
276 guiProgress.registerHandler(progressId,
277 new IProgressIndicatorHandler()
281 public boolean cancelActivity(long id)
283 ((CancellableI) annotService).cancel(running);
288 public boolean canCancel()
296 // and poll for updates until job finishes, fails or becomes stale
298 boolean finished = false;
301 Cache.log.debug("Updating status for annotation service.");
302 annotService.updateStatus(running);
304 if (running.isFinished())
306 Cache.log.debug("Analysis service job reported finished.");
311 Cache.log.debug("Status now " + running.getState());
314 if (calcMan.isPending(this) && isInteractiveUpdate())
316 Cache.log.debug("Analysis service job is stale. aborting.");
317 // job has become stale.
320 // cancel this job and yield to the new job
324 && ((CancellableI) annotService).cancel(running))
326 System.err.println("Cancelled job: " + rslt);
330 System.err.println("FAILED TO CANCEL job: " + rslt);
333 } catch (Exception x)
338 rslt = running.getJobHandle();
342 // pull any stats - some services need to flush log output before
343 // results are available
344 Cache.log.debug("Updating progress log for annotation service.");
348 annotService.updateJobProgress(running);
349 } catch (Throwable thr)
351 Cache.log.debug("Ignoring exception during progress update.",
354 Cache.log.trace("Result of poll: " + running.getStatus());
356 if (!finished && !running.isFailed())
360 Cache.log.debug("Analysis service job thread sleeping.");
362 Cache.log.debug("Analysis service job thread woke.");
363 } catch (InterruptedException x)
370 // TODO: need to poll/retry
371 if (serverErrorsLeft > 0)
376 } catch (InterruptedException x)
380 // configure job with the associated view's feature renderer, if one
382 // TODO: here one would also grab the 'master feature renderer' in order
384 // features automatically according to user preferences
385 running.setFeatureRenderer(
386 ((jalview.gui.AlignmentPanel) ap).cloneFeatureRenderer());
387 Cache.log.debug("retrieving job results.");
388 List<AlignmentAnnotation> returnedAnnot = annotService
389 .getAlignmentAnnotation(running, this);
390 Cache.log.debug("Obtained " + (returnedAnnot == null ? "no rows"
391 : ("" + returnedAnnot.size())));
392 running.setAnnotation(returnedAnnot);
394 if (running.hasResults())
396 jalview.bin.Cache.log.debug("Updating result annotation from Job "
397 + rslt + " at " + service.getUri());
398 updateResultAnnotation(true);
399 if (running.isTransferSequenceFeatures())
401 jalview.bin.Cache.log.debug(
402 "Updating feature display settings and transferring features from Job "
403 + rslt + " at " + service.getUri());
404 ((jalview.gui.AlignmentPanel) ap)
405 .updateFeatureRendererFrom(running.getFeatureRenderer());
406 // TODO: JAL-1150 - create sequence feature settings API for defining
407 // styles and enabling/disabling feature overlay on alignment panel
409 if (alignFrame.alignPanel == ap)
411 // only do this if the alignFrame is currently showing this view.
412 Desktop.getAlignFrameFor(alignViewport)
413 .setShowSeqFeatures(true);
416 ap.adjustAnnotationHeight();
418 Cache.log.debug("Annotation Service Worker thread finished.");
420 // TODO: use service specitic exception handlers
421 // catch (JobSubmissionException x)
424 // System.err.println(
425 // "submission error with " + getServiceActionText() + " :");
426 // x.printStackTrace();
427 // calcMan.disableWorker(this);
428 // } catch (ResultNotAvailableException x)
430 // System.err.println("collection error:\nJob ID: " + rslt);
431 // x.printStackTrace();
432 // calcMan.disableWorker(this);
434 // } catch (OutOfMemoryError error)
436 // calcMan.disableWorker(this);
438 // ap.raiseOOMWarning(getServiceActionText(), error);
442 calcMan.disableWorker(this);
445 .println("Blacklisting worker due to unexpected exception:");
450 calcMan.workerComplete(this);
453 calcMan.workerComplete(this);
454 if (guiProgress != null && progressId != -1)
456 guiProgress.setProgressBar("", progressId);
458 // TODO: may not need to paintAlignment again !
459 ap.paintAlignment(false, false);
461 if (msg.length() > 0)
463 // TODO: stash message somewhere in annotation or alignment view.
464 // code below shows result in a text box popup
466 * jalview.gui.CutAndPasteTransfer cap = new
467 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
468 * jalview.gui.Desktop.addInternalFrame(cap,
469 * "Job Status for "+getServiceActionText(), 600, 400);
477 * validate input for dynamic/non-dynamic update context TODO: move to
478 * analysis interface ?
481 * @return true if input is valid
483 boolean checkValidInputSeqs(List<SequenceI> seqs)
486 for (SequenceI sq : seqs)
488 if (sq.getStart() <= sq.getEnd()
489 && (sq.isProtein() ? proteinAllowed : nucleotidesAllowed))
492 || sq.getLength() == (sq.getEnd() - sq.getStart() + 1))
498 return nvalid >= min_valid_seqs;
501 public void cancelCurrentJob()
505 String id = running.getJobId();
506 if (((CancellableI) annotService).cancel(running))
508 System.err.println("Cancelled job " + id);
512 System.err.println("Job " + id + " couldn't be cancelled.");
514 } catch (Exception q)
521 * Interactive updating. Analysis calculations that work on the currently
522 * displayed alignment data should cancel existing jobs when the input data
525 * @return true if a running job should be cancelled because new input data is
526 * available for analysis
528 boolean isInteractiveUpdate()
530 return service.isInteractiveUpdate();
534 * decide what sequences will be analysed TODO: refactor to generate
535 * List<SequenceI> for submission to service interface
541 public List<SequenceI> getInputSequences(AlignmentI alignment,
542 AnnotatedCollectionI inputSeqs)
544 if (alignment == null || alignment.getWidth() <= 0
545 || alignment.getSequences() == null || alignment.isNucleotide()
546 ? !nucleotidesAllowed
551 if (inputSeqs == null || inputSeqs.getWidth() <= 0
552 || inputSeqs.getSequences() == null
553 || inputSeqs.getSequences().size() < 1)
555 inputSeqs = alignment;
558 List<SequenceI> seqs = new ArrayList<>();
564 seqNames = new HashMap<>();
566 gapMap = new boolean[0];
567 start = inputSeqs.getStartRes();
568 end = inputSeqs.getEndRes();
569 // TODO: URGENT! unify with JPred / MSA code to handle hidden regions
571 // TODO: push attributes into WsJob instance (so they can be safely
572 // persisted/restored
573 for (SequenceI sq : (inputSeqs.getSequences()))
576 ? sq.findPosition(end + 1)
577 - sq.findPosition(start + 1) > minlen - 1
578 : sq.getEnd() - sq.getStart() > minlen - 1)
580 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
581 // make new input sequence with or without gaps
582 if (seqNames != null)
584 seqNames.put(newname, sq);
589 seqs.add(seq = new jalview.datamodel.Sequence(newname,
590 sq.getSequenceAsString()));
591 if (gapMap == null || gapMap.length < seq.getLength())
593 boolean[] tg = gapMap;
594 gapMap = new boolean[seq.getLength()];
595 System.arraycopy(tg, 0, gapMap, 0, tg.length);
596 for (int p = tg.length; p < gapMap.length; p++)
598 gapMap[p] = false; // init as a gap
601 for (int apos : sq.gapMap())
603 char sqc = sq.getCharAt(apos);
604 if (!filterNonStandardResidues
605 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
606 : ResidueProperties.nucleotideIndex[sqc] < 5))
608 gapMap[apos] = true; // aligned and real amino acid residue
615 // TODO: add ability to exclude hidden regions
616 seqs.add(seq = new jalview.datamodel.Sequence(newname,
617 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
618 sq.getSequenceAsString(start, end + 1))));
619 // for annotation need to also record map to sequence start/end
621 // then transfer back to original sequence on return.
623 if (seq.getLength() > ln)
625 ln = seq.getLength();
629 if (alignedSeqs && submitGaps)
632 for (int i = 0; i < gapMap.length; i++)
639 // try real hard to return something submittable
640 // TODO: some of AAcon measures need a minimum of two or three amino
641 // acids at each position, and AAcon doesn't gracefully degrade.
642 for (int p = 0; p < seqs.size(); p++)
644 SequenceI sq = seqs.get(p);
645 // strip gapped columns
646 char[] padded = new char[realw],
647 orig = sq.getSequence();
648 for (int i = 0, pp = 0; i < realw; pp++)
652 if (orig.length > pp)
654 padded[i++] = orig[pp];
662 seqs.set(p, new jalview.datamodel.Sequence(sq.getName(),
663 new String(padded)));
670 public void updateAnnotation()
672 updateResultAnnotation(false);
675 public void updateResultAnnotation(boolean immediate)
677 if ((immediate || !calcMan.isWorking(this)) && running != null
678 && running.hasResults())
680 List<AlignmentAnnotation> ourAnnot = running.getAnnotation();
681 updateOurAnnots(ourAnnot);
686 * notify manager that we have started, and wait for a free calculation slot
688 * @return true if slot is obtained and work still valid, false if another
689 * thread has done our work for us.
691 protected boolean checkDone()
693 calcMan.notifyStart(this);
694 ap.paintAlignment(false, false);
695 while (!calcMan.notifyWorking(this))
697 if (calcMan.isWorking(this))
705 ap.paintAlignment(false, false);
709 } catch (Exception ex)
711 ex.printStackTrace();
714 if (alignViewport.isClosed())
722 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
724 List<AlignmentAnnotation> our = ourAnnots;
725 ourAnnots = ourAnnot;
726 AlignmentI alignment = alignViewport.getAlignment();
731 for (AlignmentAnnotation an : our)
733 if (!ourAnnots.contains(an))
735 // remove the old annotation
736 alignment.deleteAnnotation(an);
741 // validate rows and update Alignmment state
742 for (AlignmentAnnotation an : ourAnnots)
744 alignViewport.getAlignment().validateAnnotation(an);
746 // TODO: may need a menu refresh after this
747 // af.setMenusForViewport();
748 ap.adjustAnnotationHeight();
752 public SequenceAnnotationServiceI getService()