JAL-3700 fix for propagation of sort commands
[jalview.git] / src / jalview / datamodel / AlignedCodonFrame.java
index 10632c5..6103df5 100644 (file)
@@ -23,6 +23,7 @@ package jalview.datamodel;
 import jalview.util.MapList;
 import jalview.util.MappingUtils;
 
+import java.util.AbstractList;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -36,7 +37,7 @@ public class AlignedCodonFrame
   /*
    * Data bean to hold mappings from one sequence to another
    */
-  private class SequenceToSequenceMapping
+  public class SequenceToSequenceMapping
   {
     private SequenceI fromSeq;
 
@@ -47,6 +48,114 @@ public class AlignedCodonFrame
       this.fromSeq = from;
       this.mapping = map;
     }
+
+    /**
+     * Readable representation for debugging only, not guaranteed not to change
+     */
+    @Override
+    public String toString()
+    {
+      return String.format("From %s %s", fromSeq.getName(),
+              mapping.toString());
+    }
+
+    /**
+     * Returns a hashCode derived from the hashcodes of the mappings and fromSeq
+     * 
+     * @see SequenceToSequenceMapping#hashCode()
+     */
+    @Override
+    public int hashCode()
+    {
+      return (fromSeq == null ? 0 : fromSeq.hashCode() * 31)
+              + mapping.hashCode();
+    }
+
+    /**
+     * Answers true if the objects hold the same mapping between the same two
+     * sequences
+     * 
+     * @see Mapping#equals
+     */
+    @Override
+    public boolean equals(Object obj)
+    {
+      if (!(obj instanceof SequenceToSequenceMapping))
+      {
+        return false;
+      }
+      SequenceToSequenceMapping that = (SequenceToSequenceMapping) obj;
+      if (this.mapping == null)
+      {
+        return that.mapping == null;
+      }
+      // TODO: can simplify by asserting fromSeq is a dataset sequence
+      return (this.fromSeq == that.fromSeq
+              || (this.fromSeq != null && that.fromSeq != null
+                      && this.fromSeq.getDatasetSequence() != null
+                      && this.fromSeq.getDatasetSequence() == that.fromSeq
+                              .getDatasetSequence()))
+              && this.mapping.equals(that.mapping);
+    }
+
+    public SequenceI getFromSeq()
+    {
+      return fromSeq;
+    }
+
+    public Mapping getMapping()
+    {
+      return mapping;
+    }
+
+    /**
+     * Returns true if the mapping covers the full length of the given sequence.
+     * This allows us to distinguish the CDS that codes for a protein from
+     * another overlapping CDS in the parent dna sequence.
+     * 
+     * @param seq
+     * @return
+     */
+    public boolean covers(SequenceI seq)
+    {
+      List<int[]> mappedRanges = null;
+      MapList mapList = mapping.getMap();
+      if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
+      {
+        mappedRanges = mapList.getFromRanges();
+      }
+      else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
+      {
+        mappedRanges = mapList.getToRanges();
+      }
+      else
+      {
+        return false;
+      }
+
+      /*
+       * check that each mapped range lieS with the sequence range
+       * (necessary for circular CDS - example EMBL:J03321:AAA91567)
+       * and mapped length covers (at least) sequence length
+       */
+      int length = 0;
+      for (int[] range : mappedRanges)
+      {
+        int from = Math.min(range[0], range[1]);
+        int to = Math.max(range[0], range[1]);
+        if (from < seq.getStart() || to > seq.getEnd())
+        {
+          return false;
+        }
+        length += (to - from + 1);
+      }
+      // add 1 to mapped length to allow for a mapped stop codon
+      if (length + 1 < (seq.getEnd() - seq.getStart() + 1))
+      {
+        return false;
+      }
+      return true;
+    }
   }
 
   private List<SequenceToSequenceMapping> mappings;
@@ -56,7 +165,7 @@ public class AlignedCodonFrame
    */
   public AlignedCodonFrame()
   {
-    mappings = new ArrayList<SequenceToSequenceMapping>();
+    mappings = new ArrayList<>();
   }
 
   /**
@@ -69,17 +178,34 @@ public class AlignedCodonFrame
    */
   public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
   {
+    addMap(dnaseq, aaseq, map, null);
+  }
+
+  /**
+   * Adds a mapping between the dataset sequences for the associated dna and
+   * protein sequence objects
+   * 
+   * @param dnaseq
+   * @param aaseq
+   * @param map
+   * @param mapFromId
+   */
+  public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
+          String mapFromId)
+  {
     // JBPNote DEBUG! THIS !
     // dnaseq.transferAnnotation(aaseq, mp);
     // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
 
     SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
             : dnaseq.getDatasetSequence();
-    SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq : aaseq
-            .getDatasetSequence();
+    SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
+            : aaseq.getDatasetSequence();
 
     /*
      * if we already hold a mapping between these sequences, just add to it 
+     * note that 'adding' a duplicate map does nothing; this protects against
+     * creating duplicate mappings in AlignedCodonFrame
      */
     for (SequenceToSequenceMapping ssm : mappings)
     {
@@ -94,6 +220,7 @@ public class AlignedCodonFrame
      * otherwise, add a new sequence mapping
      */
     Mapping mp = new Mapping(toSeq, map);
+    mp.setMappedFromId(mapFromId);
     mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
   }
 
@@ -101,7 +228,7 @@ public class AlignedCodonFrame
   {
     // TODO return a list instead?
     // return dnaSeqs;
-    List<SequenceI> seqs = new ArrayList<SequenceI>();
+    List<SequenceI> seqs = new ArrayList<>();
     for (SequenceToSequenceMapping ssm : mappings)
     {
       seqs.add(ssm.fromSeq);
@@ -112,7 +239,7 @@ public class AlignedCodonFrame
   public SequenceI[] getAaSeqs()
   {
     // TODO not used - remove?
-    List<SequenceI> seqs = new ArrayList<SequenceI>();
+    List<SequenceI> seqs = new ArrayList<>();
     for (SequenceToSequenceMapping ssm : mappings)
     {
       seqs.add(ssm.mapping.to);
@@ -122,7 +249,7 @@ public class AlignedCodonFrame
 
   public MapList[] getdnaToProt()
   {
-    List<MapList> maps = new ArrayList<MapList>();
+    List<MapList> maps = new ArrayList<>();
     for (SequenceToSequenceMapping ssm : mappings)
     {
       maps.add(ssm.mapping.map);
@@ -132,7 +259,7 @@ public class AlignedCodonFrame
 
   public Mapping[] getProtMappings()
   {
-    List<Mapping> maps = new ArrayList<Mapping>();
+    List<Mapping> maps = new ArrayList<>();
     for (SequenceToSequenceMapping ssm : mappings)
     {
       maps.add(ssm.mapping);
@@ -142,7 +269,7 @@ public class AlignedCodonFrame
 
   /**
    * Returns the first mapping found which is to or from the given sequence, or
-   * null.
+   * null if none is found
    * 
    * @param seq
    * @return
@@ -183,9 +310,12 @@ public class AlignedCodonFrame
   }
 
   /**
+   * Return the corresponding aligned or dataset dna sequence for given amino
+   * acid sequence, or null if not found. returns the sequence from the first
+   * mapping found that involves the protein sequence.
    * 
-   * @param sequenceRef
-   * @return null or corresponding aaSeq entry for dnaSeq entry
+   * @param aaSeqRef
+   * @return
    */
   public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
   {
@@ -224,7 +354,7 @@ public class AlignedCodonFrame
    *          where highlighted regions go
    */
   public void markMappedRegion(SequenceI seq, int index,
-          SearchResults results)
+          SearchResultsI results)
   {
     int[] codon;
     SequenceI ds = seq.getDatasetSequence();
@@ -293,7 +423,8 @@ public class AlignedCodonFrame
 
   /**
    * Convenience method to return the first aligned sequence in the given
-   * alignment whose dataset has a mapping with the given dataset sequence.
+   * alignment whose dataset has a mapping with the given (aligned or dataset)
+   * sequence.
    * 
    * @param seq
    * 
@@ -307,11 +438,12 @@ public class AlignedCodonFrame
      */
     for (SequenceToSequenceMapping ssm : mappings)
     {
-      if (ssm.fromSeq == seq)
+      if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
       {
         for (SequenceI sourceAligned : al.getSequences())
         {
-          if (ssm.mapping.to == sourceAligned.getDatasetSequence())
+          if (ssm.mapping.to == sourceAligned.getDatasetSequence()
+                  || ssm.mapping.to == sourceAligned)
           {
             return sourceAligned;
           }
@@ -324,7 +456,8 @@ public class AlignedCodonFrame
      */
     for (SequenceToSequenceMapping ssm : mappings)
     {
-      if (ssm.mapping.to == seq)
+      if (ssm.mapping.to == seq
+              || ssm.mapping.to == seq.getDatasetSequence())
       {
         for (SequenceI sourceAligned : al.getSequences())
         {
@@ -354,8 +487,8 @@ public class AlignedCodonFrame
   {
     SequenceI targetDs = target.getDatasetSequence() == null ? target
             : target.getDatasetSequence();
-    SequenceI queryDs = query.getDatasetSequence() == null ? query : query
-            .getDatasetSequence();
+    SequenceI queryDs = query.getDatasetSequence() == null ? query
+            : query.getDatasetSequence();
     if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
     {
       return null;
@@ -404,11 +537,12 @@ public class AlignedCodonFrame
   {
     MapList ml = null;
     SequenceI dnaSeq = null;
-    List<char[]> result = new ArrayList<char[]>();
+    List<char[]> result = new ArrayList<>();
 
     for (SequenceToSequenceMapping ssm : mappings)
     {
-      if (ssm.mapping.to == protein)
+      if (ssm.mapping.to == protein
+              && ssm.mapping.getMap().getFromRatio() == 3)
       {
         ml = ssm.mapping.map;
         dnaSeq = ssm.fromSeq;
@@ -423,33 +557,34 @@ public class AlignedCodonFrame
          * Read off the mapped nucleotides (converting to position base 0)
          */
         codonPos = MappingUtils.flattenRanges(codonPos);
-        char[] dna = dnaSeq.getSequence();
         int start = dnaSeq.getStart();
-        result.add(new char[] { dna[codonPos[0] - start],
-            dna[codonPos[1] - start], dna[codonPos[2] - start] });
+        char c1 = dnaSeq.getCharAt(codonPos[0] - start);
+        char c2 = dnaSeq.getCharAt(codonPos[1] - start);
+        char c3 = dnaSeq.getCharAt(codonPos[2] - start);
+        result.add(new char[] { c1, c2, c3 });
       }
     }
     return result.isEmpty() ? null : result;
   }
 
   /**
-   * Returns any mappings found which are to (or from) the given sequence, and
-   * to distinct sequences.
+   * Returns any mappings found which are from the given sequence, and to
+   * distinct sequences.
    * 
    * @param seq
    * @return
    */
-  public List<Mapping> getMappingsForSequence(SequenceI seq)
+  public List<Mapping> getMappingsFromSequence(SequenceI seq)
   {
-    List<Mapping> result = new ArrayList<Mapping>();
-    List<SequenceI> related = new ArrayList<SequenceI>();
+    List<Mapping> result = new ArrayList<>();
+    List<SequenceI> related = new ArrayList<>();
     SequenceI seqDs = seq.getDatasetSequence();
     seqDs = seqDs != null ? seqDs : seq;
 
     for (SequenceToSequenceMapping ssm : mappings)
     {
       final Mapping mapping = ssm.mapping;
-      if (ssm.fromSeq == seqDs || mapping.to == seqDs)
+      if (ssm.fromSeq == seqDs)
       {
         if (!related.contains(mapping.to))
         {
@@ -498,8 +633,9 @@ public class AlignedCodonFrame
    */
   protected int realiseWith(SequenceI seq, boolean doUpdate)
   {
-    SequenceI ds = seq.getDatasetSequence() != null ? seq
-            .getDatasetSequence() : seq;
+    SequenceI ds = seq.getDatasetSequence() != null
+            ? seq.getDatasetSequence()
+            : seq;
     int count = 0;
 
     /*
@@ -573,8 +709,8 @@ public class AlignedCodonFrame
     {
       int start = replacement.getStart();
       int end = replacement.getEnd();
-      boolean mappingOverlapsSequence = (mapStart >= start && mapStart <= end)
-              || (mapEnd >= start && mapEnd <= end);
+      boolean mappingOverlapsSequence = (mapStart >= start
+              && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
       if (mappingOverlapsSequence)
       {
         return true;
@@ -617,4 +753,107 @@ public class AlignedCodonFrame
       }
     }
   }
+
+  /**
+   * Answers true if this object contains no mappings
+   * 
+   * @return
+   */
+  public boolean isEmpty()
+  {
+    return mappings.isEmpty();
+  }
+
+  /**
+   * Method for debug / inspection purposes only, may change in future
+   */
+  @Override
+  public String toString()
+  {
+    return mappings == null ? "null" : mappings.toString();
+  }
+
+  /**
+   * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
+   * null if none found
+   * 
+   * @param fromSeq
+   *          aligned or dataset sequence
+   * @param toSeq
+   *          aligned or dataset sequence
+   * @return
+   */
+  public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
+  {
+    SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
+            : fromSeq.getDatasetSequence();
+    SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
+            : toSeq.getDatasetSequence();
+
+    for (SequenceToSequenceMapping mapping : mappings)
+    {
+      SequenceI from = mapping.fromSeq;
+      SequenceI to = mapping.mapping.to;
+      if ((from == dssFrom && to == dssTo)
+              || (from == dssTo && to == dssFrom))
+      {
+        return mapping.mapping;
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Returns a hashcode derived from the list of sequence mappings
+   * 
+   * @see SequenceToSequenceMapping#hashCode()
+   * @see AbstractList#hashCode()
+   */
+  @Override
+  public int hashCode()
+  {
+    return this.mappings.hashCode();
+  }
+
+  /**
+   * Two AlignedCodonFrame objects are equal if they hold the same ordered list
+   * of mappings
+   * 
+   * @see SequenceToSequenceMapping#equals
+   */
+  @Override
+  public boolean equals(Object obj)
+  {
+    if (!(obj instanceof AlignedCodonFrame))
+    {
+      return false;
+    }
+    return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
+  }
+
+  public List<SequenceToSequenceMapping> getMappings()
+  {
+    return mappings;
+  }
+
+  /**
+   * Returns the first mapping found which is between the two given sequences,
+   * and covers the full extent of both.
+   * 
+   * @param seq1
+   * @param seq2
+   * @return
+   */
+  public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
+          SequenceI seq2)
+  {
+    for (SequenceToSequenceMapping mapping : mappings)
+    {
+      if (mapping.covers(seq2) && mapping.covers(seq1))
+      {
+        return mapping;
+      }
+    }
+    return null;
+  }
 }