1 package jalview.ws2.operations;
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
9 import java.util.Objects;
11 import jalview.analysis.AlignSeq;
12 import jalview.analysis.AlignmentAnnotationUtils;
13 import jalview.analysis.SeqsetUtils;
14 import jalview.api.AlignCalcManagerI2;
15 import jalview.api.AlignViewportI;
16 import jalview.api.AlignmentViewPanel;
17 import jalview.api.FeatureColourI;
18 import jalview.api.PollableAlignCalcWorkerI;
19 import jalview.bin.Cache;
20 import jalview.datamodel.Alignment;
21 import jalview.datamodel.AlignmentAnnotation;
22 import jalview.datamodel.AlignmentI;
23 import jalview.datamodel.AnnotatedCollectionI;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.ContiguousI;
26 import jalview.datamodel.Mapping;
27 import jalview.datamodel.Sequence;
28 import jalview.datamodel.SequenceI;
29 import jalview.datamodel.features.FeatureMatcherSetI;
30 import jalview.gui.AlignFrame;
31 import jalview.gui.AlignViewport;
32 import jalview.gui.IProgressIndicator;
33 import jalview.gui.IProgressIndicatorHandler;
34 import jalview.io.FeaturesFile;
35 import jalview.schemes.FeatureSettingsAdapter;
36 import jalview.schemes.ResidueProperties;
37 import jalview.util.MapList;
38 import jalview.workers.AlignCalcManager2;
39 import jalview.ws.params.ArgumentI;
40 import jalview.ws2.WSJob;
41 import jalview.ws2.WSJobStatus;
42 import jalview.ws2.WebServiceI;
43 import jalview.ws2.gui.ProgressBarUpdater;
45 import static java.lang.String.format;
47 public class AnnotationServiceWorker implements PollableAlignCalcWorkerI
49 private AnnotationOperation operation;
50 private WebServiceI service;
51 private List<ArgumentI> args;
52 private AlignViewport viewport;
53 private AlignmentViewPanel alignPanel;
54 List<SequenceI> sequences;
55 private IProgressIndicator progressIndicator;
56 private AlignFrame frame;
57 private final AlignCalcManagerI2 calcMan;
58 private Map<String, SequenceI> seqNames;
60 * indicates columns consisting of gaps only
62 boolean[] gapMap = new boolean[0];
64 boolean transferSequenceFeatures = false;
66 private List<AlignmentAnnotation> ourAnnots;
68 private int exceptionCount = MAX_RETRY;
69 private static final int MAX_RETRY = 5;
71 AnnotationServiceWorker(AnnotationOperation operation, WebServiceI service,
72 List<ArgumentI> args, AlignViewport viewport, AlignmentViewPanel alignPanel,
73 IProgressIndicator progressIndicator, AlignFrame frame, AlignCalcManagerI2 calcMan)
75 this.operation = operation;
76 this.service = service;
78 this.viewport = viewport;
79 this.alignPanel = alignPanel;
80 this.progressIndicator = progressIndicator;
82 this.calcMan = calcMan;
86 public String getCalcName()
88 return service.getName();
92 public boolean involves(AlignmentAnnotation annot)
94 return ourAnnots != null && ourAnnots.contains(annot);
98 public void updateAnnotation()
100 if (!calcMan.isWorking(this) && job != null && !job.getStatus().isCompleted())
102 // is it correct to store annotations in a field and use them here?
103 updateResultAnnotation(ourAnnots);
108 public void removeAnnotation()
110 if (ourAnnots != null && viewport != null)
112 AlignmentI alignment = viewport.getAlignment();
113 synchronized (ourAnnots)
115 for (AlignmentAnnotation aa : ourAnnots)
117 alignment.deleteAnnotation(aa, true);
124 public boolean isDeletable()
130 public void startUp() throws IOException
132 if (viewport.isClosed())
136 /* What "bySequence" means in this context and
137 * what is the SelectionGroup and why is it only relevant when
138 * not dealing with alignment analysis? */
139 var bySequence = !operation.isAlignmentAnalysis();
140 sequences = prepareInput(viewport.getAlignment(),
141 bySequence ? viewport.getSelectionGroup() : null);
142 if (sequences == null)
144 Cache.log.info("Sequences for analysis service were null");
147 if (!checkInputSequencesValid(sequences))
149 Cache.log.info("Sequences for analysis service were not valid");
151 Cache.log.debug(format("submitting %d sequences to %s", sequences.size(),
153 job = new WSJob(service.getProviderName(), service.getName(),
154 service.getHostName());
155 // Should this part be moved out of this class to one of the gui
157 if (progressIndicator != null)
159 job.addPropertyChangeListener("status", new ProgressBarUpdater(progressIndicator));
160 progressIndicator.registerHandler(job.getUid(), new IProgressIndicatorHandler()
163 public boolean cancelActivity(long id)
165 calcMan.cancelWorker(AnnotationServiceWorker.this);
170 public boolean canCancel()
172 return isDeletable();
176 String jobId = service.submit(sequences, args);
178 Cache.log.debug(format("Service %s: submitted job id %s",
179 service.getHostName(), jobId));
182 private List<SequenceI> prepareInput(AlignmentI alignment,
183 AnnotatedCollectionI inputSeqs)
185 if (alignment == null || alignment.getWidth() <= 0 ||
186 alignment.getSequences() == null)
188 if (alignment.isNucleotide() && !operation.isNucleotideOperation())
190 if (!alignment.isNucleotide() && !operation.isProteinOperation())
192 if (inputSeqs == null || inputSeqs.getWidth() <= 0 ||
193 inputSeqs.getSequences() == null || inputSeqs.getSequences().size() < 1)
194 inputSeqs = alignment;
196 List<SequenceI> seqs = new ArrayList<>();
197 final boolean submitGaps = operation.isAlignmentAnalysis();
198 final int minlen = 10;
199 int ln = -1; // I think this variable is redundant
200 if (!operation.isAlignmentAnalysis())
201 seqNames = new HashMap<>();
202 start = inputSeqs.getStartRes();
203 end = inputSeqs.getEndRes();
204 // TODO: URGENT! unify with JPred / MSA code to handle hidden regions
206 // TODO: push attributes into WsJob instance (so they can be safely
207 // persisted/restored
208 for (SequenceI sq : inputSeqs.getSequences())
211 // is it trying to find the length of a sequence excluding gaps?
212 if (!operation.isAlignmentAnalysis())
213 // why starting at positions to the right from the end/start?
214 sqlen = sq.findPosition(end + 1) - sq.findPosition(start + 1);
216 sqlen = sq.getEnd() - sq.getStart();
219 String newName = SeqsetUtils.unique_name(seqs.size());
220 if (seqNames != null)
222 seqNames.put(newName, sq);
227 seq = new Sequence(newName, sq.getSequenceAsString());
229 if (gapMap == null || gapMap.length < seq.getLength())
231 boolean[] tg = gapMap;
232 gapMap = new boolean[seq.getLength()];
233 System.arraycopy(tg, 0, gapMap, 0, tg.length);
234 for (int p = tg.length; p < gapMap.length; p++)
236 gapMap[p] = false; // init as a gap
239 for (int apos : sq.gapMap())
241 char sqc = sq.getCharAt(apos);
242 boolean isStandard = sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
243 : ResidueProperties.nucleotideIndex[sqc] < 5;
244 if (!operation.getFilterNonStandardSymbols() || isStandard)
252 // TODO: add ability to exclude hidden regions
253 String sqstring = sq.getSequenceAsString(start, end + 1);
254 seq = new Sequence(newName,
255 AlignSeq.extractGaps(jalview.util.Comparison.GapChars, sqstring));
257 // for annotation need to also record map to sequence start/end
259 // then transfer back to original sequence on return.
261 ln = Integer.max(seq.getLength(), ln);
264 if (operation.getNeedsAlignedSequences() && submitGaps)
267 for (int i = 0; i < gapMap.length; i++)
274 // try real hard to return something submittable
275 // TODO: some of AAcon measures need a minimum of two or three amino
276 // acids at each position, and AAcon doesn't gracefully degrade.
277 for (int p = 0; p < seqs.size(); p++)
279 SequenceI sq = seqs.get(p);
280 // strip gapped columns
281 char[] padded = new char[realw];
282 char[] orig = sq.getSequence();
283 for (int i = 0, pp = 0; i < realw; pp++)
287 if (orig.length > pp)
289 padded[i++] = orig[pp];
297 seqs.set(p, new Sequence(sq.getName(), new String(padded)));
303 private boolean checkInputSequencesValid(List<SequenceI> sequences)
306 boolean allowProtein = operation.isProteinOperation(),
307 allowNucleotides = operation.isNucleotideOperation();
308 for (SequenceI sq : sequences)
310 if (sq.getStart() <= sq.getEnd() &&
311 (sq.isProtein() ? allowProtein : allowNucleotides))
316 return nvalid >= operation.getMinSequences();
320 public boolean poll() throws IOException
322 if (!job.getStatus().isDone() && !job.getStatus().isFailed())
324 Cache.log.debug(format("Polling job %s", job));
327 service.updateProgress(job);
328 exceptionCount = MAX_RETRY;
329 } catch (IOException e)
331 Cache.log.error(format("Polling job %s failed.", job), e);
332 if (--exceptionCount <= 0)
334 job.setStatus(WSJobStatus.SERVER_ERROR);
335 Cache.log.warn(format("Attempts limit exceeded. Dropping job %s.", job));
337 } catch (OutOfMemoryError e)
339 job.setStatus(WSJobStatus.BROKEN);
340 Cache.log.error(format("Out of memory when retrieving job %s", job), e);
343 return job.getStatus().isDone() || job.getStatus().isFailed();
352 } catch (IOException e)
354 Cache.log.error(format("Failed to cancel job %s.", job), e);
361 Cache.log.debug(format("Polling loop exited, job %s is %s", job, job.getStatus()));
362 if (!job.getStatus().isCompleted())
366 List<AlignmentAnnotation> outputAnnotations = null;
369 outputAnnotations = operation.annotationSupplier
370 .getResult(job, sequences, viewport);
371 } catch (IOException e)
373 Cache.log.error(format("Couldn't retrieve features for job %s.", job), e);
375 if (outputAnnotations != null)
376 Cache.log.debug(format("Obtained %d annotation rows.", outputAnnotations.size()));
378 Cache.log.debug("Obtained no annotations.");
379 Map<String, FeatureColourI> featureColours = new HashMap<>();
380 Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
381 FeaturesFile featuresFile;
384 // I think there should be a better way for obtaining features
385 // Are the features added to the sequences here?
386 featuresFile = operation.featuresSupplier.getResult(job, sequences, viewport);
387 if (featuresFile != null)
389 Alignment aln = new Alignment(sequences.toArray(new SequenceI[0]));
390 // I do nothing with the featureFilters object
391 featuresFile.parse(aln, featureColours, true);
393 } catch (IOException e)
395 Cache.log.error(format("Couldn't retrieve features for job %s", job), e);
397 Cache.log.debug(format("There are %d feature colours and %d filters.",
398 featureColours.size(), featureFilters.size()));
399 if (outputAnnotations != null)
401 for (AlignmentAnnotation aa : outputAnnotations)
403 if (aa.getCalcId() == null || aa.getCalcId().equals(""))
405 aa.setCalcId(service.getName());
407 // Can't services other than alignment analysis be interactive?
408 // What's the point of storing that information in the annotation?
409 aa.autoCalculated = operation.isAlignmentAnalysis() && operation.isInteractive();
411 updateResultAnnotation(outputAnnotations);
412 if (transferSequenceFeatures)
414 Cache.log.debug(format("Updating feature display settings and transferring"
415 + "features fron job %s at %s", job, service.getHostName()));
416 viewport.applyFeaturesStyle(new FeatureSettingsAdapter()
419 public FeatureColourI getFeatureColour(String type)
421 return featureColours.get(type);
425 public FeatureMatcherSetI getFeatureFilters(String type)
427 return featureFilters.get(type);
431 public boolean isFeatureDisplayed(String type)
433 return featureColours.containsKey(type);
436 if (frame.alignPanel == alignPanel)
438 viewport.setShowSequenceFeatures(true);
439 frame.setMenusForViewport();
443 Cache.log.debug("Annotation service task finished.");
446 // What is the purpose of this method?
447 // When is it called (apart from the above)?
448 private void updateResultAnnotation(List<AlignmentAnnotation> annotations)
450 var currentAnnotations = Objects.requireNonNullElse(
451 viewport.getAlignment().getAlignmentAnnotation(),
452 new AlignmentAnnotation[0]);
453 List<AlignmentAnnotation> newAnnots = new ArrayList<>();
454 // what is the graph group and why starting from 1?
456 for (AlignmentAnnotation alna : currentAnnotations)
458 graphGroup = Integer.max(graphGroup, alna.graphGroup);
460 for (AlignmentAnnotation ala : annotations)
462 if (ala.graphGroup > 0)
464 ala.graphGroup += graphGroup;
467 // stores original sequence, in what case it ends up as null?
468 SequenceI aseq = null;
469 if (ala.sequenceRef != null)
471 SequenceI seq = seqNames.get(ala.sequenceRef.getName());
473 while (seq.getDatasetSequence() != null)
475 seq = seq.getDatasetSequence();
478 Annotation[] resAnnot = ala.annotations;
479 Annotation[] gappedAnnot = new Annotation[Math
480 .max(viewport.getAlignment().getWidth(), gapMap.length)];
481 // is it adding gaps which were previously removed to the annotation?
482 for (int p = 0, ap = start; ap < gappedAnnot.length; ap++)
484 if (gapMap != null && gapMap.length > ap && !gapMap[ap])
486 gappedAnnot[ap] = new Annotation("", "", ' ', Float.NaN);
488 else if (p < resAnnot.length)
490 gappedAnnot[ap] = resAnnot[p++];
493 // replacing sequence with the original one?
494 ala.sequenceRef = aseq;
495 ala.annotations = gappedAnnot;
496 AlignmentAnnotation newAnnot = viewport.getAlignment()
497 .updateFromOrCopyAnnotation(ala);
500 aseq.addAlignmentAnnotation(newAnnot);
501 newAnnot.adjustForAlignment();
502 AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(newAnnot,
503 newAnnot.label, newAnnot.getCalcId());
505 newAnnots.add(newAnnot);
508 for (SequenceI sq : sequences)
510 // what are DBRefs? why are they relevant here?
511 if (!sq.getFeatures().hasFeatures() &&
512 (sq.getDBRefs() == null || sq.getDBRefs().size() == 0))
516 transferSequenceFeatures = true;
517 SequenceI seq = seqNames.get(sq.getName());
519 ContiguousI seqRange = seq.findPositions(start, end);
521 while ((dseq = seq).getDatasetSequence() != null)
523 seq = seq.getDatasetSequence();
525 List<ContiguousI> sourceRange = new ArrayList<>();
526 if (gapMap != null && gapMap.length > end)
528 int lastcol = start, col = start;
531 if (col == end || !gapMap[col])
533 if (lastcol <= col - 1)
535 seqRange = seq.findPositions(lastcol, col);
536 sourceRange.add(seqRange);
540 } while (++col < end);
544 sourceRange.add(seq.findPositions(start, end));
547 int sourceStartEnd[] = new int[sourceRange.size() * 2];
548 for (ContiguousI range : sourceRange)
550 sourceStartEnd[i++] = range.getBegin();
551 sourceStartEnd[i++] = range.getEnd();
553 Mapping mp = new Mapping(new MapList(sourceStartEnd,
554 new int[] { seq.getStart(), seq.getEnd() }, 1, 1));
555 dseq.transferAnnotation(sq, mp);
557 updateOurAnnots(newAnnots);
560 protected void updateOurAnnots(List<AlignmentAnnotation> annots)
562 List<AlignmentAnnotation> our = ourAnnots;
563 ourAnnots = Collections.synchronizedList(annots);
564 AlignmentI alignment = viewport.getAlignment();
569 for (AlignmentAnnotation an : our)
571 if (!ourAnnots.contains(an))
573 // remove the old annotation
574 alignment.deleteAnnotation(an);
580 // validate rows and update Alignment state
581 synchronized (ourAnnots)
583 for (AlignmentAnnotation an : ourAnnots)
585 viewport.getAlignment().validateAnnotation(an);
588 // TODO: may need a menu refresh after this
589 // af.setMenusForViewport();
590 alignPanel.adjustAnnotationHeight();