1 package jalview.ws2.actions.annotation;
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
10 import jalview.analysis.AlignmentAnnotationUtils;
11 import jalview.api.AlignCalcManagerI2;
12 import jalview.api.AlignCalcWorkerI;
13 import jalview.api.AlignViewportI;
14 import jalview.api.FeatureColourI;
15 import jalview.api.PollableAlignCalcWorkerI;
16 import jalview.bin.Cache;
17 import jalview.bin.Console;
18 import jalview.datamodel.AlignmentAnnotation;
19 import jalview.datamodel.AlignmentI;
20 import jalview.datamodel.AnnotatedCollectionI;
21 import jalview.datamodel.Annotation;
22 import jalview.datamodel.ContiguousI;
23 import jalview.datamodel.Mapping;
24 import jalview.datamodel.SequenceI;
25 import jalview.datamodel.features.FeatureMatcherSetI;
26 import jalview.schemes.FeatureSettingsAdapter;
27 import jalview.util.ArrayUtils;
28 import jalview.util.MapList;
29 import jalview.util.MathUtils;
30 import jalview.util.Pair;
31 import jalview.workers.AlignCalcWorker;
32 import jalview.ws.params.ArgumentI;
33 import jalview.ws2.actions.BaseJob;
34 import jalview.ws2.actions.BaseTask;
35 import jalview.ws2.actions.ServiceInputInvalidException;
36 import jalview.ws2.actions.api.JobI;
37 import jalview.ws2.actions.api.TaskEventListener;
38 import jalview.ws2.actions.api.TaskI;
39 import jalview.ws2.api.Credentials;
40 import jalview.ws2.api.JobStatus;
41 import jalview.ws2.api.WebServiceJobHandle;
42 import jalview.ws2.client.api.AnnotationWebServiceClientI;
43 import jalview.ws2.helpers.DelegateJobEventListener;
44 import jalview.ws2.helpers.TaskEventSupport;
46 public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
48 private AnnotationWebServiceClientI client;
50 private final AnnotationAction action;
52 private final AlignViewportI viewport;
54 private JobStatus taskStatus = null;
56 private AlignCalcWorkerAdapter worker = null;
58 private DelegateJobEventListener<AnnotationResult> jobEventHandler;
60 public AnnotationTask(AnnotationWebServiceClientI client,
61 AnnotationAction action, List<ArgumentI> args, Credentials credentials,
62 AlignViewportI viewport)
64 super(client, args, credentials);
67 this.viewport = viewport;
71 * Create and return a list of annotation jobs from the current state of the
72 * viewport. Returned job are not started by this method and should be stored
73 * in a field and started separately.
75 * @return list of annotation jobs
76 * @throws ServiceInputInvalidException
77 * input data is not valid
80 public List<AnnotationJob> prepareJobs() throws ServiceInputInvalidException
82 AlignmentI alignment = viewport.getAlignment();
83 if (alignment == null || alignment.getWidth() <= 0 ||
84 alignment.getSequences() == null)
85 throw new ServiceInputInvalidException("Alignment does not contain sequences");
86 if (alignment.isNucleotide() && !action.doAllowNucleotide())
87 throw new ServiceInputInvalidException(
88 action.getFullName() + " does not allow nucleotide sequences");
89 if (!alignment.isNucleotide() && !action.doAllowProtein())
90 throw new ServiceInputInvalidException(
91 action.getFullName() + " does not allow protein sequences");
92 boolean bySequence = !action.isAlignmentAnalysis();
93 AnnotatedCollectionI inputSeqs = bySequence ? viewport.getSelectionGroup() : null;
94 if (inputSeqs == null || inputSeqs.getWidth() <= 0 ||
95 inputSeqs.getSequences() == null || inputSeqs.getSequences().size() < 1)
96 inputSeqs = alignment;
97 boolean submitGaps = action.isAlignmentAnalysis();
98 boolean requireAligned = action.getRequireAlignedSequences();
99 boolean filterSymbols = action.getFilterSymbols();
100 int minSize = action.getMinSequences();
101 AnnotationJob job = AnnotationJob.create(inputSeqs, bySequence,
102 submitGaps, requireAligned, filterSymbols, minSize);
103 if (!job.isInputValid())
105 job.setStatus(JobStatus.INVALID);
106 throw new ServiceInputInvalidException("Annotation job has invalid input");
108 job.setStatus(JobStatus.READY);
113 protected AnnotationResult collectResult(List<AnnotationJob> jobs) throws IOException
115 final Map<String, FeatureColourI> featureColours = new HashMap<>();
116 final Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
117 var job = jobs.get(0);
118 List<AlignmentAnnotation> returnedAnnot = client.attachAnnotations(
119 job.getServerJob(), job.getInputSequences(), featureColours,
122 * copy over each annotation row returned and also defined on each
123 * sequence, excluding regions not annotated due to gapMap/column
126 udpateCalcId(returnedAnnot);
127 int graphGroup = viewport.getAlignment().getLastGraphGroup();
128 shiftGraphGroup(returnedAnnot, graphGroup);
129 List<AlignmentAnnotation> annotations = new ArrayList<>();
130 for (AlignmentAnnotation ala : returnedAnnot)
132 SequenceI aseq = null;
133 if (ala.sequenceRef != null) {
134 SequenceI seq = job.seqNames.get(ala.sequenceRef.getName());
135 aseq = seq.getRootDatasetSequence();
137 ala.sequenceRef = aseq;
138 Annotation[] gappedAnnots = createGappedAnnotations(ala.annotations, job.start, job.gapMap);
139 ala.annotations = gappedAnnots;
141 AlignmentAnnotation newAnnot = viewport.getAlignment()
142 .updateFromOrCopyAnnotation(ala);
145 aseq.addAlignmentAnnotation(newAnnot);
146 newAnnot.adjustForAlignment();
147 AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(
148 newAnnot, newAnnot.label, newAnnot.getCalcId());
150 annotations.add(newAnnot);
153 boolean hasFeatures = false;
154 for (SequenceI sq : job.getInputSequences())
156 if (!sq.getFeatures().hasFeatures() && (sq.getDBRefs() == null || sq.getDBRefs().isEmpty()))
159 SequenceI seq = job.seqNames.get(sq.getName());
160 SequenceI datasetSeq = seq.getRootDatasetSequence();
161 List<ContiguousI> sourceRange = findContiguousRanges(datasetSeq, job.gapMap, job.start, job.end);
162 int[] sourceStartEnd = ContiguousI.toStartEndArray(sourceRange);
163 Mapping mp = new Mapping(new MapList(
164 sourceStartEnd, new int[]
165 { datasetSeq.getStart(), datasetSeq.getEnd() }, 1, 1));
166 datasetSeq.transferAnnotation(sq, mp);
169 return new AnnotationResult(annotations, hasFeatures, featureColours, featureFilters);
173 * Updates calcId on provided annotations if not already set.
175 public void udpateCalcId(Iterable<AlignmentAnnotation> annotations)
177 for (var annotation : annotations)
179 if (annotation.getCalcId() == null || annotation.getCalcId().isEmpty())
181 annotation.setCalcId(action.getFullName());
183 annotation.autoCalculated = action.isAlignmentAnalysis() &&
184 action.getWebService().isInteractive();
188 private static void shiftGraphGroup(Iterable<AlignmentAnnotation> annotations, int shift)
190 for (AlignmentAnnotation ala : annotations)
192 if (ala.graphGroup > 0)
194 ala.graphGroup += shift;
199 private Annotation[] createGappedAnnotations(Annotation[] annotations, int start, boolean[] gapMap)
201 var size = Math.max(viewport.getAlignment().getWidth(), gapMap.length);
202 Annotation[] gappedAnnotations = new Annotation[size];
203 for (int p = 0, ap = start; ap < size; ap++)
205 if (gapMap != null && gapMap.length > ap && !gapMap[ap])
207 gappedAnnotations[ap] = new Annotation("", "", ' ', Float.NaN);
209 else if (p < annotations.length)
211 gappedAnnotations[ap] = annotations[p++];
214 return gappedAnnotations;
217 private List<ContiguousI> findContiguousRanges(SequenceI seq, boolean[] gapMap, int start, int end)
219 if (gapMap == null || gapMap.length < end)
220 return List.of(seq.findPositions(start, end));
221 List<ContiguousI> ranges = new ArrayList<>();
222 int lastcol = start, col = start;
225 if (col == end || !gapMap[col])
228 ranges.add(seq.findPositions(lastcol, col));
231 } while (++col <= end);
236 public String toString()
238 var status = taskStatus != null ? taskStatus.name() : "UNSET";
239 return String.format("%s(%x, %s)", getClass().getSimpleName(), uid, status);