JAL-4241 Fix annotation and feature alignment with selection
[jalview.git] / src / jalview / ws2 / actions / annotation / AnnotationTask.java
index 866f862..6cb5aa6 100644 (file)
@@ -6,7 +6,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import jalview.analysis.AlignmentAnnotationUtils;
 import jalview.api.AlignViewportI;
 import jalview.api.FeatureColourI;
 import jalview.datamodel.AlignmentAnnotation;
@@ -25,7 +24,8 @@ import jalview.ws2.api.Credentials;
 import jalview.ws2.api.JobStatus;
 import jalview.ws2.client.api.AnnotationWebServiceClientI;
 
-public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
+public class AnnotationTask
+        extends BaseTask<AnnotationJob, AnnotationResult>
 {
   private AnnotationWebServiceClientI client;
 
@@ -36,8 +36,8 @@ public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
   private final AnnotatedCollectionI selectionGroup;
 
   public AnnotationTask(AnnotationWebServiceClientI client,
-      AnnotationAction action, List<ArgumentI> args, Credentials credentials,
-      AlignViewportI viewport)
+          AnnotationAction action, List<ArgumentI> args,
+          Credentials credentials, AlignViewportI viewport)
   {
     super(client, args, credentials);
     this.client = client;
@@ -50,52 +50,57 @@ public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
    * Create and return a list of annotation jobs from the current state of the
    * viewport. Returned job are not started by this method and should be stored
    * in a field and started separately.
-   * 
+   *
    * @return list of annotation jobs
    * @throws ServiceInputInvalidException
    *           input data is not valid
    */
   @Override
-  public List<AnnotationJob> prepareJobs() throws ServiceInputInvalidException
+  public List<AnnotationJob> prepareJobs()
+          throws ServiceInputInvalidException
   {
-    if (alignment == null || alignment.getWidth() <= 0 ||
-        alignment.getSequences() == null)
-      throw new ServiceInputInvalidException("Alignment does not contain sequences");
-    if (alignment.isNucleotide() && !action.doAllowNucleotide())
+    if (alignment == null || alignment.getWidth() <= 0
+            || alignment.getSequences() == null)
       throw new ServiceInputInvalidException(
-          action.getFullName() + " does not allow nucleotide sequences");
+              "Alignment does not contain sequences");
+    if (alignment.isNucleotide() && !action.doAllowNucleotide())
+      throw new ServiceInputInvalidException(action.getFullName()
+              + " does not allow nucleotide sequences");
     if (!alignment.isNucleotide() && !action.doAllowProtein())
       throw new ServiceInputInvalidException(
-          action.getFullName() + " does not allow protein sequences");
+              action.getFullName() + " does not allow protein sequences");
     boolean bySequence = !action.isAlignmentAnalysis();
     AnnotatedCollectionI inputSeqs = bySequence ? selectionGroup : null;
-    if (inputSeqs == null || inputSeqs.getWidth() <= 0 ||
-        inputSeqs.getSequences() == null || inputSeqs.getSequences().size() < 1)
+    if (inputSeqs == null || inputSeqs.getWidth() <= 0
+            || inputSeqs.getSequences() == null
+            || inputSeqs.getSequences().size() < 1)
       inputSeqs = alignment;
     boolean submitGaps = action.isAlignmentAnalysis();
     boolean requireAligned = action.getRequireAlignedSequences();
     boolean filterSymbols = action.getFilterSymbols();
     int minSize = action.getMinSequences();
     AnnotationJob job = AnnotationJob.create(inputSeqs, bySequence,
-        submitGaps, requireAligned, filterSymbols, minSize);
+            submitGaps, requireAligned, filterSymbols, minSize);
     if (!job.isInputValid())
     {
       job.setStatus(JobStatus.INVALID);
-      throw new ServiceInputInvalidException("Annotation job has invalid input");
+      throw new ServiceInputInvalidException(
+              "Annotation job has invalid input");
     }
     job.setStatus(JobStatus.READY);
     return List.of(job);
   }
 
   @Override
-  protected AnnotationResult collectResult(List<AnnotationJob> jobs) throws IOException
+  protected AnnotationResult collectResult(List<AnnotationJob> jobs)
+          throws IOException
   {
     final Map<String, FeatureColourI> featureColours = new HashMap<>();
     final Map<String, FeatureMatcherSetI> featureFilters = new HashMap<>();
     var job = jobs.get(0);
     List<AlignmentAnnotation> returnedAnnot = client.attachAnnotations(
-        job.getServerJob(), job.getInputSequences(), featureColours,
-        featureFilters);
+            job.getServerJob(), job.getInputSequences(), featureColours,
+            featureFilters);
     /* TODO
      * copy over each annotation row returned and also defined on each
      * sequence, excluding regions not annotated due to gapMap/column
@@ -104,34 +109,40 @@ public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
     udpateCalcId(returnedAnnot);
     for (AlignmentAnnotation ala : returnedAnnot)
     {
-      SequenceI aseq = null;
-      if (ala.sequenceRef != null)
+      SequenceI seq = (ala.sequenceRef == null) ? null
+              : job.seqNames.get(ala.sequenceRef.getName());
+      if (job.gapMap != null && job.gapMap.length > 0)
+        ala.annotations = createGappedAnnotations(ala.annotations,
+                job.gapMap);
+      if (seq != null)
       {
-        SequenceI seq = job.seqNames.get(ala.sequenceRef.getName());
-        aseq = seq.getRootDatasetSequence();
+        int startRes = seq.findPosition(job.regionStart);
+        ala.createSequenceMapping(seq, startRes, false);
       }
-      ala.sequenceRef = aseq;
-      Annotation[] gappedAnnots = createGappedAnnotations(ala.annotations, job.start, job.gapMap);
-      ala.annotations = gappedAnnots;
     }
 
     boolean hasFeatures = false;
     for (SequenceI sq : job.getInputSequences())
     {
-      if (!sq.getFeatures().hasFeatures() && (sq.getDBRefs() == null || sq.getDBRefs().isEmpty()))
+      if (!sq.getFeatures().hasFeatures()
+              && (sq.getDBRefs() == null || sq.getDBRefs().isEmpty()))
         continue;
       hasFeatures = true;
       SequenceI seq = job.seqNames.get(sq.getName());
       SequenceI datasetSeq = seq.getRootDatasetSequence();
-      List<ContiguousI> sourceRange = findContiguousRanges(datasetSeq, job.gapMap, job.start, job.end);
+      List<ContiguousI> sourceRange = findContiguousRanges(seq,
+              job.gapMap, job.regionStart, job.regionEnd);
       int[] sourceStartEnd = ContiguousI.toStartEndArray(sourceRange);
-      Mapping mp = new Mapping(new MapList(
-          sourceStartEnd, new int[]
-          { datasetSeq.getStart(), datasetSeq.getEnd() }, 1, 1));
+      Mapping mp = new Mapping(
+          new MapList(
+              sourceStartEnd,
+              new int[] { datasetSeq.getStart(), datasetSeq.getEnd() },
+              1, 1));
       datasetSeq.transferAnnotation(sq, mp);
     }
 
-    return new AnnotationResult(returnedAnnot, hasFeatures, featureColours, featureFilters);
+    return new AnnotationResult(returnedAnnot, hasFeatures, featureColours,
+            featureFilters);
   }
 
   /**
@@ -141,22 +152,24 @@ public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
   {
     for (var annotation : annotations)
     {
-      if (annotation.getCalcId() == null || annotation.getCalcId().isEmpty())
+      if (annotation.getCalcId() == null
+              || annotation.getCalcId().isEmpty())
       {
         annotation.setCalcId(action.getFullName());
       }
-      annotation.autoCalculated = action.isAlignmentAnalysis() &&
-          action.getWebService().isInteractive();
+      annotation.autoCalculated = action.isAlignmentAnalysis()
+              && action.getWebService().isInteractive();
     }
   }
 
-  private Annotation[] createGappedAnnotations(Annotation[] annotations, int start, boolean[] gapMap)
+  private Annotation[] createGappedAnnotations(Annotation[] annotations,
+          boolean[] gapMap)
   {
-    var size = Math.max(alignment.getWidth(), gapMap.length);
+    var size = Math.max(annotations.length, gapMap.length);
     Annotation[] gappedAnnotations = new Annotation[size];
-    for (int p = 0, ap = start; ap < size; ap++)
+    for (int p = 0, ap = 0; ap < size; ap++)
     {
-      if (gapMap != null && gapMap.length > ap && !gapMap[ap])
+      if (ap < gapMap.length && !gapMap[ap])
       {
         gappedAnnotations[ap] = new Annotation("", "", ' ', Float.NaN);
       }
@@ -168,10 +181,12 @@ public class AnnotationTask extends BaseTask<AnnotationJob, AnnotationResult>
     return gappedAnnotations;
   }
 
-  private List<ContiguousI> findContiguousRanges(SequenceI seq, boolean[] gapMap, int start, int end)
+  // TODO: review ant test!!!
+  private List<ContiguousI> findContiguousRanges(SequenceI seq,
+          boolean[] gapMap, int start, int end)
   {
     if (gapMap == null || gapMap.length < end)
-      return List.of(seq.findPositions(start, end));
+      return List.of(seq.findPositions(start + 1, end + 1));
     List<ContiguousI> ranges = new ArrayList<>();
     int lastcol = start, col = start;
     do