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;
59 boolean[] gapMap = new boolean[0];
61 boolean transferSequenceFeatures = false;
63 private List<AlignmentAnnotation> ourAnnots;
65 private int exceptionCount = MAX_RETRY;
66 private static final int MAX_RETRY = 5;
68 AnnotationServiceWorker(AnnotationOperation operation, WebServiceI service,
69 List<ArgumentI> args, AlignViewport viewport, AlignmentViewPanel alignPanel,
70 IProgressIndicator progressIndicator, AlignFrame frame, AlignCalcManagerI2 calcMan)
72 this.operation = operation;
73 this.service = service;
75 this.viewport = viewport;
76 this.alignPanel = alignPanel;
77 this.progressIndicator = progressIndicator;
79 this.calcMan = calcMan;
83 public String getCalcName()
85 return service.getName();
89 public boolean involves(AlignmentAnnotation annot)
91 return ourAnnots != null && ourAnnots.contains(annot);
95 public void updateAnnotation()
97 if (!calcMan.isWorking(this) && job != null && !job.getStatus().isCompleted())
99 updateResultAnnotation(ourAnnots);
104 public void removeAnnotation()
106 if (ourAnnots != null && viewport != null)
108 AlignmentI alignment = viewport.getAlignment();
109 synchronized (ourAnnots)
111 for (AlignmentAnnotation aa : ourAnnots)
113 alignment.deleteAnnotation(aa, true);
120 public boolean isDeletable()
126 public void startUp() throws IOException
128 if (viewport.isClosed())
132 var bySequence = !operation.isAlignmentAnalysis();
133 sequences = prepareInput(viewport.getAlignment(),
134 bySequence ? viewport.getSelectionGroup() : null);
135 if (sequences == null)
137 Cache.log.info("Sequences for analysis service were null");
140 if (!checkInputSequencesValid(sequences))
142 Cache.log.info("Sequences for analysis service were not valid");
144 Cache.log.debug(format("submitting %d sequences to %s", sequences.size(),
146 job = new WSJob(service.getProviderName(), service.getName(),
147 service.getHostName());
148 if (progressIndicator != null)
150 job.addPropertyChangeListener("status", new ProgressBarUpdater(progressIndicator));
151 progressIndicator.registerHandler(job.getUid(), new IProgressIndicatorHandler()
154 public boolean cancelActivity(long id)
156 calcMan.cancelWorker(AnnotationServiceWorker.this);
161 public boolean canCancel()
163 return isDeletable();
167 String jobId = service.submit(sequences, args);
169 Cache.log.debug(format("Service %s: submitted job id %s",
170 service.getHostName(), jobId));
173 private List<SequenceI> prepareInput(AlignmentI alignment,
174 AnnotatedCollectionI inputSeqs)
176 if (alignment == null || alignment.getWidth() <= 0 ||
177 alignment.getSequences() == null)
179 if (alignment.isNucleotide() && !operation.isNucleotideOperation())
181 if (!alignment.isNucleotide() && !operation.isProteinOperation())
183 if (inputSeqs == null || inputSeqs.getWidth() <= 0 ||
184 inputSeqs.getSequences() == null || inputSeqs.getSequences().size() < 1)
185 inputSeqs = alignment;
187 List<SequenceI> seqs = new ArrayList<>();
188 final boolean submitGaps = operation.isAlignmentAnalysis();
189 final int minlen = 10;
191 // FIXME don't return values by class parameters
192 if (!operation.isAlignmentAnalysis())
193 seqNames = new HashMap<>();
194 start = inputSeqs.getStartRes();
195 end = inputSeqs.getEndRes();
196 // TODO: URGENT! unify with JPred / MSA code to handle hidden regions
198 // TODO: push attributes into WsJob instance (so they can be safely
199 // persisted/restored
200 for (SequenceI sq : inputSeqs.getSequences())
203 if (!operation.isAlignmentAnalysis())
204 sqlen = sq.findPosition(end + 1) - sq.findPosition(start + 1);
206 sqlen = sq.getEnd() - sq.getStart();
209 String newName = SeqsetUtils.unique_name(seqs.size());
210 if (seqNames != null)
212 seqNames.put(newName, sq);
217 seq = new Sequence(newName, sq.getSequenceAsString());
219 if (gapMap == null || gapMap.length < seq.getLength())
221 boolean[] tg = gapMap;
222 gapMap = new boolean[seq.getLength()];
223 System.arraycopy(tg, 0, gapMap, 0, tg.length);
224 for (int p = tg.length; p < gapMap.length; p++)
226 gapMap[p] = false; // init as a gap
229 for (int apos : sq.gapMap())
231 char sqc = sq.getCharAt(apos);
232 boolean isStandard = sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
233 : ResidueProperties.nucleotideIndex[sqc] < 5;
234 if (!operation.getFilterNonStandardSymbols() || isStandard)
242 // TODO: add ability to exclude hidden regions
243 String sqstring = sq.getSequenceAsString(start, end + 1);
244 seq = new Sequence(newName,
245 AlignSeq.extractGaps(jalview.util.Comparison.GapChars, sqstring));
247 // for annotation need to also record map to sequence start/end
249 // then transfer back to original sequence on return.
251 ln = Integer.max(seq.getLength(), ln);
254 if (operation.getNeedsAlignedSequences() && submitGaps)
257 for (int i = 0; i < gapMap.length; i++)
264 // try real hard to return something submittable
265 // TODO: some of AAcon measures need a minimum of two or three amino
266 // acids at each position, and AAcon doesn't gracefully degrade.
267 for (int p = 0; p < seqs.size(); p++)
269 SequenceI sq = seqs.get(p);
270 // strip gapped columns
271 char[] padded = new char[realw];
272 char[] orig = sq.getSequence();
273 for (int i = 0, pp = 0; i < realw; pp++)
277 if (orig.length > pp)
279 padded[i++] = orig[pp];
287 seqs.set(p, new Sequence(sq.getName(), new String(padded)));
293 private boolean checkInputSequencesValid(List<SequenceI> sequences)
296 boolean allowProtein = operation.isProteinOperation(),
297 allowNucleotides = operation.isNucleotideOperation();
298 for (SequenceI sq : sequences)
300 if (sq.getStart() <= sq.getEnd() &&
301 (sq.isProtein() ? allowProtein : allowNucleotides))
306 return nvalid >= operation.getMinSequences();
310 public boolean poll() throws IOException
312 if (!job.getStatus().isDone() && !job.getStatus().isFailed())
314 Cache.log.debug(format("Polling job %s", job));
317 service.updateProgress(job);
318 exceptionCount = MAX_RETRY;
319 } catch (IOException e)
321 Cache.log.error(format("Polling job %s failed.", job), e);
322 if (--exceptionCount <= 0)
324 job.setStatus(WSJobStatus.SERVER_ERROR);
325 Cache.log.warn(format("Attempts limit exceeded. Dropping job %s.", job));
327 } catch (OutOfMemoryError e)
329 job.setStatus(WSJobStatus.BROKEN);
330 Cache.log.error(format("Out of memory when retrieving job %s", job), e);
333 return job.getStatus().isDone() || job.getStatus().isFailed();
342 } catch (IOException e)
344 Cache.log.error(format("Failed to cancel job %s.", job), e);
351 Cache.log.debug(format("Polling loop exited, job %s is %s", job, job.getStatus()));
352 if (!job.getStatus().isCompleted())
356 List<AlignmentAnnotation> outputAnnotations = null;
359 outputAnnotations = operation.annotationSupplier
360 .getResult(job, sequences, viewport);
361 } catch (IOException e)
363 Cache.log.error(format("Couldn't retrieve features for job %s.", job), e);
365 if (outputAnnotations != null)
366 Cache.log.debug(format("Obtained %d annotation rows.", outputAnnotations.size()));
368 Cache.log.debug("Obtained no annotations.");
369 Map<String, FeatureColourI> featureColours = new HashMap<>();
370 Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
371 FeaturesFile featuresFile;
374 featuresFile = operation.featuresSupplier.getResult(job, sequences, viewport);
375 if (featuresFile != null)
377 Alignment aln = new Alignment(sequences.toArray(new SequenceI[0]));
378 featuresFile.parse(aln, featureColours, true);
380 } catch (IOException e)
382 Cache.log.error(format("Couldn't retrieve features for job %s", job), e);
384 Cache.log.debug(format("There are %d feature colours and %d filters.",
385 featureColours.size(), featureFilters.size()));
386 if (outputAnnotations != null)
388 for (AlignmentAnnotation aa : outputAnnotations)
390 if (aa.getCalcId() == null || aa.getCalcId().equals(""))
392 aa.setCalcId(service.getName());
394 aa.autoCalculated = operation.isAlignmentAnalysis() && operation.isInteractive();
396 updateResultAnnotation(outputAnnotations);
397 if (transferSequenceFeatures)
399 Cache.log.debug(format("Updating feature display settings and transferring"
400 + "features fron job %s at %s", job, service.getHostName()));
401 viewport.applyFeaturesStyle(new FeatureSettingsAdapter()
404 public FeatureColourI getFeatureColour(String type)
406 return featureColours.get(type);
410 public FeatureMatcherSetI getFeatureFilters(String type)
412 return featureFilters.get(type);
416 public boolean isFeatureDisplayed(String type)
418 return featureColours.containsKey(type);
421 if (frame.alignPanel == alignPanel)
423 viewport.setShowSequenceFeatures(true);
424 frame.setMenusForViewport();
428 Cache.log.debug("Annotation service task finished.");
431 private void updateResultAnnotation(List<AlignmentAnnotation> annotations)
433 var currentAnnotations = Objects.requireNonNullElse(
434 viewport.getAlignment().getAlignmentAnnotation(),
435 new AlignmentAnnotation[0]);
436 List<AlignmentAnnotation> newAnnots = new ArrayList<>();
438 for (AlignmentAnnotation alna : currentAnnotations)
440 graphGroup = Integer.max(graphGroup, alna.graphGroup);
442 for (AlignmentAnnotation ala : annotations)
444 if (ala.graphGroup > 0)
446 ala.graphGroup += graphGroup;
449 SequenceI aseq = null;
450 if (ala.sequenceRef != null)
452 SequenceI seq = seqNames.get(ala.sequenceRef.getName());
454 while (seq.getDatasetSequence() != null)
456 seq = seq.getDatasetSequence();
459 Annotation[] resAnnot = ala.annotations;
460 Annotation[] gappedAnnot = new Annotation[Math
461 .max(viewport.getAlignment().getWidth(), gapMap.length)];
462 for (int p = 0, ap = start; ap < gappedAnnot.length; ap++)
464 if (gapMap != null && gapMap.length > ap && !gapMap[ap])
466 gappedAnnot[ap] = new Annotation("", "", ' ', Float.NaN);
468 else if (p < resAnnot.length)
470 gappedAnnot[ap] = resAnnot[p++];
473 ala.sequenceRef = aseq;
474 ala.annotations = gappedAnnot;
475 AlignmentAnnotation newAnnot = viewport.getAlignment()
476 .updateFromOrCopyAnnotation(ala);
479 aseq.addAlignmentAnnotation(newAnnot);
480 newAnnot.adjustForAlignment();
481 AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(newAnnot,
482 newAnnot.label, newAnnot.getCalcId());
484 newAnnots.add(newAnnot);
487 for (SequenceI sq : sequences)
489 if (!sq.getFeatures().hasFeatures() &&
490 (sq.getDBRefs() == null || sq.getDBRefs().size() == 0))
494 transferSequenceFeatures = true;
495 SequenceI seq = seqNames.get(sq.getName());
497 ContiguousI seqRange = seq.findPositions(start, end);
499 while ((dseq = seq).getDatasetSequence() != null)
501 seq = seq.getDatasetSequence();
503 List<ContiguousI> sourceRange = new ArrayList<>();
504 if (gapMap != null && gapMap.length > end)
506 int lastcol = start, col = start;
509 if (col == end || !gapMap[col])
511 if (lastcol <= col - 1)
513 seqRange = seq.findPositions(lastcol, col);
514 sourceRange.add(seqRange);
518 } while (++col < end);
522 sourceRange.add(seq.findPositions(start, end));
525 int sourceStartEnd[] = new int[sourceRange.size() * 2];
526 for (ContiguousI range : sourceRange)
528 sourceStartEnd[i++] = range.getBegin();
529 sourceStartEnd[i++] = range.getEnd();
531 Mapping mp = new Mapping(new MapList(sourceStartEnd,
532 new int[] { seq.getStart(), seq.getEnd() }, 1, 1));
533 dseq.transferAnnotation(sq, mp);
535 updateOurAnnots(newAnnots);
538 protected void updateOurAnnots(List<AlignmentAnnotation> annots)
540 List<AlignmentAnnotation> our = ourAnnots;
541 ourAnnots = Collections.synchronizedList(annots);
542 AlignmentI alignment = viewport.getAlignment();
547 for (AlignmentAnnotation an : our)
549 if (!ourAnnots.contains(an))
551 // remove the old annotation
552 alignment.deleteAnnotation(an);
558 // validate rows and update Alignment state
559 synchronized (ourAnnots)
561 for (AlignmentAnnotation an : ourAnnots)
563 viewport.getAlignment().validateAnnotation(an);
566 // TODO: may need a menu refresh after this
567 // af.setMenusForViewport();
568 alignPanel.adjustAnnotationHeight();