e2a05a0cecb93271e7ac461373750a8956521071
[jalview.git] / src / jalview / ws2 / actions / annotation / AnnotationTask.java
1 package jalview.ws2.actions.annotation;
2
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.List;
8 import java.util.Map;
9
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;
45
46 public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
47 {
48   private AnnotationWebServiceClientI client;
49
50   private final AnnotationAction action;
51
52   private final AlignViewportI viewport;
53
54   private JobStatus taskStatus = null;
55
56   private AlignCalcWorkerAdapter worker = null;
57
58   private DelegateJobEventListener<AnnotationResult> jobEventHandler;
59
60   public AnnotationTask(AnnotationWebServiceClientI client,
61       AnnotationAction action, List<ArgumentI> args, Credentials credentials,
62       AlignViewportI viewport)
63   {
64     super(client, args, credentials);
65     this.client = client;
66     this.action = action;
67     this.viewport = viewport;
68   }
69
70   /**
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.
74    * 
75    * @return list of annotation jobs
76    * @throws ServiceInputInvalidException
77    *           input data is not valid
78    */
79   @Override
80   public List<AnnotationJob> prepareJobs() throws ServiceInputInvalidException
81   {
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())
104     {
105       job.setStatus(JobStatus.INVALID);
106       throw new ServiceInputInvalidException("Annotation job has invalid input");
107     }
108     job.setStatus(JobStatus.READY);
109     return List.of(job);
110   }
111
112   @Override
113   protected AnnotationResult collectResult(List<AnnotationJob> jobs) throws IOException
114   {
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,
120         featureFilters);
121     /* TODO
122      * copy over each annotation row returned and also defined on each
123      * sequence, excluding regions not annotated due to gapMap/column
124      * visibility */
125
126     udpateCalcId(returnedAnnot);
127     int graphGroup = viewport.getAlignment().getLastGraphGroup();
128     shiftGraphGroup(returnedAnnot, graphGroup);
129     List<AlignmentAnnotation> annotations = new ArrayList<>();
130     for (AlignmentAnnotation ala : returnedAnnot)
131     {
132       SequenceI aseq = null;
133       if (ala.sequenceRef != null) {
134         SequenceI seq = job.seqNames.get(ala.sequenceRef.getName());
135         aseq = seq.getRootDatasetSequence();
136       }
137       ala.sequenceRef = aseq;
138       Annotation[] gappedAnnots = createGappedAnnotations(ala.annotations, job.start, job.gapMap);
139       ala.annotations = gappedAnnots;
140
141       AlignmentAnnotation newAnnot = viewport.getAlignment()
142           .updateFromOrCopyAnnotation(ala);
143       if (aseq != null)
144       {
145         aseq.addAlignmentAnnotation(newAnnot);
146         newAnnot.adjustForAlignment();
147         AlignmentAnnotationUtils.replaceAnnotationOnAlignmentWith(
148             newAnnot, newAnnot.label, newAnnot.getCalcId());
149       }
150       annotations.add(newAnnot);
151     }
152
153     boolean hasFeatures = false;
154     for (SequenceI sq : job.getInputSequences())
155     {
156       if (!sq.getFeatures().hasFeatures() && (sq.getDBRefs() == null || sq.getDBRefs().isEmpty()))
157         continue;
158       hasFeatures = true;
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);
167     }
168
169     return new AnnotationResult(annotations, hasFeatures, featureColours, featureFilters);
170   }
171
172   /**
173    * Updates calcId on provided annotations if not already set.
174    */
175   public void udpateCalcId(Iterable<AlignmentAnnotation> annotations)
176   {
177     for (var annotation : annotations)
178     {
179       if (annotation.getCalcId() == null || annotation.getCalcId().isEmpty())
180       {
181         annotation.setCalcId(action.getFullName());
182       }
183       annotation.autoCalculated = action.isAlignmentAnalysis() &&
184           action.getWebService().isInteractive();
185     }
186   }
187
188   private static void shiftGraphGroup(Iterable<AlignmentAnnotation> annotations, int shift)
189   {
190     for (AlignmentAnnotation ala : annotations)
191     {
192       if (ala.graphGroup > 0)
193       {
194         ala.graphGroup += shift;
195       }
196     }
197   }
198
199   private Annotation[] createGappedAnnotations(Annotation[] annotations, int start, boolean[] gapMap)
200   {
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++)
204     {
205       if (gapMap != null && gapMap.length > ap && !gapMap[ap])
206       {
207         gappedAnnotations[ap] = new Annotation("", "", ' ', Float.NaN);
208       }
209       else if (p < annotations.length)
210       {
211         gappedAnnotations[ap] = annotations[p++];
212       }
213     }
214     return gappedAnnotations;
215   }
216
217   private List<ContiguousI> findContiguousRanges(SequenceI seq, boolean[] gapMap, int start, int end)
218   {
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;
223     do
224     {
225       if (col == end || !gapMap[col])
226       {
227         if (lastcol < col)
228           ranges.add(seq.findPositions(lastcol, col));
229         lastcol = col + 1;
230       }
231     } while (++col <= end);
232     return ranges;
233   }
234
235   @Override
236   public String toString()
237   {
238     var status = taskStatus != null ? taskStatus.name() : "UNSET";
239     return String.format("%s(%x, %s)", getClass().getSimpleName(), uid, status);
240   }
241 }