JAL-1622 fix bug computing superposition + associated refactorings
authorgmungoc <g.m.carstairs@dundee.ac.uk>
Fri, 5 Jun 2015 14:15:01 +0000 (15:15 +0100)
committergmungoc <g.m.carstairs@dundee.ac.uk>
Fri, 5 Jun 2015 14:15:01 +0000 (15:15 +0100)
src/jalview/ext/jmol/JalviewJmolBinding.java
src/jalview/ext/rbvi/chimera/JalviewChimeraBinding.java
src/jalview/gui/ChimeraViewFrame.java
src/jalview/gui/StructureChooser.java
src/jalview/gui/StructureViewer.java
src/jalview/structures/models/AAStructureBindingModel.java
test/jalview/ext/rbvi/chimera/JalviewChimeraView.java
test/jalview/structures/models/AAStructureBindingModelTest.java [new file with mode: 0644]

index deadbfc..cdd137b 100644 (file)
@@ -50,11 +50,10 @@ import jalview.datamodel.SequenceI;
 import jalview.io.AppletFormatAdapter;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ResidueProperties;
-import jalview.structure.StructureMapping;
+import jalview.structure.AtomSpec;
 import jalview.structure.StructureMappingcommandSet;
 import jalview.structure.StructureSelectionManager;
 import jalview.structures.models.AAStructureBindingModel;
-import jalview.util.MessageManager;
 
 public abstract class JalviewJmolBinding extends AAStructureBindingModel
         implements JmolStatusListener, JmolSelectionListener,
@@ -243,47 +242,31 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     { hiddenCols });
   }
 
+  /**
+   * Construct and send a command to align structures against a reference
+   * structure, based on one or more sequence alignments
+   * 
+   * @param _alignment
+   *          an array of alignments to process
+   * @param _refStructure
+   *          an array of corresponding reference structures (index into pdb
+   *          file array); if a negative value is passed, the first PDB file
+   *          mapped to an alignment sequence is used as the reference for
+   *          superposition
+   * @param _hiddenCols
+   *          an array of corresponding hidden columns for each alignment
+   */
   public void superposeStructures(AlignmentI[] _alignment,
           int[] _refStructure, ColumnSelection[] _hiddenCols)
   {
-    assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
-
     String[] files = getPdbFile();
-    // check to see if we are still waiting for Jmol files
-    long starttime = System.currentTimeMillis();
-    boolean waiting = true;
-    do
-    {
-      waiting = false;
-      for (String file : files)
-      {
-        try
-        {
-          // HACK - in Jalview 2.8 this call may not be threadsafe so we catch
-          // every possible exception
-          StructureMapping[] sm = getSsm().getMapping(file);
-          if (sm == null || sm.length == 0)
-          {
-            waiting = true;
-          }
-        } catch (Exception x)
-        {
-          waiting = true;
-        } catch (Error q)
-        {
-          waiting = true;
-        }
-      }
-      // we wait around for a reasonable time before we give up
-    } while (waiting
-            && System.currentTimeMillis() < (10000 + 1000 * files.length + starttime));
-    if (waiting)
+
+    if (!waitForFileLoad(files))
     {
-      System.err
-              .println("RUNTIME PROBLEM: Jmol seems to be taking a long time to process all the structures.");
       return;
     }
-    StringBuffer selectioncom = new StringBuffer();
+
+    StringBuilder selectioncom = new StringBuilder(256);
     // In principle - nSeconds specifies the speed of animation for each
     // superposition - but is seems to behave weirdly, so we don't specify it.
     String nSeconds = " ";
@@ -319,134 +302,78 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
                 + refStructure);
         refStructure = -1;
       }
-      if (refStructure < -1)
-      {
-        refStructure = -1;
-      }
-      StringBuffer command = new StringBuffer();
 
+      /*
+       * 'matched' array will hold 'true' for visible alignment columns where
+       * all sequences have a residue with a mapping to the PDB structure
+       */
       boolean matched[] = new boolean[alignment.getWidth()];
       for (int m = 0; m < matched.length; m++)
       {
-
         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
       }
 
-      int commonrpositions[][] = new int[files.length][alignment.getWidth()];
-      String isel[] = new String[files.length];
-      // reference structure - all others are superposed in it
-      String[] targetC = new String[files.length];
-      String[] chainNames = new String[files.length];
-      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+      SuperposeData[] structures = new SuperposeData[files.length];
+      for (int f = 0; f < files.length; f++)
       {
-        StructureMapping[] mapping = getSsm().getMapping(files[pdbfnum]);
-        // RACE CONDITION - getMapping only returns Jmol loaded filenames once
-        // Jmol callback has completed.
-        if (mapping == null || mapping.length < 1)
-        {
-          throw new Error(MessageManager.getString("error.implementation_error_jmol_getting_data"));
-        }
-        int lastPos = -1;
-        final int sequenceCountForPdbFile = getSequence()[pdbfnum].length;
-        for (int s = 0; s < sequenceCountForPdbFile; s++)
-        {
-          for (int sp, m = 0; m < mapping.length; m++)
-          {
-            if (mapping[m].getSequence() == getSequence()[pdbfnum][s]
-                    && (sp = alignment.findIndex(getSequence()[pdbfnum][s])) > -1)
-            {
-              if (refStructure == -1)
-              {
-                refStructure = pdbfnum;
-              }
-              SequenceI asp = alignment.getSequenceAt(sp);
-              for (int r = 0; r < matched.length; r++)
-              {
-                if (!matched[r])
-                {
-                  continue;
-                }
-                matched[r] = false; // assume this is not a good site
-                if (r >= asp.getLength())
-                {
-                  continue;
-                }
-
-                if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
-                {
-                  // no mapping to gaps in sequence
-                  continue;
-                }
-                int t = asp.findPosition(r); // sequence position
-                int apos = mapping[m].getAtomNum(t);
-                int pos = mapping[m].getPDBResNum(t);
-
-                if (pos < 1 || pos == lastPos)
-                {
-                  // can't align unmapped sequence
-                  continue;
-                }
-                matched[r] = true; // this is a good ite
-                lastPos = pos;
-                // just record this residue position
-                commonrpositions[pdbfnum][r] = pos;
-              }
-              // create model selection suffix
-              isel[pdbfnum] = "/" + (pdbfnum + 1) + ".1";
-              if (mapping[m].getChain() == null
-                      || mapping[m].getChain().trim().length() == 0)
-              {
-                targetC[pdbfnum] = "";
-              }
-              else
-              {
-                targetC[pdbfnum] = ":" + mapping[m].getChain();
-              }
-              chainNames[pdbfnum] = mapping[m].getPdbId()
-                      + targetC[pdbfnum];
-              // move on to next pdb file
-              s = getSequence()[pdbfnum].length;
-              break;
-            }
-          }
-        }
+        structures[f] = new SuperposeData(alignment.getWidth());
       }
 
-      // TODO: consider bailing if nmatched less than 4 because superposition
-      // not
-      // well defined.
-      // TODO: refactor superposable position search (above) from jmol selection
-      // construction (below)
+      /*
+       * Calculate the superposable alignment columns ('matched'), and the
+       * corresponding structure residue positions (structures.pdbResNo)
+       */
+      int candidateRefStructure = findSuperposableResidues(alignment,
+              matched, structures);
+      if (refStructure < 0)
+      {
+        /*
+         * If no reference structure was specified, pick the first one that has
+         * a mapping in the alignment
+         */
+        refStructure = candidateRefStructure;
+      }
 
       String[] selcom = new String[files.length];
       int nmatched = 0;
-      // generate select statements to select regions to superimpose structures
+      for (boolean b : matched)
+      {
+        if (b)
+        {
+          nmatched++;
+        }
+      }
+      if (nmatched < 4)
+      {
+        // TODO: bail out here because superposition illdefined?
+      }
+
+      /*
+       * generate select statements to select regions to superimpose structures
+       */
       {
         for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
         {
-          String chainCd = targetC[pdbfnum];
+          String chainCd = ":" + structures[pdbfnum].chain;
           int lpos = -1;
           boolean run = false;
-          StringBuffer molsel = new StringBuffer();
+          StringBuilder molsel = new StringBuilder();
           molsel.append("{");
           for (int r = 0; r < matched.length; r++)
           {
             if (matched[r])
             {
-              if (pdbfnum == 0)
-              {
-                nmatched++;
-              }
-              if (lpos != commonrpositions[pdbfnum][r] - 1)
+              int pdbResNo = structures[pdbfnum].pdbResNo[r];
+              if (lpos != pdbResNo - 1)
               {
                 // discontinuity
                 if (lpos != -1)
                 {
                   molsel.append(lpos);
                   molsel.append(chainCd);
-                  // molsel.append("} {");
                   molsel.append("|");
                 }
+                run = false;
               }
               else
               {
@@ -459,11 +386,12 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
                 }
                 run = true;
               }
-              lpos = commonrpositions[pdbfnum][r];
-              // molsel.append(lpos);
+              lpos = pdbResNo;
             }
           }
-          // add final selection phrase
+          /*
+           * add final selection phrase
+           */
           if (lpos != -1)
           {
             molsel.append(lpos);
@@ -490,6 +418,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
           }
         }
       }
+      StringBuilder command = new StringBuilder(256);
       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
       {
         if (pdbfnum == refStructure || selcom[pdbfnum] == null
@@ -499,23 +428,23 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
         }
         command.append("echo ");
         command.append("\"Superposing (");
-        command.append(chainNames[pdbfnum]);
+        command.append(structures[pdbfnum].pdbId);
         command.append(") against reference (");
-        command.append(chainNames[refStructure]);
+        command.append(structures[refStructure].pdbId);
         command.append(")\";\ncompare " + nSeconds);
         command.append("{");
-        command.append(1 + pdbfnum);
+        command.append(Integer.toString(1 + pdbfnum));
         command.append(".1} {");
-        command.append(1 + refStructure);
+        command.append(Integer.toString(1 + refStructure));
         // conformation=1 excludes alternate locations for CA (JAL-1757)
         command.append(".1} SUBSET {(*.CA | *.P) and conformation=1} ATOMS ");
 
-        // form the matched pair strings
-        String sep = "";
-        for (int s = 0; s < 2; s++)
-        {
-          command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
-        }
+        // for (int s = 0; s < 2; s++)
+        // {
+        // command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
+        // }
+        command.append(selcom[pdbfnum]);
+        command.append(selcom[refStructure]);
         command.append(" ROTATE TRANSLATE;\n");
       }
       if (selectioncom.length() > 0)
@@ -524,10 +453,11 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
         evalStateCommand("select *; cartoons off; backbone; select ("
                 + selectioncom.toString() + "); cartoons; ");
         // selcom.append("; ribbons; ");
+        String cmdString = command.toString();
         System.out
-                .println("Superimpose command(s):\n" + command.toString());
+.println("Superimpose command(s):\n" + cmdString);
 
-        evalStateCommand(command.toString());
+        evalStateCommand(cmdString);
       }
     }
     if (selectioncom.length() > 0)
@@ -703,6 +633,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
   // ////////////////////////////////
   // /StructureListener
+  @Override
   public synchronized String[] getPdbFile()
   {
     if (viewer == null)
@@ -786,6 +717,22 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     jmolpopup.show(x, y);
   }
 
+  /**
+   * Highlight zero, one or more atoms on the structure
+   */
+  @Override
+  public void highlightAtoms(List<AtomSpec> atoms)
+  {
+    if (atoms != null)
+    {
+      for (AtomSpec atom : atoms)
+      {
+        highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
+                atom.getChain(), atom.getPdbFile());
+      }
+    }
+  }
+
   // jmol/ssm only
   public void highlightAtom(int atomIndex, int pdbResNum, String chain,
           String pdbfile)
index 3c455c2..cee271a 100644 (file)
@@ -44,11 +44,9 @@ import jalview.httpserver.AbstractRequestHandler;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ResidueProperties;
 import jalview.structure.AtomSpec;
-import jalview.structure.StructureMapping;
 import jalview.structure.StructureMappingcommandSet;
 import jalview.structure.StructureSelectionManager;
 import jalview.structures.models.AAStructureBindingModel;
-import jalview.util.Comparison;
 import jalview.util.MessageManager;
 
 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
@@ -56,14 +54,15 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   // Chimera clause to exclude alternate locations in atom selection
   private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
 
+  private static final String COLOURING_CHIMERA = MessageManager
+          .getString("status.colouring_chimera");
+
   private static final boolean debug = false;
 
   private static final String PHOSPHORUS = "P";
 
   private static final String ALPHACARBON = "CA";
 
-  private StructureManager csm;
-
   /*
    * Object through which we talk to Chimera
    */
@@ -92,12 +91,6 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
    */
   private boolean finishedInit = false;
 
-  private List<String> atomsPicked = new ArrayList<String>();
-
-  private List<String> chainNames;
-
-  private Map<String, String> chainFile;
-
   public String fileLoadingError;
 
   /*
@@ -217,7 +210,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   {
     super(ssm, pdbentry, sequenceIs, chains, protocol);
     viewer = new ChimeraManager(
-            csm = new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
+            new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
   }
 
   /**
@@ -238,20 +231,6 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
-   * Constructor
-   * 
-   * @param ssm
-   * @param theViewer
-   */
-  public JalviewChimeraBinding(StructureSelectionManager ssm,
-          ChimeraManager theViewer)
-  {
-    super(ssm, null);
-    viewer = theViewer;
-    csm = viewer.getStructureManager();
-  }
-
-  /**
    * Construct a title string for the viewer window based on the data Jalview
    * knows about
    * 
@@ -264,34 +243,37 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
-   * prepare the view for a given set of models/chains. chainList contains
-   * strings of the form 'pdbfilename:Chaincode'
+   * Tells Chimera to display only the specified chains
    * 
    * @param toshow
-   *          list of chains to make visible
    */
-  public void centerViewer(List<String> toshow)
+  public void showChains(List<String> toshow)
   {
+    /*
+     * Construct a chimera command like
+     * 
+     * ~display #*;~ribbon #*;ribbon :.A,:.B
+     */
     StringBuilder cmd = new StringBuilder(64);
-    int mlength, p;
-    for (String lbl : toshow)
+    boolean first = true;
+    for (String chain : toshow)
     {
-      mlength = 0;
-      do
+      if (!first)
       {
-        p = mlength;
-        mlength = lbl.indexOf(":", p);
-      } while (p < mlength && mlength < (lbl.length() - 2));
-      // TODO: lookup each pdb id and recover proper model number for it.
-      cmd.append("#" + getModelNum(chainFile.get(lbl)) + "."
-              + lbl.substring(mlength + 1) + " or ");
-    }
-    if (cmd.length() > 0)
-    {
-      cmd.setLength(cmd.length() - 4);
+        cmd.append(",");
+      }
+      cmd.append(":.").append(chain);
+      first = false;
     }
-    String cmdstring = cmd.toString();
-    evalStateCommand("~display #*; ~ribbon #*; ribbon " + cmdstring, false);
+
+    /*
+     * could append ";focus" to this command to resize the display to fill the
+     * window, but it looks more helpful not to (easier to relate chains to the
+     * whole)
+     */
+    final String command = "~display #*; ~ribbon #*; ribbon "
+            + cmd.toString();
+    sendChimeraCommand(command, false);
   }
 
   /**
@@ -319,287 +301,182 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   public void colourByChain()
   {
     colourBySequence = false;
-    evalStateCommand("rainbow chain", false);
-  }
-
-  public void colourByCharge()
-  {
-    colourBySequence = false;
-    evalStateCommand(
-            "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS",
-            false);
-  }
-
-  /**
-   * superpose the structures associated with sequences in the alignment
-   * according to their corresponding positions.
-   */
-  public void superposeStructures(AlignmentI alignment)
-  {
-    superposeStructures(alignment, -1, null);
+    sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
   }
 
   /**
-   * superpose the structures associated with sequences in the alignment
-   * according to their corresponding positions. ded)
-   * 
-   * @param refStructure
-   *          - select which pdb file to use as reference (default is -1 - the
-   *          first structure in the alignment)
+   * Constructs and sends a Chimera command to colour by charge
+   * <ul>
+   * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
+   * <li>Lysine and Arginine (positive charge) blue</li>
+   * <li>Cysteine - yellow</li>
+   * <li>all others - white</li>
+   * </ul>
    */
-  public void superposeStructures(AlignmentI alignment, int refStructure)
+  public void colourByCharge()
   {
-    superposeStructures(alignment, refStructure, null);
+    colourBySequence = false;
+    String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
+    sendAsynchronousCommand(command, COLOURING_CHIMERA);
   }
 
   /**
-   * superpose the structures associated with sequences in the alignment
-   * according to their corresponding positions. ded)
+   * Construct and send a command to align structures against a reference
+   * structure, based on one or more sequence alignments
    * 
-   * @param refStructure
-   *          - select which pdb file to use as reference (default is -1 - the
-   *          first structure in the alignment)
-   * @param hiddenCols
-   *          TODO
+   * @param _alignment
+   *          an array of alignments to process
+   * @param _refStructure
+   *          an array of corresponding reference structures (index into pdb
+   *          file array); if a negative value is passed, the first PDB file
+   *          mapped to an alignment sequence is used as the reference for
+   *          superposition
+   * @param _hiddenCols
+   *          an array of corresponding hidden columns for each alignment
    */
-  public void superposeStructures(AlignmentI alignment, int refStructure,
-          ColumnSelection hiddenCols)
-  {
-    superposeStructures(new AlignmentI[]
-    { alignment }, new int[]
-    { refStructure }, new ColumnSelection[]
-    { hiddenCols });
-  }
-
   public void superposeStructures(AlignmentI[] _alignment,
           int[] _refStructure, ColumnSelection[] _hiddenCols)
   {
-    assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
-    StringBuilder allComs = new StringBuilder(128); // Chimera superposition cmd
+    StringBuilder allComs = new StringBuilder(128);
     String[] files = getPdbFile();
-    // check to see if we are still waiting for Chimera files
-    long starttime = System.currentTimeMillis();
-    boolean waiting = true;
-    do
-    {
-      waiting = false;
-      for (String file : files)
-      {
-        try
-        {
-          // HACK - in Jalview 2.8 this call may not be threadsafe so we catch
-          // every possible exception
-          StructureMapping[] sm = getSsm().getMapping(file);
-          if (sm == null || sm.length == 0)
-          {
-            waiting = true;
-          }
-        } catch (Exception x)
-        {
-          waiting = true;
-        } catch (Error q)
-        {
-          waiting = true;
-        }
-      }
-      // we wait around for a reasonable time before we give up
-    } while (waiting
-            && System.currentTimeMillis() < (10000 + 1000 * files.length + starttime));
-    if (waiting)
+
+    if (!waitForFileLoad(files))
     {
-      System.err
-              .println("RUNTIME PROBLEM: Chimera seems to be taking a long time to process all the structures.");
       return;
     }
+
     refreshPdbEntries();
-    StringBuffer selectioncom = new StringBuffer();
+    StringBuilder selectioncom = new StringBuilder(256);
     for (int a = 0; a < _alignment.length; a++)
     {
       int refStructure = _refStructure[a];
       AlignmentI alignment = _alignment[a];
       ColumnSelection hiddenCols = _hiddenCols[a];
-      if (a > 0
-              && selectioncom.length() > 0
-              && !selectioncom.substring(selectioncom.length() - 1).equals(
-                      " "))
-      {
-        selectioncom.append(" ");
-      }
-      // process this alignment
+
       if (refStructure >= files.length)
       {
-        System.err.println("Invalid reference structure value "
+        System.err.println("Ignoring invalid reference structure value "
                 + refStructure);
         refStructure = -1;
       }
-      if (refStructure < -1)
-      {
-        refStructure = -1;
-      }
 
+      /*
+       * 'matched' array will hold 'true' for visible alignment columns where
+       * all sequences have a residue with a mapping to the PDB structure
+       */
       boolean matched[] = new boolean[alignment.getWidth()];
       for (int m = 0; m < matched.length; m++)
       {
-
         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
       }
 
-      int commonrpositions[][] = new int[files.length][alignment.getWidth()];
-      String isel[] = new String[files.length];
-      String[] targetC = new String[files.length];
-      String[] chainNames = new String[files.length];
-      String[] atomSpec = new String[files.length];
-      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+      SuperposeData[] structures = new SuperposeData[files.length];
+      for (int f = 0; f < files.length; f++)
       {
-        StructureMapping[] mapping = getSsm().getMapping(files[pdbfnum]);
-        // RACE CONDITION - getMapping only returns Jmol loaded filenames once
-        // Jmol callback has completed.
-        if (mapping == null || mapping.length < 1)
-        {
-          throw new Error(MessageManager.getString("error.implementation_error_chimera_getting_data"));
-        }
-        int lastPos = -1;
-        final int seqCountForPdbFile = getSequence()[pdbfnum].length;
-        for (int s = 0; s < seqCountForPdbFile; s++)
+        structures[f] = new SuperposeData(alignment.getWidth());
+      }
+
+      /*
+       * Calculate the superposable alignment columns ('matched'), and the
+       * corresponding structure residue positions (structures.pdbResNo)
+       */
+      int candidateRefStructure = findSuperposableResidues(alignment,
+              matched, structures);
+      if (refStructure < 0)
+      {
+        /*
+         * If no reference structure was specified, pick the first one that has
+         * a mapping in the alignment
+         */
+        refStructure = candidateRefStructure;
+      }
+
+      int nmatched = 0;
+      for (boolean b : matched)
+      {
+        if (b)
         {
-          for (int sp, m = 0; m < mapping.length; m++)
-          {
-            final SequenceI theSequence = getSequence()[pdbfnum][s];
-            if (mapping[m].getSequence() == theSequence
-                    && (sp = alignment.findIndex(theSequence)) > -1)
-            {
-              if (refStructure == -1)
-              {
-                refStructure = pdbfnum;
-              }
-              SequenceI asp = alignment.getSequenceAt(sp);
-              for (int r = 0; r < matched.length; r++)
-              {
-                if (!matched[r])
-                {
-                  continue;
-                }
-                matched[r] = false; // assume this is not a good site
-                if (r >= asp.getLength())
-                {
-                  continue;
-                }
-
-                if (Comparison.isGap(asp.getCharAt(r)))
-                {
-                  // no mapping to gaps in sequence
-                  continue;
-                }
-                int t = asp.findPosition(r); // sequence position
-                int apos = mapping[m].getAtomNum(t);
-                int pos = mapping[m].getPDBResNum(t);
-
-                if (pos < 1 || pos == lastPos)
-                {
-                  // can't align unmapped sequence
-                  continue;
-                }
-                matched[r] = true; // this is a good ite
-                lastPos = pos;
-                // just record this residue position
-                commonrpositions[pdbfnum][r] = pos;
-              }
-              // create model selection suffix
-              isel[pdbfnum] = "#" + pdbfnum;
-              if (mapping[m].getChain() == null
-                      || mapping[m].getChain().trim().length() == 0)
-              {
-                targetC[pdbfnum] = "";
-              }
-              else
-              {
-                targetC[pdbfnum] = "." + mapping[m].getChain();
-              }
-              chainNames[pdbfnum] = mapping[m].getPdbId()
-                      + targetC[pdbfnum];
-              atomSpec[pdbfnum] = asp.getRNA() != null ? PHOSPHORUS : ALPHACARBON;
-              // move on to next pdb file
-              s = seqCountForPdbFile;
-              break;
-            }
-          }
+          nmatched++;
         }
       }
+      if (nmatched < 4)
+      {
+        // TODO: bail out here because superposition illdefined?
+      }
 
-      // TODO: consider bailing if nmatched less than 4 because superposition
-      // not
-      // well defined.
-      // TODO: refactor superposable position search (above) from jmol selection
-      // construction (below)
-
+      /*
+       * Generate select statements to select regions to superimpose structures
+       */
       String[] selcom = new String[files.length];
-      int nmatched = 0;
-      String sep = "";
-      // generate select statements to select regions to superimpose structures
+      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
       {
-        for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+        String chainCd = "." + structures[pdbfnum].chain;
+        int lpos = -1;
+        boolean run = false;
+        StringBuilder molsel = new StringBuilder();
+        for (int r = 0; r < matched.length; r++)
         {
-          String chainCd = targetC[pdbfnum];
-          int lpos = -1;
-          boolean run = false;
-          StringBuffer molsel = new StringBuffer();
-          for (int r = 0; r < matched.length; r++)
+          if (matched[r])
           {
-            if (matched[r])
+            int pdbResNum = structures[pdbfnum].pdbResNo[r];
+            if (lpos != pdbResNum - 1)
             {
-              if (pdbfnum == 0)
+              /*
+               * discontiguous - append last residue now
+               */
+              if (lpos != -1)
               {
-                nmatched++;
+                molsel.append(String.valueOf(lpos));
+                molsel.append(chainCd);
+                molsel.append(",");
               }
-              if (lpos != commonrpositions[pdbfnum][r] - 1)
-              {
-                // discontinuity
-                if (lpos != -1)
-                {
-                  molsel.append((run ? "" : ":") + lpos);
-                  molsel.append(chainCd);
-                  molsel.append(",");
-                }
-              }
-              else
-              {
-                // continuous run - and lpos >-1
-                if (!run)
-                {
-                  // at the beginning, so add dash
-                  molsel.append(":" + lpos);
-                  molsel.append("-");
-                }
-                run = true;
-              }
-              lpos = commonrpositions[pdbfnum][r];
-              // molsel.append(lpos);
+              run = false;
             }
-          }
-          // add final selection phrase
-          if (lpos != -1)
-          {
-            molsel.append((run ? "" : ":") + lpos);
-            molsel.append(chainCd);
-            // molsel.append("");
-          }
-          if (molsel.length() > 1)
-          {
-            selcom[pdbfnum] = molsel.toString();
-            selectioncom.append("#" + pdbfnum);
-            selectioncom.append(selcom[pdbfnum]);
-            selectioncom.append(" ");
-            if (pdbfnum < files.length - 1)
+            else
             {
-              selectioncom.append("| ");
+              /*
+               * extending a contiguous run
+               */
+              if (!run)
+              {
+                /*
+                 * start the range selection
+                 */
+                molsel.append(String.valueOf(lpos));
+                molsel.append("-");
+              }
+              run = true;
             }
+            lpos = pdbResNum;
           }
-          else
+        }
+
+        /*
+         * and terminate final selection
+         */
+        if (lpos != -1)
+        {
+          molsel.append(String.valueOf(lpos));
+          molsel.append(chainCd);
+        }
+        if (molsel.length() > 1)
+        {
+          selcom[pdbfnum] = molsel.toString();
+          selectioncom.append("#").append(String.valueOf(pdbfnum))
+                  .append(":");
+          selectioncom.append(selcom[pdbfnum]);
+          selectioncom.append(" ");
+          if (pdbfnum < files.length - 1)
           {
-            selcom[pdbfnum] = null;
+            selectioncom.append("| ");
           }
         }
+        else
+        {
+          selcom[pdbfnum] = null;
+        }
       }
+
       StringBuilder command = new StringBuilder(256);
       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
       {
@@ -615,22 +492,23 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
         /*
          * Form Chimera match command, from the 'new' structure to the
-         * 'reference' structure e.g. (residues 1-91, chain B/A, alphacarbons):
+         * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
          * 
-         * match #1:1-91.B@CA #0:1-91.A@CA
+         * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
          * 
          * @see
          * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
          */
-        command.append("match #" + pdbfnum /* +".1" */);
-        // TODO: handle sub-models
+        command.append("match ").append(getModelSpec(pdbfnum)).append(":");
         command.append(selcom[pdbfnum]);
-        command.append("@" + atomSpec[pdbfnum]);
-        // JAL-1757 exclude alternative CA locations
+        command.append("@").append(
+                structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
+        // JAL-1757 exclude alternate CA locations
         command.append(NO_ALTLOCS);
-        command.append(" #" + refStructure /* +".1" */);
+        command.append(" ").append(getModelSpec(refStructure)).append(":");
         command.append(selcom[refStructure]);
-        command.append("@" + atomSpec[refStructure]);
+        command.append("@").append(
+                structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
         command.append(NO_ALTLOCS);
       }
       if (selectioncom.length() > 0)
@@ -641,13 +519,14 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
           System.out.println("Superimpose command(s):\n"
                   + command.toString());
         }
-        allComs.append("~display all; chain @CA|P; ribbon "
-                + selectioncom.toString() + ";"+command.toString());
-        // selcom.append("; ribbons; ");
+        allComs.append("~display all; chain @CA|P; ribbon ")
+                .append(selectioncom.toString())
+                .append(";" + command.toString());
       }
     }
     if (selectioncom.length() > 0)
-    {// finally, mark all regions that were superposed.
+    {
+      // TODO: visually distinguish regions that were superposed
       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
       {
         selectioncom.setLength(selectioncom.length() - 1);
@@ -656,24 +535,63 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
       {
         System.out.println("Select regions:\n" + selectioncom.toString());
       }
-      allComs.append("; ~display all; chain @CA|P; ribbon "
-              + selectioncom.toString() + "; focus");
-      // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
-      evalStateCommand(allComs.toString(), true /* false */);
+      allComs.append("; ~display all; chain @CA|P; ribbon ")
+              .append(selectioncom.toString()).append("; focus");
+      sendChimeraCommand(allComs.toString(), false);
     }
-    
+
   }
 
-  private void checkLaunched()
+  /**
+   * Helper method to construct model spec in Chimera format:
+   * <ul>
+   * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
+   * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
+   * <ul>
+   * Note for now we only ever choose the first of multiple models. This
+   * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
+   * future if there is a need to select specific sub-models.
+   * 
+   * @param pdbfnum
+   * @return
+   */
+  protected String getModelSpec(int pdbfnum)
   {
-    if (!viewer.isChimeraLaunched())
+    if (pdbfnum < 0 || pdbfnum >= getPdbCount())
     {
-      viewer.launchChimera(StructureManager.getChimeraPaths());
+      return "";
     }
+
+    /*
+     * For now, the test for having sub-models is whether multiple Chimera
+     * models are mapped for the PDB file; the models are returned as a response
+     * to the Chimera command 'list models type molecule', see
+     * ChimeraManager.getModelList().
+     */
+    List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
+    boolean hasSubModels = maps != null && maps.size() > 1;
+    return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
+  }
+
+  /**
+   * Launch Chimera, unless an instance linked to this object is already
+   * running. Returns true if chimera is successfully launched, or already
+   * running, else false.
+   * 
+   * @return
+   */
+  public boolean launchChimera()
+  {
     if (!viewer.isChimeraLaunched())
     {
-      log("Failed to launch Chimera!");
+      return viewer.launchChimera(StructureManager.getChimeraPaths());
     }
+    if (viewer.isChimeraLaunched())
+    {
+      return true;
+    }
+    log("Failed to launch Chimera!");
+    return false;
   }
 
   /**
@@ -688,21 +606,19 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
-   * Send a command to Chimera, launching it first if necessary, and optionally
-   * log any responses.
+   * Send a command to Chimera, and optionally log any responses.
    * 
    * @param command
    * @param logResponse
    */
-  public void evalStateCommand(final String command, boolean logResponse)
+  public void sendChimeraCommand(final String command, boolean logResponse)
   {
     viewerCommandHistory(false);
-    checkLaunched();
     if (lastCommand == null || !lastCommand.equals(command))
     {
       // trim command or it may never find a match in the replyLog!!
       lastReply = viewer.sendChimeraCommand(command.trim(), logResponse);
-      if (debug && logResponse)
+      if (logResponse && debug)
       {
         log("Response from command ('" + command + "') was:\n" + lastReply);
       }
@@ -712,6 +628,16 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
+   * Send a Chimera command asynchronously in a new thread. If the progress
+   * message is not null, display this message while the command is executing.
+   * 
+   * @param command
+   * @param progressMsg
+   */
+  protected abstract void sendAsynchronousCommand(String command,
+          String progressMsg);
+
+  /**
    * colour any structures associated with sequences in the given alignment
    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
    * if colourBySequence is enabled.
@@ -743,7 +669,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
     {
       for (String command : cpdbbyseq.commands)
       {
-        executeWhenReady(command);
+        sendAsynchronousCommand(command, COLOURING_CHIMERA);
       }
     }
   }
@@ -769,7 +695,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   protected void executeWhenReady(String command)
   {
     waitForChimera();
-    evalStateCommand(command, false);
+    sendChimeraCommand(command, false);
     waitForChimera();
   }
 
@@ -777,15 +703,15 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   {
     while (viewer != null && viewer.isBusy())
     {
-      try {
+      try
+      {
         Thread.sleep(15);
       } catch (InterruptedException q)
-      {}
+      {
+      }
     }
   }
 
-
-
   // End StructureListener
   // //////////////////////////
 
@@ -813,7 +739,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
   /**
    * instruct the Jalview binding to update the pdbentries vector if necessary
-   * prior to matching the jmol view's contents to the list of structure files
+   * prior to matching the viewer's contents to the list of structure files
    * Jalview knows about.
    */
   public abstract void refreshPdbEntries();
@@ -844,6 +770,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
   // ////////////////////////////////
   // /StructureListener
+  @Override
   public synchronized String[] getPdbFile()
   {
     if (viewer == null)
@@ -888,46 +815,63 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
           AlignmentViewPanel alignment);
 
   /**
-   * Construct and send a command to highlight an atom.
+   * Construct and send a command to highlight zero, one or more atoms.
    * 
    * <pre>
    * Done by generating a command like (to 'highlight' position 44)
-   *   ~show #0:43.C;show #0:44.C
-   * Note this removes the highlight from the previous position.
+   *   show #0:44.C
    * </pre>
    */
-  public void highlightAtom(int atomIndex, int pdbResNum, String chain,
-          String pdbfile)
+  @Override
+  public void highlightAtoms(List<AtomSpec> atoms)
   {
-    List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
-    if (cms != null)
+    if (atoms == null)
+    {
+      return;
+    }
+    StringBuilder atomSpecs = new StringBuilder();
+    boolean first = true;
+    for (AtomSpec atom : atoms)
     {
-      StringBuilder sb = new StringBuilder();
-      sb.append(" #" + cms.get(0).getModelNumber());
-      sb.append(":" + pdbResNum);
-      if (!chain.equals(" "))
+      int pdbResNum = atom.getPdbResNum();
+      String chain = atom.getChain();
+      String pdbfile = atom.getPdbFile();
+      List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
+      if (cms != null && !cms.isEmpty())
       {
-        sb.append("." + chain);
+        /*
+         * Formatting as #0:34.A,#1:33.A doesn't work as desired, so instead we
+         * concatenate multiple 'show' commands
+         */
+        atomSpecs.append(first ? "" : ";show ");
+        first = false;
+        atomSpecs.append("#" + cms.get(0).getModelNumber());
+        atomSpecs.append(":" + pdbResNum);
+        if (!chain.equals(" "))
+        {
+          atomSpecs.append("." + chain);
+        }
       }
-      String atomSpec = sb.toString();
+    }
+    String atomSpec = atomSpecs.toString();
 
-      StringBuilder command = new StringBuilder(32);
-      if (lastMousedOverAtomSpec != null)
-      {
-        command.append("~show " + lastMousedOverAtomSpec + ";");
-      }
-      viewerCommandHistory(false);
+    /*
+     * Avoid repeated commands for the same residue
+     */
+    if (atomSpec.equals(lastMousedOverAtomSpec))
+    {
+      return;
+    }
+
+    StringBuilder command = new StringBuilder(32);
+    viewerCommandHistory(false);
+    if (atomSpec.length() > 0)
+    {
       command.append("show ").append(atomSpec);
-      String cmd = command.toString();
-      if (cmd.length() > 0)
-      {
-        viewer.stopListening(chimeraListener.getUri());
-        viewer.sendChimeraCommand(cmd, false);
-        viewer.startListening(chimeraListener.getUri());
-      }
-      viewerCommandHistory(true);
-      this.lastMousedOverAtomSpec = atomSpec;
+      viewer.sendChimeraCommand(command.toString(), false);
     }
+    viewerCommandHistory(true);
+    this.lastMousedOverAtomSpec = atomSpec;
   }
 
   /**
@@ -952,26 +896,28 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
       {
         continue; // malformed
       }
-    
+
       int hashPos = atomSpec.indexOf("#");
       String modelSubmodel = atomSpec.substring(hashPos + 1, colonPos);
       int dotPos = modelSubmodel.indexOf(".");
       int modelId = 0;
-      try {
+      try
+      {
         modelId = Integer.valueOf(dotPos == -1 ? modelSubmodel
                 : modelSubmodel.substring(0, dotPos));
-      } catch (NumberFormatException e) {
+      } catch (NumberFormatException e)
+      {
         // ignore, default to model 0
       }
-    
+
       String residueChain = atomSpec.substring(colonPos + 1);
       dotPos = residueChain.indexOf(".");
       int pdbResNum = Integer.parseInt(dotPos == -1 ? residueChain
               : residueChain.substring(0, dotPos));
-    
+
       String chainId = dotPos == -1 ? "" : residueChain
               .substring(dotPos + 1);
-    
+
       /*
        * Work out the pdbfilename from the model number
        */
@@ -1037,7 +983,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
               / normalise + " ::" + res + ";");
     }
 
-    evalStateCommand(command.toString(),false);
+    sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
     viewerCommandHistory(true);
   }
 
@@ -1077,7 +1023,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   /**
    * Send the Chimera 'background solid <color>" command.
    * 
-   * @see https
+   * @see https 
    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
    *      .html
    * @param col
@@ -1086,8 +1032,8 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   {
     viewerCommandHistory(false);
     double normalise = 255D;
-    final String command = "background solid " + col.getRed() / normalise + ","
-            + col.getGreen() / normalise + "," + col.getBlue()
+    final String command = "background solid " + col.getRed() / normalise
+            + "," + col.getGreen() / normalise + "," + col.getBlue()
             / normalise + ";";
     viewer.sendChimeraCommand(command, false);
     viewerCommandHistory(true);
@@ -1128,7 +1074,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
    */
   public boolean openSession(String filepath)
   {
-    evalStateCommand("open " + filepath, true);
+    sendChimeraCommand("open " + filepath, true);
     // todo: test for failure - how?
     return true;
   }
@@ -1143,9 +1089,40 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
     this.finishedInit = finishedInit;
   }
 
+  /**
+   * Returns a list of chains mapped in this viewer. Note this list is not
+   * currently scoped per structure.
+   * 
+   * @return
+   */
   public List<String> getChainNames()
   {
-    return chainNames;
+    List<String> names = new ArrayList<String>();
+    String[][] allNames = getChains();
+    if (allNames != null)
+    {
+      for (String[] chainsForPdb : allNames)
+      {
+        if (chainsForPdb != null)
+        {
+          for (String chain : chainsForPdb)
+          {
+            if (chain != null && !names.contains(chain))
+            {
+              names.add(chain);
+            }
+          }
+        }
+      }
+    }
+    return names;
   }
 
+  /**
+   * Send a 'focus' command to Chimera to recentre the visible display
+   */
+  public void focusView()
+  {
+    sendChimeraCommand("focus", false);
+  }
 }
index 7d8d97c..1915936 100644 (file)
@@ -32,7 +32,9 @@ import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import java.util.Random;
+import java.util.Set;
 import java.util.Vector;
 
 import javax.swing.JCheckBoxMenuItem;
@@ -71,7 +73,7 @@ import jalview.util.Platform;
 import jalview.ws.dbsources.Pdb;
 
 /**
- * GUI elements for handlnig an external chimera display
+ * GUI elements for handling an external chimera display
  * 
  * @author jprocter
  *
@@ -151,6 +153,8 @@ public class ChimeraViewFrame extends StructureViewerBase
               }
             });
     viewMenu.add(seqColourBy);
+    viewMenu.add(fitToWindow);
+
     final ItemListener handler;
     JMenu alpanels = new ViewSelectionMenu(
             MessageManager.getString("label.superpose_with"), this,
@@ -204,110 +208,161 @@ public class ChimeraViewFrame extends StructureViewerBase
           String[] chains, final AlignmentPanel ap)
   {
     super();
-    progressBar = ap.alignFrame;
-    // ////////////////////////////////
-    // Is the pdb file already loaded?
+
+    /*
+     * is the pdb file already loaded?
+     */
+    String pdbId = pdbentry.getId();
     String alreadyMapped = ap.getStructureSelectionManager()
-            .alreadyMappedToFile(pdbentry.getId());
+            .alreadyMappedToFile(pdbId);
 
     if (alreadyMapped != null)
     {
-      int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
-              MessageManager.formatMessage(
-                      "label.pdb_entry_is_already_displayed", new Object[]
-                      { pdbentry.getId() }), MessageManager.formatMessage(
-                      "label.map_sequences_to_visible_window", new Object[]
-                      { pdbentry.getId() }),
-              JOptionPane.YES_NO_CANCEL_OPTION);
-
+      int option = chooseAddSequencesToViewer(pdbId);
       if (option == JOptionPane.CANCEL_OPTION)
       {
         return;
       }
       if (option == JOptionPane.YES_OPTION)
       {
-        // TODO : Fix multiple seq to one chain issue here.
-        ap.getStructureSelectionManager().setMapping(seq, chains,
-                alreadyMapped, AppletFormatAdapter.FILE);
-        if (ap.getSeqPanel().seqCanvas.fr != null)
-        {
-          ap.getSeqPanel().seqCanvas.fr.featuresAdded();
-          ap.paintAlignment(true);
-        }
-
-        // Now this ChimeraViewFrame is mapped to new sequences. We must add
-        // them to the existing array
-        JInternalFrame[] frames = Desktop.instance.getAllFrames();
-
-        for (JInternalFrame frame : frames)
-        {
-          if (frame instanceof ChimeraViewFrame)
-          {
-            final ChimeraViewFrame topView = ((ChimeraViewFrame) frame);
-            // JBPNOTE: this looks like a binding routine, rather than a gui
-            // routine
-            for (int pe = 0; pe < topView.jmb.getPdbCount(); pe++)
-            {
-              if (topView.jmb.getPdbEntry(pe).getFile()
-                      .equals(
-                      alreadyMapped))
-              {
-                topView.jmb.addSequence(pe, seq);
-                topView.addAlignmentPanel(ap);
-                // add it to the set used for colouring
-                topView.useAlignmentPanelForColourbyseq(ap);
-                topView.buildActionMenu();
-                ap.getStructureSelectionManager()
-                        .sequenceColoursChanged(ap);
-                break;
-              }
-            }
-          }
-        }
-
+        addSequenceMappingsToStructure(seq, chains, ap, alreadyMapped);
         return;
       }
     }
-    // /////////////////////////////////
-    // Check if there are other Chimera views involving this alignment
-    // and prompt user about adding this molecule to one of them
+
+    /*
+     * Check if there are other Chimera views involving this alignment and give
+     * user the option to add and align this molecule to one of them
+     */
     List<ChimeraViewFrame> existingViews = getChimeraWindowsFor(ap);
-    for (ChimeraViewFrame topView : existingViews)
+    for (ChimeraViewFrame view : existingViews)
     {
-      // TODO: highlight topView in view somehow
+      // TODO: highlight view somehow
       /*
        * JAL-1742 exclude view with this structure already mapped (don't offer
        * to align chain B to chain A of the same structure)
        */
-      if (topView.hasPdbId(pdbentry.getId()))
+      if (view.hasPdbId(pdbId))
       {
         continue;
       }
-      int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
-              MessageManager.formatMessage("label.add_pdbentry_to_view",
-                      new Object[]
-                      { pdbentry.getId(), topView.getTitle() }),
-              MessageManager
-                      .getString("label.align_to_existing_structure_view"),
-              JOptionPane.YES_NO_CANCEL_OPTION);
+      int option = chooseAlignStructureToViewer(pdbId, view);
       if (option == JOptionPane.CANCEL_OPTION)
       {
         return;
       }
       if (option == JOptionPane.YES_OPTION)
       {
-        topView.useAlignmentPanelForSuperposition(ap);
-        topView.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
+        view.useAlignmentPanelForSuperposition(ap);
+        view.addStructure(pdbentry, seq, chains, true, ap.alignFrame);
         return;
       }
     }
-    // /////////////////////////////////
+
+    /*
+     * If the options above are declined or do not apply, open a new viewer
+     */
     openNewChimera(ap, new PDBEntry[]
     { pdbentry }, new SequenceI[][]
     { seq });
   }
 
   /**
+   * Presents a dialog with the option to add an align a structure to an
+   * existing Chimera view
+   * 
+   * @param pdbId
+   * @param view
+   * @return YES, NO or CANCEL JOptionPane code
+   */
+  protected int chooseAlignStructureToViewer(String pdbId,
+          ChimeraViewFrame view)
+  {
+    int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
+            MessageManager.formatMessage("label.add_pdbentry_to_view",
+                    new Object[]
+                    { pdbId, view.getTitle() }), MessageManager
+                    .getString("label.align_to_existing_structure_view"),
+            JOptionPane.YES_NO_CANCEL_OPTION);
+    return option;
+  }
+
+  /**
+   * Presents a dialog with the option to add sequences to a viewer which
+   * already has their structure open
+   * 
+   * @param pdbId
+   * @return YES, NO or CANCEL JOptionPane code
+   */
+  protected int chooseAddSequencesToViewer(String pdbId)
+  {
+    int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
+            MessageManager.formatMessage(
+                    "label.pdb_entry_is_already_displayed", new Object[]
+                    { pdbId }), MessageManager.formatMessage(
+                    "label.map_sequences_to_visible_window", new Object[]
+                    { pdbId }), JOptionPane.YES_NO_CANCEL_OPTION);
+    return option;
+  }
+
+  /**
+   * Adds mappings for the given sequences to an already opened PDB structure,
+   * and updates any viewers that have the PDB file
+   * 
+   * @param seq
+   * @param chains
+   * @param ap
+   * @param pdbFilename
+   */
+  protected void addSequenceMappingsToStructure(SequenceI[] seq,
+          String[] chains, final AlignmentPanel ap, String pdbFilename)
+  {
+    // TODO : Fix multiple seq to one chain issue here.
+    /*
+     * create the mappings
+     */
+    ap.getStructureSelectionManager().setMapping(seq, chains, pdbFilename,
+            AppletFormatAdapter.FILE);
+
+    /*
+     * alert the FeatureRenderer to show new (PDB RESNUM) features
+     */
+    if (ap.getSeqPanel().seqCanvas.fr != null)
+    {
+      ap.getSeqPanel().seqCanvas.fr.featuresAdded();
+      ap.paintAlignment(true);
+    }
+
+    /*
+     * add the sequences to any other Chimera viewers for this pdb file
+     */
+    // JBPNOTE: this looks like a binding routine, rather than a gui routine
+    for (JInternalFrame frame : Desktop.instance.getAllFrames())
+    {
+      if (frame instanceof ChimeraViewFrame)
+      {
+        ChimeraViewFrame chimeraView = ((ChimeraViewFrame) frame);
+        for (int pe = 0; pe < chimeraView.jmb.getPdbCount(); pe++)
+        {
+          if (chimeraView.jmb.getPdbEntry(pe).getFile().equals(pdbFilename))
+          {
+            chimeraView.jmb.addSequence(pe, seq);
+            chimeraView.addAlignmentPanel(ap);
+            /*
+             * add it to the set of alignments used for colouring structure by
+             * sequence
+             */
+            chimeraView.useAlignmentPanelForColourbyseq(ap);
+            chimeraView.buildActionMenu();
+            ap.getStructureSelectionManager().sequenceColoursChanged(ap);
+            break;
+          }
+        }
+      }
+    }
+  }
+
+  /**
    * Create a helper to manage progress bar display
    */
   protected void createProgressBar()
@@ -327,7 +382,6 @@ public class ChimeraViewFrame extends StructureViewerBase
           SequenceI[][] seqs)
   {
     createProgressBar();
-
     String[][] chains = extractChains(seqs);
     jmb = new JalviewChimeraBindingModel(this,
             ap.getStructureSelectionManager(), pdbentrys, seqs, chains,
@@ -390,21 +444,6 @@ public class ChimeraViewFrame extends StructureViewerBase
   }
 
   /**
-   * create a new viewer containing several structures superimposed using the
-   * given alignPanel.
-   * 
-   * @param ap
-   * @param pe
-   * @param seqs
-   */
-  public ChimeraViewFrame(AlignmentPanel ap, PDBEntry[] pe,
-          SequenceI[][] seqs)
-  {
-    super();
-    openNewChimera(ap, pe, seqs);
-  }
-
-  /**
    * Create a new viewer from saved session state data including Chimera session
    * file.
    * 
@@ -439,6 +478,44 @@ public class ChimeraViewFrame extends StructureViewerBase
   }
 
   /**
+   * create a new viewer containing several structures superimposed using the
+   * given alignPanel.
+   * 
+   * @param pe
+   * @param seqs
+   * @param ap
+   */
+  public ChimeraViewFrame(PDBEntry[] pe, SequenceI[][] seqs,
+          AlignmentPanel ap)
+  {
+    super();
+    openNewChimera(ap, pe, seqs);
+  }
+
+  public ChimeraViewFrame(Map<PDBEntry, List<SequenceI>> toView,
+          AlignmentPanel alignPanel)
+  {
+    super();
+
+    /*
+     * Convert the map of sequences per pdb entry into the tied arrays expected
+     * by openNewChimera
+     * 
+     * TODO pass the Map down to openNewChimera and its callees instead
+     */
+    final Set<PDBEntry> pdbEntries = toView.keySet();
+    PDBEntry[] pdbs = pdbEntries.toArray(new PDBEntry[pdbEntries.size()]);
+    SequenceI[][] seqsForPdbs = new SequenceI[pdbEntries.size()][];
+    for (int i = 0; i < pdbs.length; i++)
+    {
+      final List<SequenceI> seqsForPdb = toView.get(pdbs[i]);
+      seqsForPdbs[i] = seqsForPdb.toArray(new SequenceI[seqsForPdb.size()]);
+    }
+
+    openNewChimera(alignPanel, pdbs, seqsForPdbs);
+  }
+
+  /**
    * add a new structure (with associated sequences and chains) to this viewer,
    * retrieving it if necessary first.
    * 
@@ -489,7 +566,7 @@ public class ChimeraViewFrame extends StructureViewerBase
     addingStructures = true;
     _started = false;
     alignAddedStructures = b;
-    progressBar = alignFrame; // visual indication happens on caller frame.
+    // progressBar = alignFrame; // visual indication happens on caller frame.
     (worker = new Thread(this)).start();
     return;
   }
@@ -522,10 +599,7 @@ public class ChimeraViewFrame extends StructureViewerBase
     jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle("Chimera", true),
             getBounds().width, getBounds().height);
 
-    /*
-     * Pass an empty 'command' to launch Chimera
-     */
-    jmb.evalStateCommand("", false);
+    jmb.launchChimera();
 
     if (this.chimeraSessionFile != null)
     {
@@ -542,10 +616,16 @@ public class ChimeraViewFrame extends StructureViewerBase
     jmb.startChimeraListener();
   }
 
+  /**
+   * If the list is not empty, add menu items for 'All' and each individual
+   * chain to the "View | Show Chain" sub-menu. Multiple selections are allowed.
+   * 
+   * @param chainNames
+   */
   void setChainMenuItems(List<String> chainNames)
   {
     chainMenu.removeAll();
-    if (chainNames == null)
+    if (chainNames == null || chainNames.isEmpty())
     {
       return;
     }
@@ -563,7 +643,7 @@ public class ChimeraViewFrame extends StructureViewerBase
             ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
           }
         }
-        centerViewer();
+        showSelectedChains();
         allChainsSelected = false;
       }
     });
@@ -579,7 +659,7 @@ public class ChimeraViewFrame extends StructureViewerBase
         {
           if (!allChainsSelected)
           {
-            centerViewer();
+            showSelectedChains();
           }
         }
       });
@@ -588,7 +668,10 @@ public class ChimeraViewFrame extends StructureViewerBase
     }
   }
 
-  void centerViewer()
+  /**
+   * Show only the selected chain(s) in the viewer
+   */
+  void showSelectedChains()
   {
     List<String> toshow = new ArrayList<String>();
     for (int i = 0; i < chainMenu.getItemCount(); i++)
@@ -602,7 +685,7 @@ public class ChimeraViewFrame extends StructureViewerBase
         }
       }
     }
-    jmb.centerViewer(toshow);
+    jmb.showChains(toshow);
   }
 
   /**
@@ -760,8 +843,8 @@ public class ChimeraViewFrame extends StructureViewerBase
               stopProgressBar("", startTime);
             }
             // Explicitly map to the filename used by Chimera ;
-            // TODO: use pe.getId() instead of pe.getFile() ?
-            jmb.getSsm().setMapping(jmb.getSequence()[pos], null,
+            jmb.getSsm().setMapping(jmb.getSequence()[pos],
+                    jmb.getChains()[pos],
                     pe.getFile(),
                     protocol);
           } catch (OutOfMemoryError oomerror)
@@ -819,9 +902,19 @@ public class ChimeraViewFrame extends StructureViewerBase
     Pdb pdbclient = new Pdb();
     AlignmentI pdbseq = null;
     String pdbid = processingEntry.getId();
-    long hdl = startProgressBar(MessageManager.formatMessage(
-            "status.fetching_pdb", new Object[]
-            { pdbid }));
+    long handle = System.currentTimeMillis()
+            + Thread.currentThread().hashCode();
+
+    /*
+     * Write 'fetching PDB' progress on AlignFrame as we are not yet visible
+     */
+    String msg = MessageManager.formatMessage("status.fetching_pdb",
+            new Object[]
+            { pdbid });
+    getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
+    // long hdl = startProgressBar(MessageManager.formatMessage(
+    // "status.fetching_pdb", new Object[]
+    // { pdbid }));
     try
     {
       pdbseq = pdbclient.getSequenceRecords(pdbid);
@@ -830,9 +923,10 @@ public class ChimeraViewFrame extends StructureViewerBase
       new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
     } finally
     {
-      String msg = pdbid + " "
+      msg = pdbid + " "
               + MessageManager.getString("label.state_completed");
-      stopProgressBar(msg, hdl);
+      getAlignmentPanel().alignFrame.setProgressBar(msg, handle);
+      // stopProgressBar(msg, hdl);
     }
     /*
      * If PDB data were saved and are not invalid (empty alignment), return the
@@ -867,6 +961,13 @@ public class ChimeraViewFrame extends StructureViewerBase
     return tm;
   }
 
+  /**
+   * End the progress bar with the specified handle, leaving a message (if not
+   * null) on the status bar
+   * 
+   * @param msg
+   * @param handle
+   */
   public void stopProgressBar(String msg, long handle)
   {
     if (progressBar != null)
@@ -1136,12 +1237,12 @@ public class ChimeraViewFrame extends StructureViewerBase
     {
       return;
     }
-    ;
+
     if (_alignwith.size() == 0)
     {
       _alignwith.add(getAlignmentPanel());
     }
-    ;
+
     try
     {
       AlignmentI[] als = new Alignment[_alignwith.size()];
@@ -1165,9 +1266,7 @@ public class ChimeraViewFrame extends StructureViewerBase
       }
       Cache.log.info("Couldn't align structures with the " + sp.toString()
               + "associated alignment panels.", e);
-
     }
-
   }
 
   public void setJalviewColourScheme(ColourSchemeI ucs)
index 2cc5079..2e3b37a 100644 (file)
 
 package jalview.gui;
 
-import jalview.datamodel.DBRefEntry;
-import jalview.datamodel.PDBEntry;
-import jalview.datamodel.SequenceI;
-import jalview.jbgui.GStructureChooser;
-import jalview.jbgui.PDBDocFieldPreferences;
-import jalview.structure.StructureSelectionManager;
-import jalview.util.MessageManager;
-import jalview.ws.dbsources.PDBRestClient;
-import jalview.ws.dbsources.PDBRestClient.PDBDocField;
-import jalview.ws.uimodel.PDBRestRequest;
-import jalview.ws.uimodel.PDBRestResponse;
-import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
-
 import java.awt.event.ItemEvent;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -49,6 +36,19 @@ import javax.swing.JLabel;
 import javax.swing.JOptionPane;
 import javax.swing.table.DefaultTableModel;
 
+import jalview.datamodel.DBRefEntry;
+import jalview.datamodel.PDBEntry;
+import jalview.datamodel.SequenceI;
+import jalview.jbgui.GStructureChooser;
+import jalview.jbgui.PDBDocFieldPreferences;
+import jalview.structure.StructureSelectionManager;
+import jalview.util.MessageManager;
+import jalview.ws.dbsources.PDBRestClient;
+import jalview.ws.dbsources.PDBRestClient.PDBDocField;
+import jalview.ws.uimodel.PDBRestRequest;
+import jalview.ws.uimodel.PDBRestResponse;
+import jalview.ws.uimodel.PDBRestResponse.PDBResponseSummary;
+
 
 /**
  * Provides the behaviors for the Structure chooser Panel
@@ -746,17 +746,17 @@ public class StructureChooser extends GStructureChooser
 
   private void launchStructureViewer(StructureSelectionManager ssm,
           PDBEntry[] pdbEntriesToView, AlignmentPanel alignPanel,
-          SequenceI[] selectedSequences)
+          SequenceI[] sequences)
   {
     StructureViewer sViewer = new StructureViewer(ssm);
     if (pdbEntriesToView.length > 1)
     {
-      sViewer.viewStructures(alignPanel, pdbEntriesToView,
-              alignPanel.av.collateForPDB(pdbEntriesToView));
+      sViewer.viewStructures(pdbEntriesToView, alignPanel.av.collateForPDB(pdbEntriesToView),
+              alignPanel);
     }
     else
     {
-      sViewer.viewStructures(pdbEntriesToView[0], selectedSequences, null,
+      sViewer.viewStructures(pdbEntriesToView[0], sequences,
               alignPanel);
     }
   }
index 7584612..2285765 100644 (file)
  */
 package jalview.gui;
 
+import java.awt.Rectangle;
+import java.util.ArrayList;
+import java.util.List;
+
 import jalview.api.structures.JalviewStructureDisplayI;
 import jalview.bin.Cache;
 import jalview.datamodel.PDBEntry;
@@ -27,8 +31,6 @@ import jalview.datamodel.SequenceI;
 import jalview.datamodel.StructureViewerModel;
 import jalview.structure.StructureSelectionManager;
 
-import java.awt.Rectangle;
-
 /**
  * proxy for handling structure viewers.
  * 
@@ -64,23 +66,85 @@ public class StructureViewer
     ssm = structureSelectionManager;
   }
 
-  public JalviewStructureDisplayI viewStructures(AlignmentPanel ap,
-          PDBEntry[] pr, SequenceI[][] collateForPDB)
+  /**
+   * View multiple PDB entries, each with associated sequences
+   * 
+   * @param pdbs
+   * @param seqsForPdbs
+   * @param ap
+   * @return
+   */
+  public JalviewStructureDisplayI viewStructures(PDBEntry[] pdbs,
+          SequenceI[][] seqsForPdbs, AlignmentPanel ap)
   {
-    return viewStructures(getViewerType(), ap, pr, collateForPDB);
+    JalviewStructureDisplayI viewer = onlyOnePdb(pdbs, seqsForPdbs, ap);
+    if (viewer != null)
+    {
+      return viewer;
+    }
+    return viewStructures(getViewerType(), pdbs, seqsForPdbs, ap);
   }
 
-  public JalviewStructureDisplayI viewStructures(ViewerType viewerType,
-          AlignmentPanel ap, PDBEntry[] pr, SequenceI[][] collateForPDB)
+  /**
+   * A strictly temporary method pending JAL-1761 refactoring. Determines if all
+   * the passed PDB entries are the same (this is the case if selected sequences
+   * to view structure for are chains of the same structure). If so, calls the
+   * single-pdb version of viewStructures and returns the viewer, else returns
+   * null.
+   * 
+   * @param pdbs
+   * @param seqsForPdbs
+   * @param ap
+   * @return
+   */
+  private JalviewStructureDisplayI onlyOnePdb(PDBEntry[] pdbs,
+          SequenceI[][] seqsForPdbs,
+          AlignmentPanel ap)
+  {
+    List<SequenceI> seqs = new ArrayList<SequenceI>();
+    if (pdbs == null || pdbs.length == 0)
+    {
+      return null;
+    }
+    int i = 0;
+    String firstFile = pdbs[0].getFile();
+    for (PDBEntry pdb : pdbs)
+    {
+      String pdbFile = pdb.getFile();
+      if (pdbFile == null || !pdbFile.equals(firstFile))
+      {
+        return null;
+      }
+      SequenceI[] pdbseqs = seqsForPdbs[i++];
+      if (pdbseqs != null)
+      {
+        for (SequenceI sq : pdbseqs)
+        {
+          seqs.add(sq);
+        }
+      }
+    }
+    return viewStructures(pdbs[0],
+            seqs.toArray(new SequenceI[seqs.size()]), ap);
+  }
+
+  public JalviewStructureDisplayI viewStructures(PDBEntry pdb,
+          SequenceI[] seqsForPdb, AlignmentPanel ap)
+  {
+    return viewStructures(getViewerType(), pdb, seqsForPdb, ap);
+  }
+
+  protected JalviewStructureDisplayI viewStructures(ViewerType viewerType,
+          PDBEntry[] pdbs, SequenceI[][] seqsForPdbs, AlignmentPanel ap)
   {
     JalviewStructureDisplayI sview = null;
     if (viewerType.equals(ViewerType.JMOL))
     {
-      sview = new AppJmol(ap, pr, ap.av.collateForPDB(pr));
+      sview = new AppJmol(ap, pdbs, ap.av.collateForPDB(pdbs));
     }
     else if (viewerType.equals(ViewerType.CHIMERA))
     {
-      sview = new ChimeraViewFrame(ap, pr, ap.av.collateForPDB(pr));
+      sview = new ChimeraViewFrame(pdbs, ap.av.collateForPDB(pdbs), ap);
     }
     else
     {
@@ -90,17 +154,17 @@ public class StructureViewer
     return sview;
   }
 
-  public JalviewStructureDisplayI viewStructures(ViewerType viewerType,
-          AlignmentPanel ap, PDBEntry pr, SequenceI[] collateForPDB)
+  protected JalviewStructureDisplayI viewStructures(ViewerType viewerType,
+          PDBEntry pdb, SequenceI[] seqsForPdb, AlignmentPanel ap)
   {
     JalviewStructureDisplayI sview = null;
     if (viewerType.equals(ViewerType.JMOL))
     {
-      sview = new AppJmol(pr, collateForPDB, null, ap);
+      sview = new AppJmol(pdb, seqsForPdb, null, ap);
     }
     else if (viewerType.equals(ViewerType.CHIMERA))
     {
-      sview = new ChimeraViewFrame(pr, collateForPDB, null, ap);
+      sview = new ChimeraViewFrame(pdb, seqsForPdb, null, ap);
     }
     else
     {
@@ -110,12 +174,6 @@ public class StructureViewer
     return sview;
   }
 
-  public JalviewStructureDisplayI viewStructures(PDBEntry pdb,
-          SequenceI[] sequenceIs, Object object, AlignmentPanel ap)
-  {
-    return viewStructures(getViewerType(), ap, pdb, sequenceIs);
-  }
-
   /**
    * Create a new panel controlling a structure viewer.
    * 
index 298e82c..86c9a21 100644 (file)
@@ -5,10 +5,12 @@ import java.util.Arrays;
 import java.util.List;
 
 import jalview.api.StructureSelectionManagerProvider;
+import jalview.datamodel.AlignmentI;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.structure.AtomSpec;
 import jalview.structure.StructureListener;
+import jalview.structure.StructureMapping;
 import jalview.structure.StructureSelectionManager;
 import jalview.util.Comparison;
 import jalview.util.MessageManager;
@@ -51,6 +53,35 @@ public abstract class AAStructureBindingModel extends
   private boolean nucleotide;
 
   /**
+   * Data bean class to simplify parameterisation in superposeStructures
+   */
+  protected class SuperposeData
+  {
+    /**
+     * Constructor with alignment width argument
+     * 
+     * @param width
+     */
+    public SuperposeData(int width)
+    {
+      pdbResNo = new int[width];
+    }
+
+    public String filename;
+
+    public String pdbId;
+
+    public String chain = "";
+
+    public boolean isRna;
+
+    /*
+     * The pdb residue number (if any) mapped to each column of the alignment
+     */
+    public int[] pdbResNo;
+  }
+
+  /**
    * Constructor
    * 
    * @param ssm
@@ -388,6 +419,14 @@ public abstract class AAStructureBindingModel extends
     }
   }
 
+  @Override
+  public abstract void highlightAtoms(List<AtomSpec> atoms);
+
+  protected boolean isNucleotide()
+  {
+    return this.nucleotide;
+  }
+
   /**
    * Returns a readable description of all mappings for the wrapped pdbfile to
    * any mapped sequences
@@ -412,24 +451,154 @@ public abstract class AAStructureBindingModel extends
     return sb.toString();
   }
 
-  @Override
-  public void highlightAtoms(List<AtomSpec> atoms)
+  /**
+   * Returns the mapped structure position for a given aligned column of a given
+   * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
+   * not mapped to structure.
+   * 
+   * @param seq
+   * @param alignedPos
+   * @param mapping
+   * @return
+   */
+  protected int getMappedPosition(SequenceI seq, int alignedPos,
+          StructureMapping mapping)
   {
-    if (atoms != null)
+    if (alignedPos >= seq.getLength())
     {
-      for (AtomSpec atom : atoms)
+      return -1;
+    }
+
+    if (Comparison.isGap(seq.getCharAt(alignedPos)))
+    {
+      return -1;
+    }
+    int seqPos = seq.findPosition(alignedPos);
+    int pos = mapping.getPDBResNum(seqPos);
+    return pos;
+  }
+
+  /**
+   * Helper method to identify residues that can participate in a structure
+   * superposition command. For each structure, identify a sequence in the
+   * alignment which is mapped to the structure. Identify non-gapped columns in
+   * the sequence which have a mapping to a residue in the structure. Returns
+   * the index of the first structure that has a mapping to the alignment.
+   * 
+   * @param alignment
+   *          the sequence alignment which is the basis of structure
+   *          superposition
+   * @param matched
+   *          an array of booleans, indexed by alignment column, where true
+   *          indicates that every structure has a mapped residue present in the
+   *          column (so the column can participate in structure alignment)
+   * @param structures
+   *          an array of data beans corresponding to pdb file index
+   * @return
+   */
+  protected int findSuperposableResidues(AlignmentI alignment,
+          boolean[] matched, SuperposeData[] structures)
+  {
+    int refStructure = -1;
+    String[] files = getPdbFile();
+    for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+    {
+      StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
+      int lastPos = -1;
+
+      /*
+       * Find the first mapped sequence (if any) for this PDB entry which is in
+       * the alignment
+       */
+      final int seqCountForPdbFile = getSequence()[pdbfnum].length;
+      for (int s = 0; s < seqCountForPdbFile; s++)
       {
-        highlightAtom(atom.getAtomIndex(), atom.getPdbResNum(),
-                atom.getChain(), atom.getPdbFile());
+        for (StructureMapping mapping : mappings)
+        {
+          final SequenceI theSequence = getSequence()[pdbfnum][s];
+          if (mapping.getSequence() == theSequence
+                  && alignment.findIndex(theSequence) > -1)
+          {
+            if (refStructure < 0)
+            {
+              refStructure = pdbfnum;
+            }
+            for (int r = 0; r < matched.length; r++)
+            {
+              if (!matched[r])
+              {
+                continue;
+              }
+              int pos = getMappedPosition(theSequence, r, mapping);
+              if (pos < 1 || pos == lastPos)
+              {
+                matched[r] = false;
+                continue;
+              }
+              lastPos = pos;
+              structures[pdbfnum].pdbResNo[r] = pos;
+            }
+            String chain = mapping.getChain();
+            if (chain != null && chain.trim().length() > 0)
+            {
+              structures[pdbfnum].chain = chain;
+            }
+            structures[pdbfnum].pdbId = mapping.getPdbId();
+            structures[pdbfnum].isRna = theSequence.getRNA() != null;
+            // move on to next pdb file
+            s = seqCountForPdbFile;
+            break;
+          }
+        }
       }
     }
+    return refStructure;
   }
 
-  protected abstract void highlightAtom(int atomIndex, int pdbResNum,
-          String chain, String pdbFile);
-
-  protected boolean isNucleotide()
+  /**
+   * Returns true if the structure viewer has loaded all of the files of
+   * interest (identified by the file mapping having been set up), or false if
+   * any are still not loaded after a timeout interval.
+   * 
+   * @param files
+   */
+  protected boolean waitForFileLoad(String[] files)
   {
-    return this.nucleotide;
+    /*
+     * give up after 10 secs plus 1 sec per file
+     */
+    long starttime = System.currentTimeMillis();
+    long endTime = 10000 + 1000 * files.length + starttime;
+    String notLoaded = null;
+
+    boolean waiting = true;
+    while (waiting && System.currentTimeMillis() < endTime)
+    {
+      waiting = false;
+      for (String file : files)
+      {
+        notLoaded = file;
+        try
+        {
+          StructureMapping[] sm = getSsm().getMapping(file);
+          if (sm == null || sm.length == 0)
+          {
+            waiting = true;
+          }
+        } catch (Throwable x)
+        {
+          waiting = true;
+        }
+      }
+    }
+
+    if (waiting)
+    {
+      System.err
+              .println("Timed out waiting for structure viewer to load file "
+                      + notLoaded);
+      return false;
+    }
+    return true;
   }
 }
\ No newline at end of file
index f2535cb..807d7bb 100644 (file)
@@ -7,7 +7,6 @@ import org.junit.BeforeClass;
 import org.junit.Test;
 
 import jalview.api.structures.JalviewStructureDisplayI;
-import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
 import jalview.gui.AlignFrame;
 import jalview.gui.StructureViewer;
@@ -63,14 +62,11 @@ public class JalviewChimeraView
         {
           final StructureViewer structureViewer = new StructureViewer(af
                   .getViewport().getStructureSelectionManager());
-
+          structureViewer.setViewerType(ViewerType.JMOL);
           JalviewStructureDisplayI jmolViewer = structureViewer
-                  .viewStructures(ViewerType.JMOL, af.getCurrentView()
-                          .getAlignPanel(), new PDBEntry[]
-                  { (PDBEntry) dsq.getPDBId().elementAt(q) },
-                          new SequenceI[][]
-                          { new SequenceI[]
-                          { sq } });
+                  .viewStructures(dsq.getPDBId().elementAt(q),
+                          new SequenceI[]
+                  { sq }, af.getCurrentView().getAlignPanel());
           /*
            * Wait for viewer thread to start
            */
@@ -110,14 +106,11 @@ public class JalviewChimeraView
         {
           final StructureViewer structureViewer = new StructureViewer(af
                   .getViewport().getStructureSelectionManager());
-
+          structureViewer.setViewerType(ViewerType.CHIMERA);
           JalviewStructureDisplayI chimeraViewer = structureViewer
-                  .viewStructures(ViewerType.CHIMERA, af.getCurrentView()
-                          .getAlignPanel(), new PDBEntry[]
-                  { (PDBEntry) dsq.getPDBId().elementAt(q) },
-                          new SequenceI[][]
-                          { new SequenceI[]
-                          { sq } });
+                  .viewStructures(dsq.getPDBId().elementAt(q),
+                          new SequenceI[]
+                          { sq }, af.getCurrentView().getAlignPanel());
           /*
            * Wait for viewer thread to start
            */
diff --git a/test/jalview/structures/models/AAStructureBindingModelTest.java b/test/jalview/structures/models/AAStructureBindingModelTest.java
new file mode 100644 (file)
index 0000000..3db7f23
--- /dev/null
@@ -0,0 +1,183 @@
+package jalview.structures.models;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentI;
+import jalview.datamodel.PDBEntry;
+import jalview.datamodel.PDBEntry.Type;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceI;
+import jalview.io.AppletFormatAdapter;
+import jalview.structure.AtomSpec;
+import jalview.structure.StructureSelectionManager;
+import jalview.structures.models.AAStructureBindingModel.SuperposeData;
+
+/**
+ * Unit tests for non-abstract methods of abstract base class
+ * 
+ * @author gmcarstairs
+ *
+ */
+public class AAStructureBindingModelTest
+{
+  private static final String PDB_1 = "HEADER    COMPLEX (ANTI-ONCOGENE/ANKYRIN REPEATS) 30-SEP-96   1YCS              \n"
+          + "ATOM      2  CA  VAL A  97      24.134   4.926  45.821  1.00 47.43           C  \n"
+          + "ATOM      9  CA  PRO A  98      25.135   8.584  46.217  1.00 41.60           C  \n"
+          + "ATOM     16  CA  SER A  99      28.243   9.596  44.271  1.00 39.63           C  \n"
+          + "ATOM     22  CA  GLN A 100      31.488  10.133  46.156  1.00 35.60           C  \n"
+          + "ATOM     31  CA  LYS A 101      33.323  11.587  43.115  1.00 41.69           C  \n";
+
+  private static final String PDB_2 = "HEADER    HYDROLASE                               09-SEP-09   3A6S              \n"
+          + "ATOM      2  CA  MET A   1      15.366 -11.648  24.854  1.00 32.05           C  \n"
+          + "ATOM     10  CA  LYS A   2      16.846  -9.215  22.340  1.00 25.68           C  \n"
+          + "ATOM     19  CA  LYS A   3      15.412  -6.335  20.343  1.00 19.42           C  \n"
+          + "ATOM     28  CA  LEU A   4      15.629  -5.719  16.616  1.00 15.49           C  \n"
+          + "ATOM     36  CA  GLN A   5      14.412  -2.295  15.567  1.00 12.19           C  \n";
+
+  private static final String PDB_3 = "HEADER    STRUCTURAL GENOMICS                     04-MAR-03   1OOT              \n"
+          + "ATOM      2  CA  SER A   1      29.427   3.330  -6.578  1.00 32.50           C  \n"
+          + "ATOM      8  CA  PRO A   2      29.975   3.340  -2.797  1.00 17.62           C  \n"
+          + "ATOM     16  CA ALYS A   3      26.958   3.024  -0.410  0.50  8.78           C  \n"
+          + "ATOM     33  CA  ALA A   4      26.790   4.320   3.172  1.00 11.98           C  \n"
+          + "ATOM     39  CA AVAL A   5      24.424   3.853   6.106  0.50 13.83           C  \n";
+
+  AAStructureBindingModel testee;
+
+  AlignmentI al = null;
+
+  /**
+   * Set up test conditions with three aligned sequences,
+   */
+  @Before
+  public void setUp()
+  {
+    SequenceI seq1 = new Sequence("1YCS", "-VPSQK");
+    SequenceI seq2 = new Sequence("3A6S", "MK-KLQ");
+    SequenceI seq3 = new Sequence("1OOT", "SPK-AV");
+    al = new Alignment(new SequenceI[]
+    { seq1, seq2, seq3 });
+    al.setDataset(null);
+
+    PDBEntry[] pdbFiles = new PDBEntry[3];
+    pdbFiles[0] = new PDBEntry("1YCS", "A", Type.PDB, "1YCS.pdb");
+    pdbFiles[1] = new PDBEntry("3A6S", "B", Type.PDB, "3A6S.pdb");
+    pdbFiles[2] = new PDBEntry("1OOT", "A", Type.PDB, "1OOT.pdb");
+    String[][] chains = new String[3][];
+    SequenceI[][] seqs = new SequenceI[3][];
+    seqs[0] = new SequenceI[]
+    { seq1 };
+    seqs[1] = new SequenceI[]
+    { seq2 };
+    seqs[2] = new SequenceI[]
+    { seq3 };
+    StructureSelectionManager ssm = new StructureSelectionManager();
+
+    ssm.setMapping(new SequenceI[]
+    { seq1 }, null, PDB_1, AppletFormatAdapter.PASTE);
+    ssm.setMapping(new SequenceI[]
+    { seq2 }, null, PDB_2, AppletFormatAdapter.PASTE);
+    ssm.setMapping(new SequenceI[]
+    { seq3 }, null, PDB_3, AppletFormatAdapter.PASTE);
+
+    testee = new AAStructureBindingModel(ssm, pdbFiles, seqs, chains, null)
+    {
+      @Override
+      public String[] getPdbFile()
+      {
+        /*
+         * fudge 'filenames' to match those generated when PDBFile parses PASTE
+         * data
+         */
+        return new String[]
+        { "INLINE1YCS", "INLINE3A6S", "INLINE1OOT" };
+      }
+      @Override
+      public void updateColours(Object source)
+      {
+      }
+      @Override
+      public void releaseReferences(Object svl)
+      {
+      }
+      @Override
+      public void highlightAtoms(List<AtomSpec> atoms)
+      {
+      }
+    };
+  }
+
+  /**
+   * Verify that the method determines that columns 2, 5 and 6 of the aligment
+   * are alignable in structure
+   */
+  @Test
+  public void testFindSuperposableResidues()
+  {
+    SuperposeData[] structs = new SuperposeData[al.getHeight()];
+    for (int i = 0; i < structs.length; i++)
+    {
+      structs[i] = testee.new SuperposeData(al.getWidth());
+    }
+    /*
+     * initialise array of 'superposable columns' to true (would be false for
+     * hidden columns)
+     */
+    boolean[] matched = new boolean[al.getWidth()];
+    Arrays.fill(matched, true);
+
+    int refStructure = testee
+            .findSuperposableResidues(al, matched, structs);
+
+    assertEquals(0, refStructure);
+
+    /*
+     * only ungapped, structure-mapped columns are superposable
+     */
+    assertFalse(matched[0]); // gap in first sequence
+    assertTrue(matched[1]);
+    assertFalse(matched[2]); // gap in second sequence
+    assertFalse(matched[3]); // gap in third sequence
+    assertTrue(matched[4]);
+    assertTrue(matched[5]);
+  }
+
+  @Test
+  public void testFindSuperposableResidues_hiddenColumn()
+  {
+    SuperposeData[] structs = new SuperposeData[al.getHeight()];
+    for (int i = 0; i < structs.length; i++)
+    {
+      structs[i] = testee.new SuperposeData(al.getWidth());
+    }
+    /*
+     * initialise array of 'superposable columns' to true (would be false for
+     * hidden columns)
+     */
+    boolean[] matched = new boolean[al.getWidth()];
+    Arrays.fill(matched, true);
+    // treat column 5 of the alignment as hidden
+    matched[4] = false;
+
+    int refStructure = testee
+            .findSuperposableResidues(al, matched, structs);
+
+    assertEquals(0, refStructure);
+
+    // only ungapped, structure-mapped columns are not superposable
+    assertFalse(matched[0]);
+    assertTrue(matched[1]);
+    assertFalse(matched[2]);
+    assertFalse(matched[3]);
+    assertFalse(matched[4]); // superposable, but hidden, column
+    assertTrue(matched[5]);
+  }
+}