merge
authortcofoegbu <tcnofoegbu@dundee.ac.uk>
Wed, 16 Sep 2015 13:56:31 +0000 (14:56 +0100)
committertcofoegbu <tcnofoegbu@dundee.ac.uk>
Wed, 16 Sep 2015 13:56:31 +0000 (14:56 +0100)
24 files changed:
examples/javascript/jalview.js
src/jalview/analysis/AlignmentUtils.java
src/jalview/appletgui/AlignFrame.java
src/jalview/appletgui/CutAndPasteTransfer.java
src/jalview/appletgui/SeqPanel.java
src/jalview/appletgui/SplitFrame.java
src/jalview/bin/JalviewLite.java
src/jalview/commands/EditCommand.java
src/jalview/datamodel/AlignedCodonFrame.java
src/jalview/datamodel/Mapping.java
src/jalview/gui/AlignFrame.java
src/jalview/gui/AlignViewport.java
src/jalview/gui/SeqPanel.java
src/jalview/javascript/MouseOverStructureListener.java
src/jalview/jbgui/GAlignFrame.java
src/jalview/util/HttpUtils.java [new file with mode: 0644]
src/jalview/ws/DBRefFetcher.java
test/jalview/analysis/AlignmentUtilsTests.java
test/jalview/bin/JalviewLiteTest.java [new file with mode: 0644]
test/jalview/commands/EditCommandTest.java
test/jalview/datamodel/AlignedCodonFrameTest.java
test/jalview/datamodel/AlignedCodonIteratorTest.java
test/jalview/datamodel/AlignmentTest.java
test/jalview/util/MappingUtilsTest.java

index 7172948..1c1f1c2 100644 (file)
@@ -318,10 +318,8 @@ function _jmolhover(jmid, atomlabel, atomidx) {
        }
        // use atomlabel[5] to look up model filename so we can highlight associated positions in any jalviews
        for (ap in _jvapps) {
-               _jvapps[ap].mouseOverStructure(atomlabel[2], atomlabel[3],
-                               getDocumentBase()
-                                               + "/" + 
-                                               modeltofiles[atomlabel[5]]);
+               pdb = getDocumentBase() + modeltofiles[atomlabel[5]];
+               _jvapps[ap].mouseOverStructure(atomlabel[2], atomlabel[3], pdb);
                msg = _jmolhovermsg;
        }
 }
index cbd9c96..05e844c 100644 (file)
@@ -228,7 +228,7 @@ public class AlignmentUtils
    * @param cdnaAlignment
    * @return
    */
-  public static boolean mapProteinToCdna(final AlignmentI proteinAlignment,
+  public static boolean mapProteinAlignmentToCdna(final AlignmentI proteinAlignment,
           final AlignmentI cdnaAlignment)
   {
     if (proteinAlignment == null || cdnaAlignment == null)
@@ -275,7 +275,7 @@ public class AlignmentUtils
           final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
           Set<SequenceI> mappedProtein, boolean xrefsOnly)
   {
-    boolean mappingPerformed = false;
+    boolean mappingExistsOrAdded = false;
     List<SequenceI> thisSeqs = proteinAlignment.getSequences();
     for (SequenceI aaSeq : thisSeqs)
     {
@@ -308,14 +308,18 @@ public class AlignmentUtils
         {
           continue;
         }
-        if (!mappingExists(proteinAlignment.getCodonFrames(),
+        if (mappingExists(proteinAlignment.getCodonFrames(),
                 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
         {
-          MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
+          mappingExistsOrAdded = true;
+        }
+        else
+        {
+          MapList map = mapProteinSequenceToCdna(aaSeq, cdnaSeq);
           if (map != null)
           {
             acf.addMap(cdnaSeq, aaSeq, map);
-            mappingPerformed = true;
+            mappingExistsOrAdded = true;
             proteinMapped = true;
             mappedDna.add(cdnaSeq);
             mappedProtein.add(aaSeq);
@@ -327,7 +331,7 @@ public class AlignmentUtils
         proteinAlignment.addCodonFrame(acf);
       }
     }
-    return mappingPerformed;
+    return mappingExistsOrAdded;
   }
 
   /**
@@ -360,7 +364,7 @@ public class AlignmentUtils
    * @param cdnaSeq
    * @return
    */
-  public static MapList mapProteinToCdna(SequenceI proteinSeq,
+  public static MapList mapProteinSequenceToCdna(SequenceI proteinSeq,
           SequenceI cdnaSeq)
   {
     /*
@@ -384,10 +388,10 @@ public class AlignmentUtils
      */
     final int mappedLength = 3 * aaSeqChars.length;
     int cdnaLength = cdnaSeqChars.length;
-    int cdnaStart = 1;
-    int cdnaEnd = cdnaLength;
-    final int proteinStart = 1;
-    final int proteinEnd = aaSeqChars.length;
+    int cdnaStart = cdnaSeq.getStart();
+    int cdnaEnd = cdnaSeq.getEnd();
+    final int proteinStart = proteinSeq.getStart();
+    final int proteinEnd = proteinSeq.getEnd();
 
     /*
      * If lengths don't match, try ignoring stop codon.
@@ -410,11 +414,13 @@ public class AlignmentUtils
     /*
      * If lengths still don't match, try ignoring start codon.
      */
+    int startOffset = 0;
     if (cdnaLength != mappedLength
             && cdnaLength > 2
             && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
                     .equals(ResidueProperties.START))
     {
+      startOffset += 3;
       cdnaStart += 3;
       cdnaLength -= 3;
     }
@@ -423,7 +429,8 @@ public class AlignmentUtils
     {
       return null;
     }
-    if (!translatesAs(cdnaSeqChars, cdnaStart - 1, aaSeqChars))
+    if (!translatesAs(cdnaSeqChars, startOffset,
+            aaSeqChars))
     {
       return null;
     }
@@ -567,6 +574,8 @@ public class AlignmentUtils
     /*
      * Traverse the aligned protein sequence.
      */
+    int fromOffset = alignFrom.getStart() - 1;
+    int toOffset = alignTo.getStart() - 1;
     int sourceGapMappedLength = 0;
     boolean inExon = false;
     for (char sourceChar : thatAligned)
@@ -583,7 +592,7 @@ public class AlignmentUtils
       sourceDsPos++;
       // Note mapping positions are base 1, our sequence positions base 0
       int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
-              sourceDsPos);
+              sourceDsPos + fromOffset);
       if (mappedPos == null)
       {
         /*
@@ -607,14 +616,15 @@ public class AlignmentUtils
        * But then 'align dna as protein' doesn't make much sense otherwise.
        */
       int intronLength = 0;
-      while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
+      while (basesWritten + toOffset < mappedCodonEnd
+              && thisSeqPos < thisSeq.length)
       {
         final char c = thisSeq[thisSeqPos++];
         if (c != myGapChar)
         {
           basesWritten++;
-
-          if (basesWritten < mappedCodonStart)
+          int sourcePosition = basesWritten + toOffset;
+          if (sourcePosition < mappedCodonStart)
           {
             /*
              * Found an unmapped (intron) base. First add in any preceding gaps
@@ -631,7 +641,7 @@ public class AlignmentUtils
           }
           else
           {
-            final boolean startOfCodon = basesWritten == mappedCodonStart;
+            final boolean startOfCodon = sourcePosition == mappedCodonStart;
             int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
                     preserveUnmappedGaps, sourceGapMappedLength, inExon,
                     trailingCopiedGap.length(), intronLength, startOfCodon);
@@ -1090,7 +1100,7 @@ public class AlignmentUtils
      * Just try to make a mapping (it is not yet stored), test whether
      * successful.
      */
-    return mapProteinToCdna(proteinDs, dnaDs) != null;
+    return mapProteinSequenceToCdna(proteinDs, dnaDs) != null;
   }
 
   /**
index 3996dee..c9183d5 100644 (file)
@@ -302,6 +302,8 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
     alignPanel.annotationSpaceFillerHolder.addKeyListener(this);
     alignPanel.alabels.addKeyListener(this);
 
+    setAnnotationsVisibility();
+
     if (addToDisplay)
     {
       addToDisplay(embedded);
@@ -913,7 +915,7 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
 
   /**
    * Set the visibility state of sequence-related and/or alignment-related
-   * annotations depending on checkbox selections. Repaint after calling.
+   * annotations depending on checkbox selections, and repaint.
    * 
    * @param visible
    */
@@ -3357,8 +3359,11 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener,
             MessageManager.getString("label.sort_annotations_by_label"));
     showAutoFirst = new CheckboxMenuItem(
             MessageManager.getString("label.show_first"));
+    showAutoFirst.setState(false); // pending applet parameter
+    setShowAutoCalculatedAbove(showAutoFirst.getState());
     showAutoLast = new CheckboxMenuItem(
             MessageManager.getString("label.show_last"));
+    showAutoLast.setState(!showAutoFirst.getState());
     showAlignmentAnnotations.addItemListener(this);
     showSequenceAnnotations.addItemListener(this);
     sortAnnBySequence.addItemListener(this);
index 5617c64..4590c54 100644 (file)
@@ -304,7 +304,7 @@ public class CutAndPasteTransfer extends Panel implements ActionListener,
     }
     AlignmentI protein = thisAlignment.isNucleotide() ? al : thisAlignment;
     AlignmentI dna = thisAlignment.isNucleotide() ? thisAlignment : al;
-    boolean mapped = AlignmentUtils.mapProteinToCdna(protein, dna);
+    boolean mapped = AlignmentUtils.mapProteinAlignmentToCdna(protein, dna);
     if (!mapped)
     {
       return false;
@@ -332,6 +332,11 @@ public class CutAndPasteTransfer extends Panel implements ActionListener,
     }
 
     /*
+     * 'align' the added alignment to match the current one
+     */
+    al.alignAs(thisAlignment);
+
+    /*
      * Open SplitFrame with DNA above and protein below, including the alignment
      * from textbox and a copy of the original.
      */
index 9870e68..b4fefec 100644 (file)
@@ -481,7 +481,7 @@ public class SeqPanel extends Panel implements MouseMotionListener,
          * Convert position in sequence (base 1) to sequence character array
          * index (base 0)
          */
-        int start = m.getStart() - 1;
+        int start = m.getStart() - m.getSequence().getStart();
         setStatusMessage(seq, start, sequenceIndex);
         return true;
       }
index 57a6732..cbad148 100644 (file)
@@ -20,7 +20,6 @@
  */
 package jalview.appletgui;
 
-import jalview.analysis.AlignmentUtils;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.ViewStyleI;
 import jalview.bin.JalviewLite;
@@ -44,12 +43,14 @@ public class SplitFrame extends EmbmenuFrame
   private Panel outermost;
 
   /**
-   * Constructor
+   * Constructs the split frame placing cdna in the top half. No 'alignment' is
+   * performed here, this should be done by the calling client if wanted.
    */
   public SplitFrame(AlignFrame af1, AlignFrame af2)
   {
-    topFrame = af1;
-    bottomFrame = af2;
+    boolean af1IsNucleotide = af1.viewport.getAlignment().isNucleotide();
+    topFrame = af1IsNucleotide ? af1 : af2;
+    bottomFrame = topFrame == af1 ? af2 : af1;
     init();
   }
 
@@ -75,20 +76,15 @@ public class SplitFrame extends EmbmenuFrame
     AlignmentViewport protein = !topAlignment.isNucleotide() ? topViewport
             : (!bottomAlignment.isNucleotide() ? bottomViewport : null);
 
-    boolean mapped = AlignmentUtils.mapProteinToCdna(
-            protein.getAlignment(), cdna.getAlignment());
-    if (mapped)
-    {
-      final StructureSelectionManager ssm = StructureSelectionManager
-              .getStructureSelectionManager(topViewport.applet);
-      ssm.registerMappings(protein.getAlignment().getCodonFrames());
-      topViewport.setCodingComplement(bottomViewport);
-      ssm.addCommandListener(cdna);
-      ssm.addCommandListener(protein);
-    }
+    final StructureSelectionManager ssm = StructureSelectionManager
+            .getStructureSelectionManager(topViewport.applet);
+    ssm.registerMappings(protein.getAlignment().getCodonFrames());
+    topViewport.setCodingComplement(bottomViewport);
+    ssm.addCommandListener(cdna);
+    ssm.addCommandListener(protein);
 
     /*
-     * Now mappings exist, can compute cDNA consensus on protein alignment
+     * Compute cDNA consensus on protein alignment
      */
     protein.initComplementConsensus();
     AlignmentViewPanel ap = topAlignment.isNucleotide() ? bottomFrame.alignPanel
index 3024e66..3d59a12 100644 (file)
@@ -45,8 +45,10 @@ import jalview.io.NewickFile;
 import jalview.javascript.JSFunctionExec;
 import jalview.javascript.JalviewLiteJsApi;
 import jalview.javascript.JsCallBack;
+import jalview.javascript.MouseOverStructureListener;
 import jalview.structure.SelectionListener;
 import jalview.structure.StructureSelectionManager;
+import jalview.util.HttpUtils;
 import jalview.util.MessageManager;
 
 import java.applet.Applet;
@@ -61,10 +63,9 @@ import java.awt.event.ActionEvent;
 import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
 import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Hashtable;
 import java.util.List;
 import java.util.StringTokenizer;
@@ -92,7 +93,7 @@ public class JalviewLite extends Applet implements
   }
 
   // /////////////////////////////////////////
-  // The following public methods maybe called
+  // The following public methods may be called
   // externally, eg via javascript in HTML page
   /*
    * (non-Javadoc)
@@ -956,11 +957,16 @@ public class JalviewLite extends Applet implements
     }
   }
 
-  /*
-   * (non-Javadoc)
-   * 
+  /**
+   * Callable from javascript to register a javascript function to pass events
+   * to a structure viewer.
+   *
+   * @param listener
+   *          the name of a javascript function
+   * @param modelSet
+   *          a token separated list of PDB file names listened for
    * @see jalview.bin.JalviewLiteJsApi#setStructureListener(java.lang.String,
-   * java.lang.String)
+   *      java.lang.String)
    */
   public void setStructureListener(String listener, String modelSet)
   {
@@ -974,8 +980,8 @@ public class JalviewLite extends Applet implements
         return;
       }
     }
-    jalview.javascript.MouseOverStructureListener mol = new jalview.javascript.MouseOverStructureListener(
-            this, listener, separatorListToArray(modelSet));
+    MouseOverStructureListener mol = new MouseOverStructureListener(this,
+            listener, separatorListToArray(modelSet));
     javascriptListeners.addElement(mol);
     StructureSelectionManager.getStructureSelectionManager(this)
             .addStructureViewerListener(mol);
@@ -1345,9 +1351,10 @@ public class JalviewLite extends Applet implements
   /**
    * init method for Jalview Applet
    */
+  @Override
   public void init()
   {
-    // remove any handlers that might be hanging around from an earlier instance
+    debug = TRUE.equalsIgnoreCase(getParameter("debug"));
     try
     {
       if (debug)
@@ -1370,17 +1377,12 @@ public class JalviewLite extends Applet implements
         ex.printStackTrace();
       }
     }
-    /**
-     * turn on extra applet debugging
-     */
-    debug = TRUE.equalsIgnoreCase(getParameter("debug"));
+
     if (debug)
     {
-
       System.err.println("JalviewLite Version " + getVersion());
       System.err.println("Build Date : " + getBuildDate());
       System.err.println("Installation : " + getInstallation());
-
     }
     String externalsviewer = getParameter("externalstructureviewer");
     if (externalsviewer != null)
@@ -1789,27 +1791,72 @@ public class JalviewLite extends Applet implements
      * update the protocol state variable for accessing the datasource located
      * by file.
      * 
-     * @param file
+     * @param path
      * @return possibly updated datasource string
      */
-    public String setProtocolState(String file)
+    public String resolveFileProtocol(String path)
     {
-      if (file.startsWith("PASTE"))
+      /*
+       * is it paste data?
+       */
+      if (path.startsWith("PASTE"))
       {
-        file = file.substring(5);
         protocol = AppletFormatAdapter.PASTE;
+        return path.substring(5);
       }
-      else if (inArchive(file))
+
+      /*
+       * is it a URL?
+       */
+      if (path.indexOf("://") != -1)
       {
-        protocol = AppletFormatAdapter.CLASSLOADER;
+        protocol = AppletFormatAdapter.URL;
+        return path;
       }
-      else
+
+      /*
+       * try relative to document root
+       */
+      URL documentBase = getDocumentBase();
+      String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
+      if (HttpUtils.isValidUrl(withDocBase))
+      {
+        if (debug)
+        {
+          System.err.println("Prepended document base '" + documentBase
+                  + "' to make: '" + withDocBase + "'");
+        }
+        protocol = AppletFormatAdapter.URL;
+        return withDocBase;
+      }
+
+      /*
+       * try relative to codebase (if different to document base)
+       */
+      URL codeBase = getCodeBase();
+      String withCodeBase = applet.resolveUrlForLocalOrAbsolute(path,
+              codeBase);
+      if (!withCodeBase.equals(withDocBase)
+              && HttpUtils.isValidUrl(withCodeBase))
       {
-        file = addProtocol(file);
         protocol = AppletFormatAdapter.URL;
+        if (debug)
+        {
+          System.err.println("Prepended codebase '" + codeBase
+                  + "' to make: '" + withCodeBase + "'");
+        }
+        return withCodeBase;
+      }
+
+      /*
+       * try locating by classloader; try this last so files in the directory
+       * are resolved using document base
+       */
+      if (inArchive(path))
+      {
+        protocol = AppletFormatAdapter.CLASSLOADER;
       }
-      dbgMsg("Protocol identified as '" + protocol + "'");
-      return file;
+      return path;
     }
 
     public LoadingThread(String file, String file2, JalviewLite _applet)
@@ -1885,8 +1932,11 @@ public class JalviewLite extends Applet implements
       {
         AlignmentI al1 = af.viewport.getAlignment();
         AlignmentI al2 = af2.viewport.getAlignment();
-        if (AlignmentUtils.isMappable(al1, al2))
+        AlignmentI cdna = al1.isNucleotide() ? al1 : al2;
+        AlignmentI prot = al1.isNucleotide() ? al2 : al1;
+        if (AlignmentUtils.mapProteinAlignmentToCdna(prot, cdna))
         {
+          al2.alignAs(al1);
           SplitFrame sf = new SplitFrame(af, af2);
           sf.addToDisplay(embedded, JalviewLite.this);
           return;
@@ -1916,7 +1966,7 @@ public class JalviewLite extends Applet implements
       {
         return null;
       }
-      String resolvedFile = setProtocolState(fileParam);
+      String resolvedFile = resolveFileProtocol(fileParam);
       String format = new IdentifyFile().Identify(resolvedFile, protocol);
       dbgMsg("File identified as '" + format + "'");
       AlignmentI al = null;
@@ -2051,8 +2101,8 @@ public class JalviewLite extends Applet implements
           else
           {
             param = st.nextToken();
-            Vector tmp = new Vector();
-            Vector tmp2 = new Vector();
+            List<SequenceI> tmp = new ArrayList<SequenceI>();
+            List<String> tmp2 = new ArrayList<String>();
 
             while (st.hasMoreTokens())
             {
@@ -2061,39 +2111,22 @@ public class JalviewLite extends Applet implements
               if (st2.countTokens() > 1)
               {
                 // This is the chain
-                tmp2.addElement(st2.nextToken());
+                tmp2.add(st2.nextToken());
                 seqstring = st2.nextToken();
               }
-              tmp.addElement(matcher == null ? (Sequence) alignFrame
+              tmp.add(matcher == null ? (Sequence) alignFrame
                       .getAlignViewport().getAlignment()
                       .findName(seqstring) : matcher.findIdMatch(seqstring));
             }
 
-            seqs = new SequenceI[tmp.size()];
-            tmp.copyInto(seqs);
+            seqs = tmp.toArray(new SequenceI[tmp.size()]);
             if (tmp2.size() == tmp.size())
             {
-              chains = new String[tmp2.size()];
-              tmp2.copyInto(chains);
+              chains = tmp2.toArray(new String[tmp2.size()]);
             }
           }
-          param = setProtocolState(param);
-
-          if (// !jmolAvailable
-          // &&
-          protocol == AppletFormatAdapter.CLASSLOADER && !useXtrnalSviewer)
-          {
-            // Re: JAL-357 : the bug isn't a problem if we are using an
-            // external viewer!
-            // TODO: verify this Re:
-            // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
-            // This exception preserves the current behaviour where, even if
-            // the local pdb file was identified in the class loader
-            protocol = AppletFormatAdapter.URL; // this is probably NOT
-            // CORRECT!
-            param = addProtocol(param); //
-          }
-
+          param = resolveFileProtocol(param);
+          // TODO check JAL-357 for files in a jar (CLASSLOADER)
           pdb.setFile(param);
 
           if (seqs != null)
@@ -2170,7 +2203,7 @@ public class JalviewLite extends Applet implements
       {
         try
         {
-          param = setProtocolState(param);
+          param = resolveFileProtocol(param);
           JPredFile predictions = new JPredFile(param, protocol);
           JnetAnnotationMaker.add_annotation(predictions,
                   alignFrame.viewport.getAlignment(), 0, false);
@@ -2205,7 +2238,7 @@ public class JalviewLite extends Applet implements
       String param = applet.getParameter("annotations");
       if (param != null)
       {
-        param = setProtocolState(param);
+        param = resolveFileProtocol(param);
 
         if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
                 param, protocol))
@@ -2258,7 +2291,7 @@ public class JalviewLite extends Applet implements
       param = applet.getParameter("features");
       if (param != null)
       {
-        param = setProtocolState(param);
+        param = resolveFileProtocol(param);
 
         result = alignFrame.parseFeaturesFile(param, protocol);
       }
@@ -2327,7 +2360,7 @@ public class JalviewLite extends Applet implements
       {
         try
         {
-          treeFile = setProtocolState(treeFile);
+          treeFile = resolveFileProtocol(treeFile);
           NewickFile fin = new NewickFile(treeFile, protocol);
           fin.parse();
 
@@ -2352,114 +2385,30 @@ public class JalviewLite extends Applet implements
     /**
      * Discovers whether the given file is in the Applet Archive
      * 
-     * @param file
+     * @param f
      *          String
      * @return boolean
      */
-    boolean inArchive(String file)
+    boolean inArchive(String f)
     {
       // This might throw a security exception in certain browsers
       // Netscape Communicator for instance.
       try
       {
-        boolean rtn = (getClass().getResourceAsStream("/" + file) != null);
+        boolean rtn = (getClass().getResourceAsStream("/" + f) != null);
         if (debug)
         {
-          System.err.println("Resource '" + file + "' was "
-                  + (rtn ? "" : "not") + " located by classloader.");
+          System.err.println("Resource '" + f + "' was "
+                  + (rtn ? "" : "not ") + "located by classloader.");
         }
         return rtn;
       } catch (Exception ex)
       {
-        System.out.println("Exception checking resources: " + file + " "
+        System.out.println("Exception checking resources: " + f + " "
                 + ex);
         return false;
       }
     }
-
-    /**
-     * If the file is not already in URL format, tries to locate it by resolving
-     * as a URL.
-     * 
-     * @param f
-     * @return
-     */
-    String addProtocol(final String f)
-    {
-      if (f.indexOf("://") != -1)
-      {
-        // already has URL format
-        return f;
-      }
-
-      /*
-       * Try relative to document base
-       */
-      URL documentBase = getDocumentBase();
-      String url = applet.resolveUrlForLocalOrAbsolute(f, documentBase);
-      if (urlExists(url))
-      {
-        if (debug)
-        {
-          System.err.println("Prepended document base '" + documentBase
-                  + "' to make: '" + url + "'");
-        }
-        return url;
-      }
-
-      /*
-       * Try relative to codebase
-       */
-      URL codeBase = getCodeBase();
-      url = applet.resolveUrlForLocalOrAbsolute(f, codeBase);
-      if (urlExists(url))
-      {
-        if (debug)
-        {
-          System.err.println("Prepended codebase '" + codeBase
-                  + "' to make: '" + url + "'");
-        }
-        return url;
-      }
-
-      return f;
-    }
-
-    /**
-     * Returns true if an input stream can be opened on the specified URL, else
-     * false.
-     * 
-     * @param url
-     * @return
-     */
-    private boolean urlExists(String url)
-    {
-      InputStream is = null;
-      try
-      {
-        is = new URL(url).openStream();
-        if (is != null)
-        {
-          return true;
-        }
-      } catch (Exception x)
-      {
-        // ignore
-      } finally
-      {
-        if (is != null)
-        {
-          try
-          {
-            is.close();
-          } catch (IOException e)
-          {
-            // ignore
-          }
-        }
-      }
-      return false;
-    }
   }
 
   /**
@@ -2512,8 +2461,9 @@ public class JalviewLite extends Applet implements
    * @param separator
    * @return elements separated by separator
    */
-  public String[] separatorListToArray(String list, String separator)
+  public static String[] separatorListToArray(String list, String separator)
   {
+    // TODO use StringUtils version (slightly different...)
     int seplen = separator.length();
     if (list == null || list.equals("") || list.equals(separator))
     {
@@ -2579,8 +2529,9 @@ public class JalviewLite extends Applet implements
    * @param separator
    * @return concatenated string
    */
-  public String arrayToSeparatorList(String[] list, String separator)
+  public static String arrayToSeparatorList(String[] list, String separator)
   {
+    // TODO use StringUtils version
     StringBuffer v = new StringBuffer();
     if (list != null && list.length > 0)
     {
@@ -2898,35 +2849,52 @@ public class JalviewLite extends Applet implements
    * form a complete URL given a path to a resource and a reference location on
    * the same server
    * 
-   * @param url
+   * @param targetPath
    *          - an absolute path on the same server as localref or a document
    *          located relative to localref
    * @param localref
    *          - a URL on the same server as url
    * @return a complete URL for the resource located by url
    */
-  private String resolveUrlForLocalOrAbsolute(String url, URL localref)
+  private String resolveUrlForLocalOrAbsolute(String targetPath,
+          URL localref)
   {
-    String codebase = localref.toString();
-    if (url.indexOf("/") == 0)
+    String resolvedPath = "";
+
+    /*
+     * get URL path and strip off any trailing file e.g.
+     * www.jalview.org/examples/index.html#applets?a=b is trimmed to
+     * www.jalview.org/examples/
+     */
+    String urlPath = localref.toString();
+    String directoryPath = urlPath;
+    int lastSeparator = directoryPath.lastIndexOf("/");
+    if (lastSeparator > 0)
+    {
+      directoryPath = directoryPath.substring(0, lastSeparator + 1);
+    }
+
+    if (targetPath.startsWith("/"))
     {
-      String localfile = localref.getFile();
-      url = codebase.substring(0, codebase.length() - localfile.length())
-              + url;
+      /*
+       * construct absolute URL to a file on the server - this is not allowed?
+       */
+      // String localfile = localref.getFile();
+      // resolvedPath = urlPath.substring(0,
+      // urlPath.length() - localfile.length())
+      // + targetPath;
+      resolvedPath = directoryPath + targetPath.substring(1);
     }
     else
     {
-      url = localref + url;
+      resolvedPath = directoryPath + targetPath;
     }
     if (debug)
     {
-      System.err.println("URL: " + localref.toString());
-      System.err.println("URL.getFile: " + localref.getFile());
-      System.err.println("URL.getPath: " + localref.getPath());
-      System.err.println("URL.getQuery: " + localref.getQuery());
-      System.err.println("returning " + url);
+      System.err.println("resolveUrlForLocalOrAbsolute returning "
+              + resolvedPath);
     }
-    return url;
+    return resolvedPath;
   }
 
   /**
@@ -2948,8 +2916,8 @@ public class JalviewLite extends Applet implements
         URL prepend;
         url = resolveUrlForLocalOrAbsolute(
                 url,
-                prepend = getDefaultParameter("resolvetocodebase", false) ? getDocumentBase()
-                        : getCodeBase());
+                prepend = getDefaultParameter("resolvetocodebase", false) ? getCodeBase()
+                        : getDocumentBase());
         if (debug)
         {
           System.err
index 4b21137..21ff841 100644 (file)
@@ -1220,10 +1220,15 @@ public class EditCommand implements CommandI
         for (SequenceI seq : e.getSequences())
         {
           SequenceI ds = seq.getDatasetSequence();
-          SequenceI preEdit = result.get(ds);
-          if (preEdit == null)
+          // SequenceI preEdit = result.get(ds);
+          if (!result.containsKey(ds))
           {
-            preEdit = new Sequence("", seq.getSequenceAsString());
+            /*
+             * copy sequence including start/end (but don't use copy constructor
+             * as we don't need annotations)
+             */
+            SequenceI preEdit = new Sequence("", seq.getSequenceAsString(),
+                    seq.getStart(), seq.getEnd());
             preEdit.setDatasetSequence(ds);
             result.put(ds, preEdit);
           }
@@ -1236,10 +1241,10 @@ public class EditCommand implements CommandI
      * Work backwards through the edit list, deriving the sequences before each
      * was applied. The final result is the sequence set before any edits.
      */
-    Iterator<Edit> edits = new ReverseListIterator<Edit>(getEdits());
-    while (edits.hasNext())
+    Iterator<Edit> editList = new ReverseListIterator<Edit>(getEdits());
+    while (editList.hasNext())
     {
-      Edit oldEdit = edits.next();
+      Edit oldEdit = editList.next();
       Action action = oldEdit.getAction();
       int position = oldEdit.getPosition();
       int number = oldEdit.getNumber();
@@ -1250,7 +1255,8 @@ public class EditCommand implements CommandI
         SequenceI preEdit = result.get(ds);
         if (preEdit == null)
         {
-          preEdit = new Sequence("", seq.getSequenceAsString());
+          preEdit = new Sequence("", seq.getSequenceAsString(),
+                  seq.getStart(), seq.getEnd());
           preEdit.setDatasetSequence(ds);
           result.put(ds, preEdit);
         }
index 627f0a6..9c642cf 100644 (file)
@@ -399,13 +399,13 @@ public class AlignedCodonFrame
       return null;
     }
     MapList ml = null;
-    char[] dnaSeq = null;
+    SequenceI dnaSeq = null;
     for (int i = 0; i < dnaToProt.length; i++)
     {
       if (dnaToProt[i].to == protein)
       {
         ml = getdnaToProt()[i];
-        dnaSeq = dnaSeqs[i].getSequence();
+        dnaSeq = dnaSeqs[i];
         break;
       }
     }
@@ -423,8 +423,10 @@ public class AlignedCodonFrame
      * Read off the mapped nucleotides (converting to position base 0)
      */
     codonPos = MappingUtils.flattenRanges(codonPos);
-    return new char[] { dnaSeq[codonPos[0] - 1], dnaSeq[codonPos[1] - 1],
-        dnaSeq[codonPos[2] - 1] };
+    char[] dna = dnaSeq.getSequence();
+    int start = dnaSeq.getStart();
+    return new char[] { dna[codonPos[0] - start], dna[codonPos[1] - start],
+        dna[codonPos[2] - start] };
   }
 
   /**
index 1272538..ea08d97 100644 (file)
@@ -48,6 +48,11 @@ public class Mapping
     private final char[] alignedSeq;
 
     /*
+     * the sequence start residue
+     */
+    private int start;
+
+    /*
      * Next position (base 0) in the aligned sequence
      */
     private int alignedColumn = 0;
@@ -90,13 +95,14 @@ public class Mapping
     /**
      * Constructor
      * 
-     * @param cs
-     *          the aligned sequence characters
+     * @param seq
+     *          the aligned sequence
      * @param gapChar
      */
-    public AlignedCodonIterator(char[] cs, char gapChar)
+    public AlignedCodonIterator(SequenceI seq, char gapChar)
     {
-      this.alignedSeq = cs;
+      this.alignedSeq = seq.getSequence();
+      this.start = seq.getStart();
       this.gap = gapChar;
       fromRanges = map.getFromRanges().iterator();
       toRanges = map.getToRanges().iterator();
@@ -165,7 +171,8 @@ public class Mapping
       // i.e. code like getNextCodon()
       if (toPosition <= currentToRange[1])
       {
-        char pep = Mapping.this.to.getSequence()[toPosition - 1];
+        SequenceI seq = Mapping.this.to;
+        char pep = seq.getSequence()[toPosition - seq.getStart()];
         toPosition++;
         return String.valueOf(pep);
       }
@@ -242,7 +249,11 @@ public class Mapping
      */
     private int getAlignedColumn(int sequencePos)
     {
-      while (alignedBases < sequencePos
+      /*
+       * allow for offset e.g. treat pos 8 as 2 if sequence starts at 7
+       */
+      int truePos = sequencePos - (start - 1);
+      while (alignedBases < truePos
               && alignedColumn < alignedSeq.length)
       {
         if (alignedSeq[alignedColumn++] != gap)
@@ -692,7 +703,7 @@ public class Mapping
 
   public Iterator<AlignedCodon> getCodonIterator(SequenceI seq, char gapChar)
   {
-    return new AlignedCodonIterator(seq.getSequence(), gapChar);
+    return new AlignedCodonIterator(seq, gapChar);
   }
 
 }
index 500dfdb..88271b9 100644 (file)
@@ -368,6 +368,9 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       setGUINucleotide(viewport.getAlignment().isNucleotide());
     }
 
+    this.alignPanel.av
+            .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
+
     setMenusFromViewport(viewport);
     buildSortByAnnotationScoresMenu();
     buildTreeMenu();
index 8378f30..a857f11 100644 (file)
@@ -926,7 +926,7 @@ public class AlignViewport extends AlignmentViewport implements
      * is a pre-requisite for building mappings.
      */
     al.setDataset(null);
-    AlignmentUtils.mapProteinToCdna(protein, cdna);
+    AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
 
     /*
      * Create the AlignFrame for the added alignment. If it is protein, mappings
index d379764..4ee87fc 100644 (file)
@@ -904,7 +904,7 @@ public class SeqPanel extends JPanel implements MouseListener,
          * Convert position in sequence (base 1) to sequence character array
          * index (base 0)
          */
-        int start = m.getStart() - 1;
+        int start = m.getStart() - m.getSequence().getStart();
         setStatusMessage(seq, start, sequenceIndex);
         return;
       }
index 2ef957e..199db46 100644 (file)
@@ -32,7 +32,11 @@ import jalview.structure.StructureListener;
 import jalview.structure.StructureMapping;
 import jalview.structure.StructureMappingcommandSet;
 import jalview.structure.StructureSelectionManager;
+import jalview.util.HttpUtils;
 
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -87,47 +91,43 @@ public class MouseOverStructureListener extends JSFunctionExec implements
     {
       for (int i = 0; i < modelSet.length; i++)
       {
-        // resolve a real filename
-        try
-        {
-          if (new java.net.URL(modelSet[i]).openConnection() != null)
-          {
-            continue;
-          }
-        } catch (Exception x)
-        {
-        }
-        ;
-        try
-        {
-          String db = jvlite.getDocumentBase().toString();
-          db = db.substring(0, db.lastIndexOf("/"));
-          if (new java.net.URL(db + "/" + modelSet[i]).openConnection() != null)
-          {
-            modelSet[i] = db + "/" + modelSet[i];
-            continue;
-          }
-        } catch (Exception x)
-        {
-        }
-        ;
-        try
-        {
-          if (new java.net.URL(jvlite.getCodeBase() + modelSet[i])
-                  .openConnection() != null)
-          {
-            modelSet[i] = jvlite.getCodeBase() + modelSet[i];
-            continue;
-          }
-        } catch (Exception x)
-        {
-        }
-        ;
-
+        modelSet[i] = resolveModelFile(modelSet[i]);
       }
     }
   }
 
+  /**
+   * Returns the first out of: file, file prefixed by document base, or file
+   * prefixed by codebase which can be resolved to a valid URL. If none can,
+   * returns the input parameter value.
+   * 
+   * @param file
+   */
+  public String resolveModelFile(String file)
+  {
+    // TODO reuse JalviewLite.LoadingThread.addProtocol instead
+    if (HttpUtils.isValidUrl(file))
+    {
+      return file;
+    }
+
+    String db = jvlite.getDocumentBase().toString();
+    db = db.substring(0, db.lastIndexOf("/"));
+    String docBaseFile = db + "/" + file;
+    if (HttpUtils.isValidUrl(docBaseFile))
+    {
+      return docBaseFile;
+    }
+
+    String cb = jvlite.getCodeBase() + file;
+    if (HttpUtils.isValidUrl(cb))
+    {
+      return cb;
+    }
+
+    return file;
+  }
+
   @Override
   public String[] getPdbFile()
   {
index 8d18064..73d34c2 100755 (executable)
@@ -1295,8 +1295,10 @@ public class GAlignFrame extends JInternalFrame
             MessageManager.getString("label.show_last"));
     buttonGroup.add(showAutoFirst);
     buttonGroup.add(showAutoLast);
-    showAutoFirst.setSelected(Cache.getDefault(
-            Preferences.SHOW_AUTOCALC_ABOVE, false));
+    final boolean autoFirst = Cache.getDefault(
+            Preferences.SHOW_AUTOCALC_ABOVE, false);
+    showAutoFirst.setSelected(autoFirst);
+    setShowAutoCalculatedAbove(autoFirst);
     showAutoFirst.addActionListener(new ActionListener()
     {
       @Override
diff --git a/src/jalview/util/HttpUtils.java b/src/jalview/util/HttpUtils.java
new file mode 100644 (file)
index 0000000..88df587
--- /dev/null
@@ -0,0 +1,47 @@
+package jalview.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+public class HttpUtils
+{
+
+  /**
+   * Returns true if it is possible to open an input stream at the given URL,
+   * else false. The input stream is closed.
+   * 
+   * @param url
+   * @return
+   */
+  public static boolean isValidUrl(String url)
+  {
+    InputStream is = null;
+    try
+    {
+      is = new URL(url).openStream();
+      if (is != null)
+      {
+        return true;
+      }
+    } catch (IOException x)
+    {
+      // MalformedURLException, FileNotFoundException
+      return false;
+    } finally
+    {
+      if (is != null)
+      {
+        try
+        {
+          is.close();
+        } catch (IOException e)
+        {
+          // ignore
+        }
+      }
+    }
+    return false;
+  }
+
+}
index 5f03ec7..03632c8 100644 (file)
@@ -125,9 +125,13 @@ public class DBRefFetcher implements Runnable
     {
       alseqs[i] = seqs[i];
       if (seqs[i].getDatasetSequence() != null)
+      {
         ds[i] = seqs[i].getDatasetSequence();
+      }
       else
+      {
         ds[i] = seqs[i];
+      }
     }
     this.dataset = ds;
     // TODO Jalview 2.5 lots of this code should be in the gui package!
@@ -596,9 +600,9 @@ public class DBRefFetcher implements Runnable
                 sequence.getSequenceAsString()).toUpperCase();
 
         int absStart = entrySeq.indexOf(nonGapped);
-        int mapStart = entry.getStart();
-        jalview.datamodel.Mapping mp;
+        Mapping mp;
 
+        final int sequenceStart = sequence.getStart();
         if (absStart == -1)
         {
           // Is local sequence contained in dataset sequence?
@@ -619,8 +623,8 @@ public class DBRefFetcher implements Runnable
           // create valid mapping between matching region of local sequence and
           // the mapped sequence
           mp = new Mapping(null, new int[] {
-              sequence.getStart() + absStart,
-              sequence.getStart() + absStart + entrySeq.length() - 1 },
+              sequenceStart + absStart,
+              sequenceStart + absStart + entrySeq.length() - 1 },
                   new int[] { entry.getStart(),
                       entry.getStart() + entrySeq.length() - 1 }, 1, 1);
           updateRefFrame = false; // mapping is based on current start/end so
@@ -645,7 +649,7 @@ public class DBRefFetcher implements Runnable
             if (sequence.getSequenceFeatures() != null)
             {
               SequenceFeature[] sf = sequence.getSequenceFeatures();
-              int start = sequence.getStart();
+              int start = sequenceStart;
               int end = sequence.getEnd();
               int startShift = 1 - absStart - start; // how much the features
                                                      // are
@@ -667,8 +671,8 @@ public class DBRefFetcher implements Runnable
                 + " from " + dbSource + " sequence : " + entry.getName());
         sequence.transferAnnotation(entry, mp);
         // unknownSequences.remove(sequence);
-        int absEnd = absStart + nonGapped.length();
-        absStart += 1;
+        absStart += entry.getStart();
+        int absEnd = absStart + nonGapped.length() - 1;
         if (!trimDatasetSeqs)
         {
           // insert full length sequence from record
index 2beacfe..84b9817 100644 (file)
@@ -281,7 +281,7 @@ public class AlignmentUtilsTests
    * @throws IOException
    */
   @Test(groups = { "Functional" })
-  public void testMapProteinToCdna_noXrefs() throws IOException
+  public void testMapProteinAlignmentToCdna_noXrefs() throws IOException
   {
     List<SequenceI> protseqs = new ArrayList<SequenceI>();
     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
@@ -298,7 +298,7 @@ public class AlignmentUtilsTests
     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
     cdna.setDataset(null);
 
-    assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
+    assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
 
     // 3 mappings made, each from 1 to 1 sequence
     assertEquals(3, protein.getCodonFrames().size());
@@ -617,7 +617,7 @@ public class AlignmentUtilsTests
    * @throws IOException
    */
   @Test(groups = { "Functional" })
-  public void testMapProteinToCdna_withStartAndStopCodons()
+  public void testMapProteinAlignmentToCdna_withStartAndStopCodons()
           throws IOException
   {
     List<SequenceI> protseqs = new ArrayList<SequenceI>();
@@ -638,7 +638,7 @@ public class AlignmentUtilsTests
     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
     cdna.setDataset(null);
 
-    assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
+    assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
 
     // 3 mappings made, each from 1 to 1 sequence
     assertEquals(3, protein.getCodonFrames().size());
@@ -710,7 +710,7 @@ public class AlignmentUtilsTests
    * @throws IOException
    */
   @Test(groups = { "Functional" })
-  public void testMapProteinToCdna_withXrefs() throws IOException
+  public void testMapProteinAlignmentToCdna_withXrefs() throws IOException
   {
     List<SequenceI> protseqs = new ArrayList<SequenceI>();
     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
@@ -739,7 +739,7 @@ public class AlignmentUtilsTests
     // A11111 should be mapped to V12347
     // A55555 is spare and has no xref so is not mapped
 
-    assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
+    assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
 
     // 4 protein mappings made for 3 proteins, 2 to V12345, 1 each to V12346/7
     assertEquals(3, protein.getCodonFrames().size());
@@ -786,7 +786,8 @@ public class AlignmentUtilsTests
    * @throws IOException
    */
   @Test(groups = { "Functional" })
-  public void testMapProteinToCdna_prioritiseXrefs() throws IOException
+  public void testMapProteinAlignmentToCdna_prioritiseXrefs()
+          throws IOException
   {
     List<SequenceI> protseqs = new ArrayList<SequenceI>();
     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
@@ -806,7 +807,7 @@ public class AlignmentUtilsTests
     // A11111 should then be mapped to the unmapped V12346
     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
 
-    assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
+    assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
 
     // 2 protein mappings made
     assertEquals(2, protein.getCodonFrames().size());
@@ -1279,4 +1280,27 @@ public class AlignmentUtilsTests
     assertTrue(AlignmentUtils.isMappable(al1, al2));
     assertTrue(AlignmentUtils.isMappable(al2, al1));
   }
+
+  /**
+   * Test creating a mapping when the sequences involved do not start at residue
+   * 1
+   * 
+   * @throws IOException
+   */
+  @Test(groups = { "Functional" })
+  public void testMapProteinSequenceToCdna_forSubsequence()
+          throws IOException
+  {
+    SequenceI prot = new Sequence("UNIPROT|V12345", "E-I--Q", 10, 12);
+    prot.createDatasetSequence();
+
+    SequenceI dna = new Sequence("EMBL|A33333", "GAA--AT-C-CAG", 40, 48);
+    dna.createDatasetSequence();
+
+    MapList map = AlignmentUtils.mapProteinSequenceToCdna(prot, dna);
+    assertEquals(10, map.getToLowest());
+    assertEquals(12, map.getToHighest());
+    assertEquals(40, map.getFromLowest());
+    assertEquals(48, map.getFromHighest());
+  }
 }
diff --git a/test/jalview/bin/JalviewLiteTest.java b/test/jalview/bin/JalviewLiteTest.java
new file mode 100644 (file)
index 0000000..047aae8
--- /dev/null
@@ -0,0 +1,39 @@
+package jalview.bin;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+
+import java.util.Arrays;
+
+import org.testng.annotations.Test;
+
+
+public class JalviewLiteTest
+{
+
+  @Test(groups = "Functional")
+  public void testSeparatorListToArray()
+  {
+    assertNull(JalviewLite.separatorListToArray(null, "|"));
+    assertNull(JalviewLite.separatorListToArray("", "|"));
+    assertNull(JalviewLite.separatorListToArray("|", "|"));
+    assertNull(JalviewLite.separatorListToArray("abc", "abc"));
+
+    String [] array = JalviewLite.separatorListToArray("abc|def|ghi|", "|");
+    assertEquals(3, array.length);
+    assertEquals("abc", array[0]);
+    assertEquals("def", array[1]);
+    assertEquals("ghi", array[2]);
+
+    assertEquals("[abc]",
+            Arrays.toString(JalviewLite.separatorListToArray("abc|", "|")));
+    assertEquals("[abc]", Arrays.toString(JalviewLite.separatorListToArray(
+            "abcxy", "xy")));
+
+    // these fail:
+    // assertEquals("[abc]",
+    // Arrays.toString(JalviewLite.separatorListToArray("|abc", "|")));
+    // assertEquals("[abc]", Arrays.toString(JalviewLite.separatorListToArray(
+    // "abc|||", "|")));
+  }
+}
index 69379d0..9afae37 100644 (file)
@@ -105,7 +105,7 @@ public class EditCommandTest
   public void testCut()
   {
     Edit ec = testee.new Edit(Action.CUT, seqs, 4, 3, al);
-    testee.cut(ec, new AlignmentI[] { al });
+    EditCommand.cut(ec, new AlignmentI[] { al });
     assertEquals("abcdhjk", seqs[0].getSequenceAsString());
     assertEquals("fghjnopq", seqs[1].getSequenceAsString());
     assertEquals("qrstxyz", seqs[2].getSequenceAsString());
@@ -130,7 +130,7 @@ public class EditCommandTest
     newSeqs[1] = new Sequence("newseq1", "JWMPDH");
 
     Edit ec = testee.new Edit(Action.PASTE, newSeqs, 0, al.getWidth(), al);
-    testee.paste(ec, new AlignmentI[] { al });
+    EditCommand.paste(ec, new AlignmentI[] { al });
     assertEquals(6, al.getSequences().size());
     assertEquals("1234567890", seqs[3].getSequenceAsString());
     assertEquals("ACEFKL", seqs[4].getSequenceAsString());
@@ -423,12 +423,12 @@ public class EditCommandTest
     SequenceI seq = new Sequence("", "--A--B-CDEF");
     SequenceI ds = new Sequence("", "ABCDEF");
     seq.setDatasetSequence(ds);
-    SequenceI[] seqs = new SequenceI[] { seq };
-    Edit e = command.new Edit(Action.INSERT_GAP, seqs, 1, 2, '-');
+    SequenceI[] sqs = new SequenceI[] { seq };
+    Edit e = command.new Edit(Action.INSERT_GAP, sqs, 1, 2, '-');
     command.addEdit(e);
-    e = command.new Edit(Action.INSERT_GAP, seqs, 4, 1, '-');
+    e = command.new Edit(Action.INSERT_GAP, sqs, 4, 1, '-');
     command.addEdit(e);
-    e = command.new Edit(Action.INSERT_GAP, seqs, 0, 2, '-');
+    e = command.new Edit(Action.INSERT_GAP, sqs, 0, 2, '-');
     command.addEdit(e);
 
     Map<SequenceI, SequenceI> unwound = command.priorState(false);
@@ -450,10 +450,10 @@ public class EditCommandTest
     SequenceI seq = new Sequence("", "ABC");
     SequenceI ds = new Sequence("", "ABC");
     seq.setDatasetSequence(ds);
-    SequenceI[] seqs = new SequenceI[] { seq };
-    Edit e = command.new Edit(Action.DELETE_GAP, seqs, 1, 1, '-');
+    SequenceI[] sqs = new SequenceI[] { seq };
+    Edit e = command.new Edit(Action.DELETE_GAP, sqs, 1, 1, '-');
     command.addEdit(e);
-    e = command.new Edit(Action.DELETE_GAP, seqs, 2, 1, '-');
+    e = command.new Edit(Action.DELETE_GAP, sqs, 2, 1, '-');
     command.addEdit(e);
 
     Map<SequenceI, SequenceI> unwound = command.priorState(false);
@@ -470,8 +470,8 @@ public class EditCommandTest
     SequenceI seq = new Sequence("", "ABCDEF");
     SequenceI ds = new Sequence("", "ABCDEF");
     seq.setDatasetSequence(ds);
-    SequenceI[] seqs = new SequenceI[] { seq };
-    Edit e = command.new Edit(Action.DELETE_GAP, seqs, 2, 2, '-');
+    SequenceI[] sqs = new SequenceI[] { seq };
+    Edit e = command.new Edit(Action.DELETE_GAP, sqs, 2, 2, '-');
     command.addEdit(e);
 
     Map<SequenceI, SequenceI> unwound = command.priorState(false);
@@ -488,12 +488,38 @@ public class EditCommandTest
     SequenceI seq = new Sequence("", "AB---CDEF");
     SequenceI ds = new Sequence("", "ABCDEF");
     seq.setDatasetSequence(ds);
-    SequenceI[] seqs = new SequenceI[] { seq };
-    Edit e = command.new Edit(Action.INSERT_GAP, seqs, 2, 3, '-');
+    SequenceI[] sqs = new SequenceI[] { seq };
+    Edit e = command.new Edit(Action.INSERT_GAP, sqs, 2, 3, '-');
     command.addEdit(e);
 
     Map<SequenceI, SequenceI> unwound = command.priorState(false);
-    assertEquals("ABCDEF", unwound.get(ds).getSequenceAsString());
+    SequenceI prior = unwound.get(ds);
+    assertEquals("ABCDEF", prior.getSequenceAsString());
+    assertEquals(1, prior.getStart());
+    assertEquals(6, prior.getEnd());
+  }
+
+  /**
+   * Test 'undoing' a single gap insertion edit command, on a sequence whose
+   * start residue is other than 1
+   */
+  @Test(groups = { "Functional" })
+  public void testPriorState_singleInsertWithOffset()
+  {
+    EditCommand command = new EditCommand();
+    SequenceI seq = new Sequence("", "AB---CDEF", 8, 13);
+    // SequenceI ds = new Sequence("", "ABCDEF", 8, 13);
+    // seq.setDatasetSequence(ds);
+    seq.createDatasetSequence();
+    SequenceI[] sqs = new SequenceI[] { seq };
+    Edit e = command.new Edit(Action.INSERT_GAP, sqs, 2, 3, '-');
+    command.addEdit(e);
+
+    Map<SequenceI, SequenceI> unwound = command.priorState(false);
+    SequenceI prior = unwound.get(seq.getDatasetSequence());
+    assertEquals("ABCDEF", prior.getSequenceAsString());
+    assertEquals(8, prior.getStart());
+    assertEquals(13, prior.getEnd());
   }
 
   /**
@@ -514,13 +540,13 @@ public class EditCommandTest
     SequenceI seq = new Sequence("", "ABC-DEF");
     SequenceI ds1 = new Sequence("", "ABCDEF");
     seq.setDatasetSequence(ds1);
-    SequenceI[] seqs = new SequenceI[] { seq };
-    Edit e = command.new Edit(Action.DELETE_GAP, seqs, 0, 2, '-');
+    SequenceI[] sqs = new SequenceI[] { seq };
+    Edit e = command.new Edit(Action.DELETE_GAP, sqs, 0, 2, '-');
     command.addEdit(e);
     seq = new Sequence("", "ABCDEF");
     seq.setDatasetSequence(ds1);
-    seqs = new SequenceI[] { seq };
-    e = command.new Edit(Action.DELETE_GAP, seqs, 3, 1, '-');
+    sqs = new SequenceI[] { seq };
+    e = command.new Edit(Action.DELETE_GAP, sqs, 3, 1, '-');
     command.addEdit(e);
 
     /*
@@ -529,13 +555,13 @@ public class EditCommandTest
     seq = new Sequence("", "FGHI--J");
     SequenceI ds2 = new Sequence("", "FGHIJ");
     seq.setDatasetSequence(ds2);
-    seqs = new SequenceI[] { seq };
-    e = command.new Edit(Action.DELETE_GAP, seqs, 2, 1, '-');
+    sqs = new SequenceI[] { seq };
+    e = command.new Edit(Action.DELETE_GAP, sqs, 2, 1, '-');
     command.addEdit(e);
     seq = new Sequence("", "FGHIJ");
     seq.setDatasetSequence(ds2);
-    seqs = new SequenceI[] { seq };
-    e = command.new Edit(Action.DELETE_GAP, seqs, 4, 2, '-');
+    sqs = new SequenceI[] { seq };
+    e = command.new Edit(Action.DELETE_GAP, sqs, 4, 2, '-');
     command.addEdit(e);
 
     /*
@@ -544,8 +570,8 @@ public class EditCommandTest
     seq = new Sequence("", "MNOPQ");
     SequenceI ds3 = new Sequence("", "MNOPQ");
     seq.setDatasetSequence(ds3);
-    seqs = new SequenceI[] { seq };
-    e = command.new Edit(Action.DELETE_GAP, seqs, 1, 1, '-');
+    sqs = new SequenceI[] { seq };
+    e = command.new Edit(Action.DELETE_GAP, sqs, 1, 1, '-');
     command.addEdit(e);
 
     Map<SequenceI, SequenceI> unwound = command.priorState(false);
@@ -579,8 +605,8 @@ public class EditCommandTest
     SequenceI seq3 = new Sequence("", "M-NO--PQ");
     SequenceI ds3 = new Sequence("", "MNOPQ");
     seq3.setDatasetSequence(ds3);
-    SequenceI[] seqs = new SequenceI[] { seq1, seq2, seq3 };
-    Edit e = command.new Edit(Action.DELETE_GAP, seqs, 0, 1, '-');
+    SequenceI[] sqs = new SequenceI[] { seq1, seq2, seq3 };
+    Edit e = command.new Edit(Action.DELETE_GAP, sqs, 0, 1, '-');
     command.addEdit(e);
 
     /*
@@ -592,8 +618,8 @@ public class EditCommandTest
     seq2.setDatasetSequence(ds2);
     seq3 = new Sequence("", "M-NOPQ");
     seq3.setDatasetSequence(ds3);
-    seqs = new SequenceI[] { seq1, seq2, seq3 };
-    e = command.new Edit(Action.DELETE_GAP, seqs, 4, 2, '-');
+    sqs = new SequenceI[] { seq1, seq2, seq3 };
+    e = command.new Edit(Action.DELETE_GAP, sqs, 4, 2, '-');
     command.addEdit(e);
 
     Map<SequenceI, SequenceI> unwound = command.priorState(false);
index 9005656..a0757cc 100644 (file)
@@ -150,4 +150,30 @@ public class AlignedCodonFrameTest
     assertEquals("[C, T, T]", Arrays.toString(acf.getMappedCodon(
             aseq1.getDatasetSequence(), 2)));
   }
+
+  /**
+   * Test for the case where sequences have start > 1
+   */
+  @Test(groups = { "Functional" })
+  public void testGetMappedCodon_forSubSequences()
+  {
+    final Sequence seq1 = new Sequence("Seq1", "c-G-TA-gC-gT-T", 27, 35);
+    seq1.createDatasetSequence();
+
+    final Sequence aseq1 = new Sequence("Seq1", "-P-R", 12, 13);
+    aseq1.createDatasetSequence();
+
+    /*
+     * Set up the mappings for the exons (upper-case bases)
+     */
+    AlignedCodonFrame acf = new AlignedCodonFrame();
+    MapList map = new MapList(new int[] { 28, 30, 32, 32, 34, 35 },
+            new int[] { 12, 13 }, 3, 1);
+    acf.addMap(seq1.getDatasetSequence(), aseq1.getDatasetSequence(), map);
+
+    assertEquals("[G, T, A]", Arrays.toString(acf.getMappedCodon(
+            aseq1.getDatasetSequence(), 12)));
+    assertEquals("[C, T, T]", Arrays.toString(acf.getMappedCodon(
+            aseq1.getDatasetSequence(), 13)));
+  }
 }
index abb06ad..cc87f29 100644 (file)
@@ -150,4 +150,31 @@ public class AlignedCodonIteratorTest
     assertEquals("Q", codon.product);
     assertFalse(codons.hasNext());
   }
+
+  /**
+   * Test for a case with sequence (and mappings) not starting at 1
+   */
+  @Test(groups = { "Functional" })
+  public void testNext_withOffset()
+  {
+    SequenceI from = new Sequence("Seq1", "-CgC-C-cCtAG-AtG-Gc", 7, 20);
+    from.createDatasetSequence();
+    SequenceI to = new Sequence("Seq1/10-12", "-PQ-R-");
+    to.createDatasetSequence();
+    MapList map = new MapList(new int[] { 7, 7, 9, 10, 12, 12, 14, 16, 18,
+        19 }, new int[] { 10, 12 }, 3, 1);
+    Mapping m = new Mapping(to.getDatasetSequence(), map);
+
+    Iterator<AlignedCodon> codons = m.getCodonIterator(from, '-');
+    AlignedCodon codon = codons.next();
+    assertEquals("[1, 3, 5]", codon.toString());
+    assertEquals("P", codon.product);
+    codon = codons.next();
+    assertEquals("[8, 10, 11]", codon.toString());
+    assertEquals("Q", codon.product);
+    codon = codons.next();
+    assertEquals("[13, 15, 17]", codon.toString());
+    assertEquals("R", codon.product);
+    assertFalse(codons.hasNext());
+  }
 }
index f64a652..8abc03e 100644 (file)
@@ -57,21 +57,21 @@ public class AlignmentTest
           "//";
 
   private static final String AA_SEQS_1 = 
-          ">Seq1Name\n" +
+          ">Seq1Name/5-8\n" +
           "K-QY--L\n" +
-          ">Seq2Name\n" +
+          ">Seq2Name/12-15\n" +
           "-R-FP-W-\n";
 
   private static final String CDNA_SEQS_1 = 
-          ">Seq1Name\n" +
+          ">Seq1Name/100-111\n" +
           "AC-GG--CUC-CAA-CT\n" +
-          ">Seq2Name\n" +
+          ">Seq2Name/200-211\n" +
           "-CG-TTA--ACG---AAGT\n";
 
   private static final String CDNA_SEQS_2 = 
-          ">Seq1Name\n" +
+          ">Seq1Name/50-61\n" +
           "GCTCGUCGTACT\n" +
-          ">Seq2Name\n" +
+          ">Seq2Name/60-71\n" +
           "GGGTCAGGCAGT\n";
   // @formatter:on
 
@@ -176,11 +176,7 @@ public class AlignmentTest
      * Make mappings between sequences. The 'aligned cDNA' is playing the role
      * of what would normally be protein here.
      */
-    AlignedCodonFrame acf = new AlignedCodonFrame();
-    MapList ml = new MapList(new int[] { 1, 12 }, new int[] { 1, 12 }, 1, 1);
-    acf.addMap(al2.getSequenceAt(0), al1.getSequenceAt(0), ml);
-    acf.addMap(al2.getSequenceAt(1), al1.getSequenceAt(1), ml);
-    al1.addCodonFrame(acf);
+    makeMappings(al2, al1);
 
     ((Alignment) al2).alignAs(al1, false, true);
     assertEquals("GC-TC--GUC-GTA-CT", al2.getSequenceAt(0)
@@ -200,11 +196,7 @@ public class AlignmentTest
     // see also AlignmentUtilsTests
     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
-    AlignedCodonFrame acf = new AlignedCodonFrame();
-    MapList ml = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
-    acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml);
-    acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml);
-    al2.addCodonFrame(acf);
+    makeMappings(al1, al2);
 
     ((Alignment) al2).alignAs(al1, false, true);
     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
@@ -212,6 +204,27 @@ public class AlignmentTest
   }
 
   /**
+   * Aligning protein from cDNA for a single sequence. This is the 'simple' case
+   * (as there is no need to compute codon 'alignments') but worth testing
+   * before tackling the multiple sequence case.
+   * 
+   * @throws IOException
+   */
+  @Test(groups = { "Functional" })
+  public void testAlignAs_proteinAsCdna_singleSequence() throws IOException
+  {
+    /*
+     * simplest case remove all gaps
+     */
+    verifyAlignAs(">protein\n-Q-K-\n", ">dna\nCAAaaa\n", "QK");
+
+    /*
+     * with sequence offsets
+     */
+    verifyAlignAs(">protein/12-13\n-Q-K-\n", ">dna/20-25\nCAAaaa\n", "QK");
+  }
+
+  /**
    * Test aligning cdna as per protein alignment.
    * 
    * @throws IOException
@@ -224,11 +237,7 @@ public class AlignmentTest
      */
     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
-    AlignedCodonFrame acf = new AlignedCodonFrame();
-    MapList ml = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
-    acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml);
-    acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml);
-    al2.addCodonFrame(acf);
+    makeMappings(al1, al2);
 
     /*
      * Realign DNA; currently keeping existing gaps in introns only
@@ -241,6 +250,88 @@ public class AlignmentTest
   }
 
   /**
+   * Test aligning cdna as per protein - single sequences
+   * 
+   * @throws IOException
+   */
+  @Test(groups = { "Functional" })
+  public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
+  {
+    /*
+     * simple case insert one gap
+     */
+    verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
+
+    /*
+     * simple case but with sequence offsets
+     */
+    verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
+            "CAA---aaa");
+
+    /*
+     * insert gaps as per protein, drop gaps within codons
+     */
+    verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
+            "---CAA---aaa------AGA");
+  }
+
+  /**
+   * Helper method that makes mappings and then aligns the first alignment as
+   * the second
+   * 
+   * @param fromSeqs
+   * @param toSeqs
+   * @param expected
+   * @throws IOException
+   */
+  public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
+          throws IOException
+  {
+    /*
+     * Load alignments and add mappings from nucleotide to protein (or from
+     * first to second if both the same type)
+     */
+    AlignmentI al1 = loadAlignment(fromSeqs, "FASTA");
+    AlignmentI al2 = loadAlignment(toSeqs, "FASTA");
+    makeMappings(al1, al2);
+
+    /*
+     * Realign DNA; currently keeping existing gaps in introns only
+     */
+    ((Alignment) al1).alignAs(al2, false, true);
+    assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
+  }
+
+  /**
+   * Helper method to make mappings from protein to dna sequences, and add the
+   * mappings to the protein alignment
+   * 
+   * @param alFrom
+   * @param alTo
+   */
+  public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
+  {
+    AlignmentI prot = !alFrom.isNucleotide() ? alFrom : alTo;
+    AlignmentI nuc = alFrom == prot ? alTo : alFrom;
+
+    int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
+
+    AlignedCodonFrame acf = new AlignedCodonFrame();
+
+    for (int i = 0; i < nuc.getHeight(); i++)
+    {
+      SequenceI seqFrom = nuc.getSequenceAt(i);
+      SequenceI seqTo = prot.getSequenceAt(i);
+      MapList ml = new MapList(new int[] { seqFrom.getStart(),
+          seqFrom.getEnd() },
+              new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
+      acf.addMap(seqFrom, seqTo, ml);
+    }
+
+    prot.addCodonFrame(acf);
+  }
+
+  /**
    * Test aligning dna as per protein alignment, for the case where there are
    * introns (i.e. some dna sites have no mapping from a peptide).
    * 
@@ -254,18 +345,19 @@ public class AlignmentTest
      */
     String dna1 = "A-Aa-gG-GCC-cT-TT";
     String dna2 = "c--CCGgg-TT--T-AA-A";
-    AlignmentI al1 = loadAlignment(">Seq1\n" + dna1 + "\n>Seq2\n" + dna2
-            + "\n", "FASTA");
-    AlignmentI al2 = loadAlignment(">Seq1\n-P--YK\n>Seq2\nG-T--F\n",
-            "FASTA");
+    AlignmentI al1 = loadAlignment(">Seq1/6-17\n" + dna1
+            + "\n>Seq2/20-31\n" + dna2 + "\n", "FASTA");
+    AlignmentI al2 = loadAlignment(
+            ">Seq1/7-9\n-P--YK\n>Seq2/11-13\nG-T--F\n", "FASTA");
     AlignedCodonFrame acf = new AlignedCodonFrame();
     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
-    MapList ml1 = new MapList(new int[] { 1, 2, 5, 8, 10, 12 }, new int[] {
-        1, 3 }, 3, 1);
+    // TODO sequence offsets
+    MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
+    { 7, 9 }, 3, 1);
     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
-    MapList ml2 = new MapList(new int[] { 2, 4, 7, 12 },
-            new int[] { 1, 3 }, 3, 1);
+    MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
+        13 }, 3, 1);
     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
     al2.addCodonFrame(acf);
 
index ad7193a..fbf021b 100644 (file)
@@ -25,7 +25,11 @@ import static org.testng.AssertJUnit.assertSame;
 import static org.testng.AssertJUnit.assertTrue;
 
 import jalview.api.AlignViewportI;
+import jalview.commands.EditCommand;
+import jalview.commands.EditCommand.Action;
+import jalview.commands.EditCommand.Edit;
 import jalview.datamodel.AlignedCodonFrame;
+import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.ColumnSelection;
 import jalview.datamodel.SearchResults;
@@ -42,6 +46,7 @@ import java.io.IOException;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
 
@@ -59,46 +64,47 @@ public class MappingUtilsTest
   @Test(groups = { "Functional" })
   public void testBuildSearchResults()
   {
-    final Sequence seq1 = new Sequence("Seq1", "C-G-TA-GC");
+    final Sequence seq1 = new Sequence("Seq1/5-10", "C-G-TA-GC");
     seq1.createDatasetSequence();
 
-    final Sequence aseq1 = new Sequence("Seq1", "-P-R");
+    final Sequence aseq1 = new Sequence("Seq1/12-13", "-P-R");
     aseq1.createDatasetSequence();
 
     /*
-     * Map dna bases 1-6 to protein residues 1-2
+     * Map dna bases 5-10 to protein residues 12-13
      */
     AlignedCodonFrame acf = new AlignedCodonFrame();
-    MapList map = new MapList(new int[] { 1, 6 }, new int[] { 1, 2 }, 3, 1);
+    MapList map = new MapList(new int[] { 5, 10 }, new int[] { 12, 13 }, 3,
+            1);
     acf.addMap(seq1.getDatasetSequence(), aseq1.getDatasetSequence(), map);
     Set<AlignedCodonFrame> acfList = Collections.singleton(acf);
 
     /*
-     * Check protein residue 1 maps to codon 1-3, 2 to codon 4-6
+     * Check protein residue 12 maps to codon 5-7, 13 to codon 8-10
      */
-    SearchResults sr = MappingUtils.buildSearchResults(aseq1, 1, acfList);
+    SearchResults sr = MappingUtils.buildSearchResults(aseq1, 12, acfList);
     assertEquals(1, sr.getResults().size());
     Match m = sr.getResults().get(0);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(1, m.getStart());
-    assertEquals(3, m.getEnd());
-    sr = MappingUtils.buildSearchResults(aseq1, 2, acfList);
+    assertEquals(5, m.getStart());
+    assertEquals(7, m.getEnd());
+    sr = MappingUtils.buildSearchResults(aseq1, 13, acfList);
     assertEquals(1, sr.getResults().size());
     m = sr.getResults().get(0);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(4, m.getStart());
-    assertEquals(6, m.getEnd());
+    assertEquals(8, m.getStart());
+    assertEquals(10, m.getEnd());
 
     /*
-     * Check inverse mappings, from codons 1-3, 4-6 to protein 1, 2
+     * Check inverse mappings, from codons 5-7, 8-10 to protein 12, 13
      */
-    for (int i = 1; i < 7; i++)
+    for (int i = 5; i < 11; i++)
     {
       sr = MappingUtils.buildSearchResults(seq1, i, acfList);
       assertEquals(1, sr.getResults().size());
       m = sr.getResults().get(0);
       assertEquals(aseq1.getDatasetSequence(), m.getSequence());
-      int residue = i > 3 ? 2 : 1;
+      int residue = i > 7 ? 13 : 12;
       assertEquals(residue, m.getStart());
       assertEquals(residue, m.getEnd());
     }
@@ -110,61 +116,61 @@ public class MappingUtilsTest
   @Test(groups = { "Functional" })
   public void testBuildSearchResults_withIntron()
   {
-    final Sequence seq1 = new Sequence("Seq1", "C-G-TAGA-GCAGCTT");
+    final Sequence seq1 = new Sequence("Seq1/5-17", "c-G-tAGa-GcAgCtt");
     seq1.createDatasetSequence();
 
-    final Sequence aseq1 = new Sequence("Seq1", "-P-R");
+    final Sequence aseq1 = new Sequence("Seq1/8-9", "-E-D");
     aseq1.createDatasetSequence();
 
     /*
-     * Map dna bases [2, 4, 5], [7, 9, 11] to protein residues 1 and 2
+     * Map dna bases [6, 8, 9], [11, 13, 115] to protein residues 8 and 9
      */
     AlignedCodonFrame acf = new AlignedCodonFrame();
-    MapList map = new MapList(new int[] { 2, 2, 4, 5, 7, 7, 9, 9, 11, 11 },
-            new int[] { 1, 2 }, 3, 1);
+    MapList map = new MapList(new int[] { 6, 6, 8, 9, 11, 11, 13, 13, 15,
+        15 }, new int[] { 8, 9 }, 3, 1);
     acf.addMap(seq1.getDatasetSequence(), aseq1.getDatasetSequence(), map);
     Set<AlignedCodonFrame> acfList = Collections.singleton(acf);
 
     /*
-     * Check protein residue 1 maps to [2, 4, 5]
+     * Check protein residue 8 maps to [6, 8, 9]
      */
-    SearchResults sr = MappingUtils.buildSearchResults(aseq1, 1, acfList);
+    SearchResults sr = MappingUtils.buildSearchResults(aseq1, 8, acfList);
     assertEquals(2, sr.getResults().size());
     Match m = sr.getResults().get(0);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(2, m.getStart());
-    assertEquals(2, m.getEnd());
+    assertEquals(6, m.getStart());
+    assertEquals(6, m.getEnd());
     m = sr.getResults().get(1);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(4, m.getStart());
-    assertEquals(5, m.getEnd());
+    assertEquals(8, m.getStart());
+    assertEquals(9, m.getEnd());
 
     /*
-     * Check protein residue 2 maps to [7, 9, 11]
+     * Check protein residue 9 maps to [11, 13, 15]
      */
-    sr = MappingUtils.buildSearchResults(aseq1, 2, acfList);
+    sr = MappingUtils.buildSearchResults(aseq1, 9, acfList);
     assertEquals(3, sr.getResults().size());
     m = sr.getResults().get(0);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(7, m.getStart());
-    assertEquals(7, m.getEnd());
+    assertEquals(11, m.getStart());
+    assertEquals(11, m.getEnd());
     m = sr.getResults().get(1);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(9, m.getStart());
-    assertEquals(9, m.getEnd());
+    assertEquals(13, m.getStart());
+    assertEquals(13, m.getEnd());
     m = sr.getResults().get(2);
     assertEquals(seq1.getDatasetSequence(), m.getSequence());
-    assertEquals(11, m.getStart());
-    assertEquals(11, m.getEnd());
+    assertEquals(15, m.getStart());
+    assertEquals(15, m.getEnd());
 
     /*
      * Check inverse mappings, from codons to protein
      */
-    for (int i = 1; i < 14; i++)
+    for (int i = 5; i < 18; i++)
     {
       sr = MappingUtils.buildSearchResults(seq1, i, acfList);
-      int residue = (i == 2 || i == 4 || i == 5) ? 1 : (i == 7 || i == 9
-              || i == 11 ? 2 : 0);
+      int residue = (i == 6 || i == 8 || i == 9) ? 8 : (i == 11 || i == 13
+              || i == 15 ? 9 : 0);
       if (residue == 0)
       {
         assertEquals(0, sr.getResults().size());
@@ -329,6 +335,9 @@ public class MappingUtilsTest
   }
 
   /**
+   * Set up mappings for tests from 3 dna to 3 protein sequences. Sequences have
+   * offset start positions for a more general test case.
+   * 
    * @throws IOException
    */
   protected void setupMappedAlignments() throws IOException
@@ -337,23 +346,32 @@ public class MappingUtilsTest
      * Set up dna and protein Seq1/2/3 with mappings (held on the protein
      * viewport). Lower case for introns.
      */
-    AlignmentI cdna = loadAlignment(">Seq1\nAC-GctGtC-T\n"
-            + ">Seq2\nTc-GA-G-T-Tc\n" + ">Seq3\nTtTT-AaCGg-\n", "FASTA");
+    AlignmentI cdna = loadAlignment(">Seq1/10-18\nAC-GctGtC-T\n"
+            + ">Seq2/20-27\nTc-GA-G-T-Tc\n" + ">Seq3/30-38\nTtTT-AaCGg-\n",
+            "FASTA");
     cdna.setDataset(null);
     AlignmentI protein = loadAlignment(
-            ">Seq1\n-K-P\n>Seq2\nL--Q\n>Seq3\nG--S\n", "FASTA");
+            ">Seq1/40-41\n-K-P\n>Seq2/50-51\nL--Q\n>Seq3/60-61\nG--S\n",
+            "FASTA");
     protein.setDataset(null);
+
+    // map first dna to first protein seq
     AlignedCodonFrame acf = new AlignedCodonFrame();
-    MapList map = new MapList(new int[] { 1, 3, 6, 6, 8, 9 }, new int[] {
-        1, 2 }, 3, 1);
+    MapList map = new MapList(new int[] { 10, 12, 15, 15, 17, 18 },
+            new int[] { 40, 41 }, 3, 1);
     acf.addMap(cdna.getSequenceAt(0).getDatasetSequence(), protein
             .getSequenceAt(0).getDatasetSequence(), map);
-    map = new MapList(new int[] { 1, 1, 3, 4, 5, 7 }, new int[] { 1, 2 },
+
+    // map second dna to second protein seq
+    map = new MapList(new int[] { 20, 20, 22, 23, 24, 26 }, new int[] { 50,
+        51 },
             3, 1);
     acf.addMap(cdna.getSequenceAt(1).getDatasetSequence(), protein
             .getSequenceAt(1).getDatasetSequence(), map);
-    map = new MapList(new int[] { 1, 1, 3, 4, 5, 5, 7, 8 }, new int[] { 1,
-        2 }, 3, 1);
+
+    // map third dna to third protein seq
+    map = new MapList(new int[] { 30, 30, 32, 34, 36, 37 }, new int[] { 60,
+        61 }, 3, 1);
     acf.addMap(cdna.getSequenceAt(2).getDatasetSequence(), protein
             .getSequenceAt(2).getDatasetSequence(), map);
     Set<AlignedCodonFrame> acfList = Collections.singleton(acf);
@@ -679,4 +697,44 @@ public class MappingUtilsTest
     result = MappingUtils.findMappingsForSequence(null, null);
     assertEquals(0, result.size());
   }
+
+  @Test(groups = { "Functional" })
+  public void testMapEditCommand()
+  {
+    SequenceI dna = new Sequence("Seq1", "---ACG---GCATCA", 8, 16);
+    SequenceI protein = new Sequence("Seq2", "-T-AS", 5, 7);
+    dna.createDatasetSequence();
+    protein.createDatasetSequence();
+    AlignedCodonFrame acf = new AlignedCodonFrame();
+    MapList map = new MapList(new int[] { 8, 16 }, new int[] { 5, 7 }, 3, 1);
+    acf.addMap(dna.getDatasetSequence(), protein.getDatasetSequence(), map);
+    Set<AlignedCodonFrame> mappings = new LinkedHashSet<AlignedCodonFrame>();
+    mappings.add(acf);
+
+    AlignmentI prot = new Alignment(new SequenceI[] { protein });
+    prot.setCodonFrames(mappings);
+    AlignmentI nuc = new Alignment(new SequenceI[] { dna });
+
+    /*
+     * construct and perform the edit command to turn "-T-AS" in to "-T-A--S"
+     * i.e. insert two gaps at column 4
+     */
+    EditCommand ec = new EditCommand();
+    final Edit edit = ec.new Edit(Action.INSERT_GAP,
+            new SequenceI[] { protein }, 4, 2, '-');
+    ec.appendEdit(edit, prot, true, null);
+
+    /*
+     * the mapped edit command should be to insert 6 gaps before base 4 in the
+     * nucleotide sequence, which corresponds to aligned column 12 in the dna
+     */
+    EditCommand mappedEdit = MappingUtils.mapEditCommand(ec, false, nuc,
+            '-', mappings);
+    assertEquals(1, mappedEdit.getEdits().size());
+    Edit e = mappedEdit.getEdits().get(0);
+    assertEquals(1, e.getSequences().length);
+    assertEquals(dna, e.getSequences()[0]);
+    assertEquals(12, e.getPosition());
+    assertEquals(6, e.getNumber());
+  }
 }