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.SequenceAnnotationServiceI;
43 import jalview.ws.api.WSAnnotationCalcManagerI;
44 import jalview.ws.gui.AnnotationWsJob;
45 import jalview.ws.jws2.dm.AAConSettings;
46 import jalview.ws.jws2.jabaws2.Jws2Instance;
47 import jalview.ws.params.ArgumentI;
48 import jalview.ws.params.WsParamSetI;
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.List;
55 public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
56 implements WSAnnotationCalcManagerI
59 protected Jws2Instance service;
61 protected WsParamSetI preset;
63 protected List<ArgumentI> 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, arguments),
90 * @return null or a string used to recover all annotation generated by this
93 public String getCalcId()
95 return service.getAlignAnalysisUI() == null ? null
96 : service.getAlignAnalysisUI().getCalcId();
99 public WsParamSetI getPreset()
104 public List<ArgumentI> getArguments()
110 * reconfigure and restart the AAConClient. This method will spawn a new
111 * thread that will wait until any current jobs are finished, modify the
112 * parameters and restart the conservation calculation with the new values.
115 * @param newarguments
117 public void updateParameters(final WsParamSetI newpreset,
118 final List<ArgumentI> newarguments)
121 arguments = newarguments;
122 calcMan.startWorker(this);
123 initViewportParams();
125 protected boolean alignedSeqs = true;
127 protected boolean nucleotidesAllowed = false;
129 protected boolean proteinAllowed = false;
132 * record sequences for mapping result back to afterwards
134 protected boolean bySequence = false;
136 protected Map<String, SequenceI> seqNames;
138 // TODO: convert to bitset
139 protected boolean[] gapMap;
147 private AlignFrame alignFrame;
149 public boolean[] getGapMap()
154 public SeqAnnotationServiceCalcWorker(AlignViewportI alignViewport,
155 AlignmentViewPanel alignPanel)
157 super(alignViewport, alignPanel);
160 public SeqAnnotationServiceCalcWorker(Jws2Instance service, AlignFrame alignFrame,
161 WsParamSetI preset, List<ArgumentI> paramset)
163 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
164 // TODO: both these fields needed ?
165 this.alignFrame = alignFrame;
166 this.guiProgress = alignFrame;
167 this.preset = preset;
168 this.arguments = paramset;
169 this.service = service;
172 annotService = (jalview.ws.api.SequenceAnnotationServiceI) service
174 } catch (ClassCastException cce)
176 JvOptionPane.showMessageDialog(Desktop.desktop,
177 MessageManager.formatMessage(
178 "label.service_called_is_not_an_annotation_service",
180 { service.getName() }),
181 MessageManager.getString("label.internal_jalview_error"),
182 JvOptionPane.WARNING_MESSAGE);
185 // configure submission flags
186 proteinAllowed = service.isProteinService();
187 nucleotidesAllowed = service.isNucleotideService();
188 alignedSeqs = service.isNeedsAlignedSequences();
189 bySequence = !service.isAlignmentAnalysis();
190 filterNonStandardResidues = service.isFilterSymbols();
191 min_valid_seqs = service.getMinimumInputSequences();
193 if (service.isInteractiveUpdate())
195 initViewportParams();
201 * @return true if the submission thread should attempt to submit data
203 public boolean hasService()
205 return annotService != null;
208 protected jalview.ws.api.SequenceAnnotationServiceI annotService = null;
210 volatile JobId rslt = null;
212 AnnotationWsJob running = null;
214 private int min_valid_seqs;
224 long progressId = -1;
226 int serverErrorsLeft = 3;
227 final boolean cancellable = CancellableI.class
228 .isAssignableFrom(annotService.getClass());
229 StringBuffer msg = new StringBuffer();
236 List<SequenceI> seqs = getInputSequences(
237 alignViewport.getAlignment(),
238 bySequence ? alignViewport.getSelectionGroup() : null);
240 if (seqs == null || !checkValidInputSeqs(seqs))
242 jalview.bin.Cache.log.debug(
243 "Sequences for analysis service were null or not valid");
244 calcMan.workerComplete(this);
248 AlignmentAnnotation[] aa = alignViewport.getAlignment()
249 .getAlignmentAnnotation();
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;
302 Cache.log.debug("Updating status for annotation service.");
303 annotService.updateStatus(running);
305 if (running.isFinished())
307 Cache.log.debug("Analysis service job reported finished.");
312 Cache.log.debug("Status now " + running.getState());
315 if (calcMan.isPending(this) && isInteractiveUpdate())
317 Cache.log.debug("Analysis service job is stale. aborting.");
318 // job has become stale.
321 // cancel this job and yield to the new job
325 && ((CancellableI) annotService).cancel(running))
327 System.err.println("Cancelled AACon job: " + rslt);
331 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
334 } catch (Exception x)
339 rslt = running.getJobHandle();
343 // pull any stats - some services need to flush log output before
344 // results are available
345 Cache.log.debug("Updating progress log for annotation service.");
349 annotService.updateJobProgress(running);
350 } catch (Throwable thr)
352 Cache.log.debug("Ignoring exception during progress update.",
355 Cache.log.trace("Result of poll: " + running.getStatus());
357 if (!finished && !running.isFailed())
361 Cache.log.debug("Analysis service job thread sleeping.");
363 Cache.log.debug("Analysis service job thread woke.");
364 } catch (InterruptedException x)
371 // TODO: need to poll/retry
372 if (serverErrorsLeft > 0)
377 } catch (InterruptedException x)
381 // configure job with the associated view's feature renderer, if one
383 // TODO: here one would also grab the 'master feature renderer' in order
385 // features automatically according to user preferences
386 running.setFeatureRenderer(
387 ((jalview.gui.AlignmentPanel) ap).cloneFeatureRenderer());
388 Cache.log.debug("retrieving job results.");
389 List<AlignmentAnnotation> returnedAnnot = annotService
390 .getAlignmentAnnotation(running, this);
391 Cache.log.debug("Obtained " + (returnedAnnot == null ? "no rows"
392 : ("" + returnedAnnot.size())));
393 running.setAnnotation(returnedAnnot);
395 if (running.hasResults())
397 jalview.bin.Cache.log.debug("Updating result annotation from Job "
398 + rslt + " at " + service.getUri());
399 updateResultAnnotation(true);
400 if (running.isTransferSequenceFeatures())
402 jalview.bin.Cache.log.debug(
403 "Updating feature display settings and transferring features from Job "
404 + rslt + " at " + service.getUri());
405 ((jalview.gui.AlignmentPanel) ap)
406 .updateFeatureRendererFrom(running.getFeatureRenderer());
407 // TODO: JAL-1150 - create sequence feature settings API for defining
408 // styles and enabling/disabling feature overlay on alignment panel
410 if (alignFrame.alignPanel == ap)
412 // only do this if the alignFrame is currently showing this view.
413 Desktop.getAlignFrameFor(alignViewport)
414 .setShowSeqFeatures(true);
417 ap.adjustAnnotationHeight();
419 Cache.log.debug("Annotation Service Worker thread finished.");
421 // TODO: use service specitic exception handlers
422 // catch (JobSubmissionException x)
425 // System.err.println(
426 // "submission error with " + getServiceActionText() + " :");
427 // x.printStackTrace();
428 // calcMan.disableWorker(this);
429 // } catch (ResultNotAvailableException x)
431 // System.err.println("collection error:\nJob ID: " + rslt);
432 // x.printStackTrace();
433 // calcMan.disableWorker(this);
435 // } catch (OutOfMemoryError error)
437 // calcMan.disableWorker(this);
439 // ap.raiseOOMWarning(getServiceActionText(), error);
443 calcMan.disableWorker(this);
446 .println("Blacklisting worker due to unexpected exception:");
451 calcMan.workerComplete(this);
454 calcMan.workerComplete(this);
455 if (guiProgress != null && progressId != -1)
457 guiProgress.setProgressBar("", progressId);
459 // TODO: may not need to paintAlignment again !
460 ap.paintAlignment(false, false);
462 if (msg.length() > 0)
464 // TODO: stash message somewhere in annotation or alignment view.
465 // code below shows result in a text box popup
467 * jalview.gui.CutAndPasteTransfer cap = new
468 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
469 * jalview.gui.Desktop.addInternalFrame(cap,
470 * "Job Status for "+getServiceActionText(), 600, 400);
478 * validate input for dynamic/non-dynamic update context TODO: move to
479 * analysis interface ?
482 * @return true if input is valid
484 boolean checkValidInputSeqs(List<SequenceI> seqs)
487 for (SequenceI sq : seqs)
489 if (sq.getStart() <= sq.getEnd()
490 && (sq.isProtein() ? proteinAllowed : nucleotidesAllowed))
493 || sq.getLength() == (sq.getEnd() - sq.getStart() + 1))
499 return nvalid >= min_valid_seqs;
502 public void cancelCurrentJob()
506 String id = running.getJobId();
507 if (((CancellableI) annotService).cancel(running))
509 System.err.println("Cancelled job " + id);
513 System.err.println("Job " + id + " couldn't be cancelled.");
515 } catch (Exception q)
522 * Interactive updating. Analysis calculations that work on the currently
523 * displayed alignment data should cancel existing jobs when the input data
526 * @return true if a running job should be cancelled because new input data is
527 * available for analysis
529 boolean isInteractiveUpdate()
531 return service.isInteractiveUpdate();
535 * decide what sequences will be analysed TODO: refactor to generate
536 * List<SequenceI> for submission to service interface
542 public List<SequenceI> getInputSequences(AlignmentI alignment,
543 AnnotatedCollectionI inputSeqs)
545 if (alignment == null || alignment.getWidth() <= 0
546 || alignment.getSequences() == null || alignment.isNucleotide()
547 ? !nucleotidesAllowed
552 if (inputSeqs == null || inputSeqs.getWidth() <= 0
553 || inputSeqs.getSequences() == null
554 || inputSeqs.getSequences().size() < 1)
556 inputSeqs = alignment;
559 List<SequenceI> seqs = new ArrayList<>();
565 seqNames = new HashMap<>();
567 gapMap = new boolean[0];
568 start = inputSeqs.getStartRes();
569 end = inputSeqs.getEndRes();
570 // TODO: URGENT! unify with JPred / MSA code to handle hidden regions
572 // TODO: push attributes into WsJob instance (so they can be safely
573 // persisted/restored
574 for (SequenceI sq : (inputSeqs.getSequences()))
577 ? sq.findPosition(end + 1)
578 - sq.findPosition(start + 1) > minlen - 1
579 : sq.getEnd() - sq.getStart() > minlen - 1)
581 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
582 // make new input sequence with or without gaps
583 if (seqNames != null)
585 seqNames.put(newname, sq);
590 seqs.add(seq = new jalview.datamodel.Sequence(newname,
591 sq.getSequenceAsString()));
592 if (gapMap == null || gapMap.length < seq.getLength())
594 boolean[] tg = gapMap;
595 gapMap = new boolean[seq.getLength()];
596 System.arraycopy(tg, 0, gapMap, 0, tg.length);
597 for (int p = tg.length; p < gapMap.length; p++)
599 gapMap[p] = false; // init as a gap
602 for (int apos : sq.gapMap())
604 char sqc = sq.getCharAt(apos);
605 if (!filterNonStandardResidues
606 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
607 : ResidueProperties.nucleotideIndex[sqc] < 5))
609 gapMap[apos] = true; // aligned and real amino acid residue
616 // TODO: add ability to exclude hidden regions
617 seqs.add(seq = new jalview.datamodel.Sequence(newname,
618 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
619 sq.getSequenceAsString(start, end + 1))));
620 // for annotation need to also record map to sequence start/end
622 // then transfer back to original sequence on return.
624 if (seq.getLength() > ln)
626 ln = seq.getLength();
630 if (alignedSeqs && submitGaps)
633 for (int i = 0; i < gapMap.length; i++)
640 // try real hard to return something submittable
641 // TODO: some of AAcon measures need a minimum of two or three amino
642 // acids at each position, and AAcon doesn't gracefully degrade.
643 for (int p = 0; p < seqs.size(); p++)
645 SequenceI sq = seqs.get(p);
646 // strip gapped columns
647 char[] padded = new char[realw],
648 orig = sq.getSequence();
649 for (int i = 0, pp = 0; i < realw; pp++)
653 if (orig.length > pp)
655 padded[i++] = orig[pp];
663 seqs.set(p, new jalview.datamodel.Sequence(sq.getName(),
664 new String(padded)));
671 public void updateAnnotation()
673 updateResultAnnotation(false);
676 public void updateResultAnnotation(boolean immediate)
678 if ((immediate || !calcMan.isWorking(this)) && running != null
679 && running.hasResults())
681 List<AlignmentAnnotation> ourAnnot = running.getAnnotation();
682 updateOurAnnots(ourAnnot);
687 * notify manager that we have started, and wait for a free calculation slot
689 * @return true if slot is obtained and work still valid, false if another
690 * thread has done our work for us.
692 protected boolean checkDone()
694 calcMan.notifyStart(this);
695 ap.paintAlignment(false, false);
696 while (!calcMan.notifyWorking(this))
698 if (calcMan.isWorking(this))
706 ap.paintAlignment(false, false);
710 } catch (Exception ex)
712 ex.printStackTrace();
715 if (alignViewport.isClosed())
723 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
725 List<AlignmentAnnotation> our = ourAnnots;
726 ourAnnots = ourAnnot;
727 AlignmentI alignment = alignViewport.getAlignment();
732 for (AlignmentAnnotation an : our)
734 if (!ourAnnots.contains(an))
736 // remove the old annotation
737 alignment.deleteAnnotation(an);
742 // validate rows and update Alignmment state
743 for (AlignmentAnnotation an : ourAnnots)
745 alignViewport.getAlignment().validateAnnotation(an);
747 // TODO: may need a menu refresh after this
748 // af.setMenusForViewport();
749 ap.adjustAnnotationHeight();
753 public SequenceAnnotationServiceI getService()