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));
246 // for annotation need to also record map to sequence start/end
248 // then transfer back to original sequence on return.
250 ln = Integer.max(seq.getLength(), ln);
253 if (operation.getNeedsAlignedSequences() && submitGaps)
256 for (int i = 0; i < gapMap.length; i++)
263 // try real hard to return something submittable
264 // TODO: some of AAcon measures need a minimum of two or three amino
265 // acids at each position, and AAcon doesn't gracefully degrade.
266 for (int p = 0; p < seqs.size(); p++)
268 SequenceI sq = seqs.get(p);
269 // strip gapped columns
270 char[] padded = new char[realw];
271 char[] orig = sq.getSequence();
272 for (int i = 0, pp = 0; i < realw; pp++)
276 if (orig.length > pp)
278 padded[i++] = orig[pp];
286 seqs.set(p, new Sequence(sq.getName(), new String(padded)));
292 private boolean checkInputSequencesValid(List<SequenceI> sequences)
295 boolean allowProtein = operation.isProteinOperation(),
296 allowNucleotides = operation.isNucleotideOperation();
297 for (SequenceI sq : sequences)
299 if (sq.getStart() <= sq.getEnd() &&
300 (sq.isProtein() ? allowProtein : allowNucleotides))
305 return nvalid >= operation.getMinSequences();
309 public boolean poll() throws IOException
311 if (!job.getStatus().isDone() && !job.getStatus().isFailed())
313 Cache.log.debug(format("Polling job %s", job));
316 service.updateProgress(job);
317 exceptionCount = MAX_RETRY;
318 } catch (IOException e)
320 Cache.log.error(format("Polling job %s failed.", job), e);
321 if (--exceptionCount <= 0)
323 job.setStatus(WSJobStatus.SERVER_ERROR);
324 Cache.log.warn(format("Attempts limit exceeded. Dropping job %s.", job));
326 } catch (OutOfMemoryError e)
328 job.setStatus(WSJobStatus.BROKEN);
329 Cache.log.error(format("Out of memory when retrieving job %s", job), e);
332 return job.getStatus().isDone() || job.getStatus().isFailed();
341 } catch (IOException e)
343 Cache.log.error(format("Failed to cancel job %s.", job), e);
350 Cache.log.debug(format("Polling loop exited, job %s is %s", job, job.getStatus()));
351 if (!job.getStatus().isCompleted())
355 List<AlignmentAnnotation> outputAnnotations = null;
358 outputAnnotations = operation.annotationSupplier
359 .getResult(job, sequences, viewport);
360 } catch (IOException e)
362 Cache.log.error(format("Couldn't retrieve features for job %s.", job), e);
364 if (outputAnnotations != null)
365 Cache.log.debug(format("Obtained %d annotation rows.", outputAnnotations.size()));
367 Cache.log.debug("Obtained no annotations.");
368 Map<String, FeatureColourI> featureColours = new HashMap<>();
369 Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
370 FeaturesFile featuresFile;
373 featuresFile = operation.featuresSupplier.getResult(job, sequences, viewport);
374 if (featuresFile != null)
376 Alignment aln = new Alignment(sequences.toArray(new SequenceI[0]));
377 featuresFile.parse(aln, featureColours, true);
379 } catch (IOException e)
381 Cache.log.error(format("Couldn't retrieve features for job %s", job), e);
383 Cache.log.debug(format("There are %d feature colours and %d filters.",
384 featureColours.size(), featureFilters.size()));
385 if (outputAnnotations != null)
387 for (AlignmentAnnotation aa : outputAnnotations)
389 if (aa.getCalcId() == null || aa.getCalcId().equals(""))
391 aa.setCalcId(service.getName());
393 aa.autoCalculated = operation.isAlignmentAnalysis() && operation.isInteractive();
395 updateResultAnnotation(outputAnnotations);
396 if (transferSequenceFeatures)
398 Cache.log.debug(format("Updating feature display settings and transferring"
399 + "features fron job %s at %s", job, service.getHostName()));
400 viewport.applyFeaturesStyle(new FeatureSettingsAdapter()
403 public FeatureColourI getFeatureColour(String type)
405 return featureColours.get(type);
409 public FeatureMatcherSetI getFeatureFilters(String type)
411 return featureFilters.get(type);
415 public boolean isFeatureDisplayed(String type)
417 return featureColours.containsKey(type);
420 if (frame.alignPanel == alignPanel)
422 viewport.setShowSequenceFeatures(true);
423 frame.setMenusForViewport();
427 Cache.log.debug("Annotation service task finished.");
430 private void updateResultAnnotation(List<AlignmentAnnotation> annotations)
432 var currentAnnotations = Objects.requireNonNullElse(
433 viewport.getAlignment().getAlignmentAnnotation(),
434 new AlignmentAnnotation[0]);
435 List<AlignmentAnnotation> newAnnots = new ArrayList<>();
437 for (AlignmentAnnotation alna : currentAnnotations)
439 graphGroup = Integer.max(graphGroup, alna.graphGroup);
441 for (AlignmentAnnotation ala : annotations)
443 if (ala.graphGroup > 0)
445 ala.graphGroup += graphGroup;
448 SequenceI aseq = null;
449 if (ala.sequenceRef != null)
451 SequenceI seq = seqNames.get(ala.sequenceRef.getName());
453 while (seq.getDatasetSequence() != null)
455 seq = seq.getDatasetSequence();
458 Annotation[] resAnnot = ala.annotations;
459 Annotation[] gappedAnnot = new Annotation[Math
460 .max(viewport.getAlignment().getWidth(), gapMap.length)];
461 for (int p = 0, ap = start; ap < gappedAnnot.length; ap++)
463 if (gapMap != null && gapMap.length > ap && !gapMap[ap])
465 gappedAnnot[ap] = new Annotation("", "", ' ', Float.NaN);
467 else if (p < resAnnot.length)
469 gappedAnnot[ap] = resAnnot[p++];
472 ala.sequenceRef = aseq;
473 ala.annotations = gappedAnnot;
474 AlignmentAnnotation newAnnot = viewport.getAlignment()
475 .updateFromOrCopyAnnotation(ala);
478 aseq.addAlignmentAnnotation(newAnnot);
479 newAnnot.adjustForAlignment();
480 AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(newAnnot,
481 newAnnot.label, newAnnot.getCalcId());
483 newAnnots.add(newAnnot);
486 for (SequenceI sq : sequences)
488 if (!sq.getFeatures().hasFeatures() &&
489 (sq.getDBRefs() == null || sq.getDBRefs().size() == 0))
493 transferSequenceFeatures = true;
494 SequenceI seq = seqNames.get(sq.getName());
496 ContiguousI seqRange = seq.findPositions(start, end);
498 while ((dseq = seq).getDatasetSequence() != null)
500 seq = seq.getDatasetSequence();
502 List<ContiguousI> sourceRange = new ArrayList<>();
503 if (gapMap != null && gapMap.length > end)
505 int lastcol = start, col = start;
508 if (col == end || !gapMap[col])
510 if (lastcol <= col - 1)
512 seqRange = seq.findPositions(lastcol, col);
513 sourceRange.add(seqRange);
517 } while (++col < end);
521 sourceRange.add(seq.findPositions(start, end));
524 int sourceStartEnd[] = new int[sourceRange.size() * 2];
525 for (ContiguousI range : sourceRange)
527 sourceStartEnd[i++] = range.getBegin();
528 sourceStartEnd[i++] = range.getEnd();
530 Mapping mp = new Mapping(new MapList(sourceStartEnd,
531 new int[] { seq.getStart(), seq.getEnd() }, 1, 1));
532 dseq.transferAnnotation(sq, mp);
534 updateOurAnnots(newAnnots);
537 protected void updateOurAnnots(List<AlignmentAnnotation> annots)
539 List<AlignmentAnnotation> our = ourAnnots;
540 ourAnnots = Collections.synchronizedList(annots);
541 AlignmentI alignment = viewport.getAlignment();
546 for (AlignmentAnnotation an : our)
548 if (!ourAnnots.contains(an))
550 // remove the old annotation
551 alignment.deleteAnnotation(an);
557 // validate rows and update Alignment state
558 synchronized (ourAnnots)
560 for (AlignmentAnnotation an : ourAnnots)
562 viewport.getAlignment().validateAnnotation(an);
565 // TODO: may need a menu refresh after this
566 // af.setMenusForViewport();
567 alignPanel.adjustAnnotationHeight();