2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ext.rbvi.chimera;
23 import jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.httpserver.AbstractRequestHandler;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureMappingcommandSet;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.structures.models.AAStructureBindingModel;
39 import jalview.util.MessageManager;
41 import java.awt.Color;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.io.PrintWriter;
46 import java.net.BindException;
47 import java.util.ArrayList;
48 import java.util.Collections;
49 import java.util.HashMap;
50 import java.util.LinkedHashMap;
51 import java.util.List;
54 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
55 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
56 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
57 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
59 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
61 // Chimera clause to exclude alternate locations in atom selection
62 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
64 private static final String COLOURING_CHIMERA = MessageManager
65 .getString("status.colouring_chimera");
67 private static final boolean debug = false;
69 private static final String PHOSPHORUS = "P";
71 private static final String ALPHACARBON = "CA";
74 * Object through which we talk to Chimera
76 private ChimeraManager viewer;
79 * Object which listens to Chimera notifications
81 private AbstractRequestHandler chimeraListener;
84 * set if chimera state is being restored from some source - instructs binding
85 * not to apply default display style when structure set is updated for first
88 private boolean loadingFromArchive = false;
91 * flag to indicate if the Chimera viewer should ignore sequence colouring
92 * events from the structure manager because the GUI is still setting up
94 private boolean loadingFinished = true;
96 public String fileLoadingError;
99 * Map of ChimeraModel objects keyed by PDB full local file name
101 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
103 String lastHighlightCommand;
106 * incremented every time a load notification is successfully handled -
107 * lightweight mechanism for other threads to detect when they can start
108 * referring to new structures.
110 private long loadNotifiesHandled = 0;
113 * Open a PDB structure file in Chimera and set up mappings from Jalview.
115 * We check if the PDB model id is already loaded in Chimera, if so don't
116 * reopen it. This is the case if Chimera has opened a saved session file.
121 public boolean openFile(PDBEntry pe)
123 String file = pe.getFile();
126 List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
127 List<ChimeraModel> oldList = viewer.getModelList();
128 boolean alreadyOpen = false;
131 * If Chimera already has this model, don't reopen it, but do remap it.
133 for (ChimeraModel open : oldList)
135 if (open.getModelName().equals(pe.getId()))
138 modelsToMap.add(open);
143 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
144 * the model name(s) added by Chimera.
148 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
149 List<ChimeraModel> newList = viewer.getModelList();
150 // JAL-1728 newList.removeAll(oldList) does not work
151 for (ChimeraModel cm : newList)
153 if (cm.getModelName().equals(pe.getId()))
160 chimeraMaps.put(file, modelsToMap);
162 if (getSsm() != null)
164 getSsm().addStructureViewerListener(this);
165 // ssm.addSelectionListener(this);
166 FeatureRenderer fr = getFeatureRenderer(null);
174 } catch (Exception q)
176 log("Exception when trying to open model " + file + "\n"
192 public JalviewChimeraBinding(StructureSelectionManager ssm,
193 PDBEntry[] pdbentry, SequenceI[][] sequenceIs, String[][] chains,
196 super(ssm, pdbentry, sequenceIs, chains, protocol);
197 viewer = new ChimeraManager(
198 new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
202 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
203 * it to start listening
205 public void startChimeraListener()
209 chimeraListener = new ChimeraListener(this);
210 viewer.startListening(chimeraListener.getUri());
211 } catch (BindException e)
213 System.err.println("Failed to start Chimera listener: "
219 * Construct a title string for the viewer window based on the data Jalview
225 public String getViewerTitle(boolean verbose)
227 return getViewerTitle("Chimera", verbose);
231 * Tells Chimera to display only the specified chains
235 public void showChains(List<String> toshow)
238 * Construct a chimera command like
240 * ~display #*;~ribbon #*;ribbon :.A,:.B
242 StringBuilder cmd = new StringBuilder(64);
243 boolean first = true;
244 for (String chain : toshow)
250 cmd.append(":.").append(chain);
255 * could append ";focus" to this command to resize the display to fill the
256 * window, but it looks more helpful not to (easier to relate chains to the
259 final String command = "~display #*; ~ribbon #*; ribbon "
261 sendChimeraCommand(command, false);
265 * Close down the Jalview viewer and listener, and (optionally) the associated
268 public void closeViewer(boolean closeChimera)
270 getSsm().removeStructureViewerListener(this, this.getPdbFile());
273 viewer.exitChimera();
275 if (this.chimeraListener != null)
277 chimeraListener.shutdown();
278 chimeraListener = null;
282 releaseUIResources();
285 public void colourByChain()
287 colourBySequence = false;
288 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
292 * Constructs and sends a Chimera command to colour by charge
294 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
295 * <li>Lysine and Arginine (positive charge) blue</li>
296 * <li>Cysteine - yellow</li>
297 * <li>all others - white</li>
300 public void colourByCharge()
302 colourBySequence = false;
303 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
304 sendAsynchronousCommand(command, COLOURING_CHIMERA);
308 * Construct and send a command to align structures against a reference
309 * structure, based on one or more sequence alignments
312 * an array of alignments to process
313 * @param _refStructure
314 * an array of corresponding reference structures (index into pdb
315 * file array); if a negative value is passed, the first PDB file
316 * mapped to an alignment sequence is used as the reference for
319 * an array of corresponding hidden columns for each alignment
321 public void superposeStructures(AlignmentI[] _alignment,
322 int[] _refStructure, ColumnSelection[] _hiddenCols)
324 StringBuilder allComs = new StringBuilder(128);
325 String[] files = getPdbFile();
327 if (!waitForFileLoad(files))
333 StringBuilder selectioncom = new StringBuilder(256);
334 for (int a = 0; a < _alignment.length; a++)
336 int refStructure = _refStructure[a];
337 AlignmentI alignment = _alignment[a];
338 ColumnSelection hiddenCols = _hiddenCols[a];
340 if (refStructure >= files.length)
342 System.err.println("Ignoring invalid reference structure value "
348 * 'matched' array will hold 'true' for visible alignment columns where
349 * all sequences have a residue with a mapping to the PDB structure
351 boolean matched[] = new boolean[alignment.getWidth()];
352 for (int m = 0; m < matched.length; m++)
354 matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
357 SuperposeData[] structures = new SuperposeData[files.length];
358 for (int f = 0; f < files.length; f++)
360 structures[f] = new SuperposeData(alignment.getWidth());
364 * Calculate the superposable alignment columns ('matched'), and the
365 * corresponding structure residue positions (structures.pdbResNo)
367 int candidateRefStructure = findSuperposableResidues(alignment,
368 matched, structures);
369 if (refStructure < 0)
372 * If no reference structure was specified, pick the first one that has
373 * a mapping in the alignment
375 refStructure = candidateRefStructure;
379 for (boolean b : matched)
388 // TODO: bail out here because superposition illdefined?
392 * Generate select statements to select regions to superimpose structures
394 String[] selcom = new String[files.length];
395 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
397 String chainCd = "." + structures[pdbfnum].chain;
400 StringBuilder molsel = new StringBuilder();
401 for (int r = 0; r < matched.length; r++)
405 int pdbResNum = structures[pdbfnum].pdbResNo[r];
406 if (lpos != pdbResNum - 1)
409 * discontiguous - append last residue now
413 molsel.append(String.valueOf(lpos));
414 molsel.append(chainCd);
422 * extending a contiguous run
427 * start the range selection
429 molsel.append(String.valueOf(lpos));
439 * and terminate final selection
443 molsel.append(String.valueOf(lpos));
444 molsel.append(chainCd);
446 if (molsel.length() > 1)
448 selcom[pdbfnum] = molsel.toString();
449 selectioncom.append("#").append(String.valueOf(pdbfnum))
451 selectioncom.append(selcom[pdbfnum]);
452 selectioncom.append(" ");
453 if (pdbfnum < files.length - 1)
455 selectioncom.append("| ");
460 selcom[pdbfnum] = null;
464 StringBuilder command = new StringBuilder(256);
465 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
467 if (pdbfnum == refStructure || selcom[pdbfnum] == null
468 || selcom[refStructure] == null)
472 if (command.length() > 0)
478 * Form Chimera match command, from the 'new' structure to the
479 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
481 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
484 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
486 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
487 command.append(selcom[pdbfnum]);
488 command.append("@").append(
489 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
490 // JAL-1757 exclude alternate CA locations
491 command.append(NO_ALTLOCS);
492 command.append(" ").append(getModelSpec(refStructure)).append(":");
493 command.append(selcom[refStructure]);
494 command.append("@").append(
495 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
496 command.append(NO_ALTLOCS);
498 if (selectioncom.length() > 0)
502 System.out.println("Select regions:\n" + selectioncom.toString());
503 System.out.println("Superimpose command(s):\n"
504 + command.toString());
506 allComs.append("~display all; chain @CA|P; ribbon ")
507 .append(selectioncom.toString())
508 .append(";" + command.toString());
511 if (selectioncom.length() > 0)
513 // TODO: visually distinguish regions that were superposed
514 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
516 selectioncom.setLength(selectioncom.length() - 1);
520 System.out.println("Select regions:\n" + selectioncom.toString());
522 allComs.append("; ~display all; chain @CA|P; ribbon ")
523 .append(selectioncom.toString()).append("; focus");
524 sendChimeraCommand(allComs.toString(), false);
530 * Helper method to construct model spec in Chimera format:
532 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
533 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
535 * Note for now we only ever choose the first of multiple models. This
536 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
537 * future if there is a need to select specific sub-models.
542 protected String getModelSpec(int pdbfnum)
544 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
550 * For now, the test for having sub-models is whether multiple Chimera
551 * models are mapped for the PDB file; the models are returned as a response
552 * to the Chimera command 'list models type molecule', see
553 * ChimeraManager.getModelList().
555 List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
556 boolean hasSubModels = maps != null && maps.size() > 1;
557 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
561 * Launch Chimera, unless an instance linked to this object is already
562 * running. Returns true if chimera is successfully launched, or already
563 * running, else false.
567 public boolean launchChimera()
569 if (!viewer.isChimeraLaunched())
571 return viewer.launchChimera(StructureManager.getChimeraPaths());
573 if (viewer.isChimeraLaunched())
577 log("Failed to launch Chimera!");
582 * Answers true if the Chimera process is still running, false if ended or not
587 public boolean isChimeraRunning()
589 return viewer.isChimeraLaunched();
593 * Send a command to Chimera, and optionally log and return any responses.
595 * Does nothing, and returns null, if the command is the same as the last one
601 public List<String> sendChimeraCommand(final String command,
606 // ? thread running after viewer shut down
609 List<String> reply = null;
610 viewerCommandHistory(false);
611 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
613 // trim command or it may never find a match in the replyLog!!
614 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
621 log("Response from command ('" + command + "') was:\n"
626 viewerCommandHistory(true);
632 * Send a Chimera command asynchronously in a new thread. If the progress
633 * message is not null, display this message while the command is executing.
638 protected abstract void sendAsynchronousCommand(String command,
642 * colour any structures associated with sequences in the given alignment
643 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
644 * if colourBySequence is enabled.
646 public void colourBySequence(boolean showFeatures,
647 jalview.api.AlignmentViewPanel alignmentv)
649 if (!colourBySequence || !loadingFinished)
653 if (getSsm() == null)
657 String[] files = getPdbFile();
659 SequenceRenderer sr = getSequenceRenderer(alignmentv);
661 FeatureRenderer fr = null;
664 fr = getFeatureRenderer(alignmentv);
666 AlignmentI alignment = alignmentv.getAlignment();
668 StructureMappingcommandSet colourBySequenceCommands = ChimeraCommands
669 .getColourBySequenceCommand(getSsm(), files, getSequence(), sr,
671 for (String command : colourBySequenceCommands.commands)
673 sendAsynchronousCommand(command, COLOURING_CHIMERA);
680 protected void executeWhenReady(String command)
683 sendChimeraCommand(command, false);
687 private void waitForChimera()
689 while (viewer != null && viewer.isBusy())
694 } catch (InterruptedException q)
700 // End StructureListener
701 // //////////////////////////
704 * returns the current featureRenderer that should be used to colour the
711 public abstract FeatureRenderer getFeatureRenderer(
712 AlignmentViewPanel alignment);
715 * instruct the Jalview binding to update the pdbentries vector if necessary
716 * prior to matching the viewer's contents to the list of structure files
717 * Jalview knows about.
719 public abstract void refreshPdbEntries();
721 private int getModelNum(String modelFileName)
723 String[] mfn = getPdbFile();
728 for (int i = 0; i < mfn.length; i++)
730 if (mfn[i].equalsIgnoreCase(modelFileName))
739 * map between index of model filename returned from getPdbFile and the first
740 * index of models from this file in the viewer. Note - this is not trimmed -
741 * use getPdbFile to get number of unique models.
743 private int _modelFileNameMap[];
745 // ////////////////////////////////
746 // /StructureListener
748 public synchronized String[] getPdbFile()
752 return new String[0];
754 // if (modelFileNames == null)
756 // Collection<ChimeraModel> chimodels = viewer.getChimeraModels();
757 // _modelFileNameMap = new int[chimodels.size()];
759 // for (ChimeraModel chimodel : chimodels)
761 // String mdlName = chimodel.getModelName();
763 // modelFileNames = new String[j];
764 // // System.arraycopy(mset, 0, modelFileNames, 0, j);
767 return chimeraMaps.keySet().toArray(
768 modelFileNames = new String[chimeraMaps.size()]);
772 * returns the current sequenceRenderer that should be used to colour the
779 public abstract SequenceRenderer getSequenceRenderer(
780 AlignmentViewPanel alignment);
783 * Construct and send a command to highlight zero, one or more atoms. We do
784 * this by sending an "rlabel" command to show the residue label at that
788 public void highlightAtoms(List<AtomSpec> atoms)
790 if (atoms == null || atoms.size() == 0)
795 StringBuilder cmd = new StringBuilder(128);
796 boolean first = true;
797 boolean found = false;
799 for (AtomSpec atom : atoms)
801 int pdbResNum = atom.getPdbResNum();
802 String chain = atom.getChain();
803 String pdbfile = atom.getPdbFile();
804 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
805 if (cms != null && !cms.isEmpty())
809 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
817 cmd.append(pdbResNum);
818 if (!chain.equals(" "))
820 cmd.append(".").append(chain);
825 String command = cmd.toString();
828 * avoid repeated commands for the same residue
830 if (command.equals(lastHighlightCommand))
836 * unshow the label for the previous residue
838 if (lastHighlightCommand != null)
840 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
844 viewer.sendChimeraCommand(command, false);
846 this.lastHighlightCommand = command;
850 * Query Chimera for its current selection, and highlight it on the alignment
852 public void highlightChimeraSelection()
855 * Ask Chimera for its current selection
857 List<String> selection = viewer.getSelectedResidueSpecs();
860 * Parse model number, residue and chain for each selected position,
861 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
863 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(selection);
866 * Broadcast the selection (which may be empty, if the user just cleared all
869 getSsm().mouseOverStructure(atomSpecs);
873 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
874 * corresponding residues (if any) in Jalview
876 * @param structureSelection
879 protected List<AtomSpec> convertStructureResiduesToAlignment(
880 List<String> structureSelection)
882 List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
883 for (String atomSpec : structureSelection)
885 int colonPos = atomSpec.indexOf(":");
888 continue; // malformed
891 int hashPos = atomSpec.indexOf("#");
892 String modelSubmodel = atomSpec.substring(hashPos + 1, colonPos);
893 int dotPos = modelSubmodel.indexOf(".");
897 modelId = Integer.valueOf(dotPos == -1 ? modelSubmodel
898 : modelSubmodel.substring(0, dotPos));
899 } catch (NumberFormatException e)
901 // ignore, default to model 0
904 String residueChain = atomSpec.substring(colonPos + 1);
905 dotPos = residueChain.indexOf(".");
906 int pdbResNum = Integer.parseInt(dotPos == -1 ? residueChain
907 : residueChain.substring(0, dotPos));
909 String chainId = dotPos == -1 ? "" : residueChain
910 .substring(dotPos + 1);
913 * Work out the pdbfilename from the model number
915 String pdbfilename = modelFileNames[0];
916 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
918 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
920 if (cm.getModelNumber() == modelId)
922 pdbfilename = pdbfile;
927 atomSpecs.add(new AtomSpec(pdbfilename, chainId, pdbResNum, 0));
932 private void log(String message)
934 System.err.println("## Chimera log: " + message);
937 private void viewerCommandHistory(boolean enable)
939 // log("(Not yet implemented) History "
940 // + ((debug || enable) ? "on" : "off"));
943 public long getLoadNotifiesHandled()
945 return loadNotifiesHandled;
948 public void setJalviewColourScheme(ColourSchemeI cs)
950 colourBySequence = false;
957 // Chimera expects RBG values in the range 0-1
958 final double normalise = 255D;
959 viewerCommandHistory(false);
960 StringBuilder command = new StringBuilder(128);
962 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
964 for (String res : residueSet)
966 Color col = cs.findColour(res.charAt(0));
967 command.append("color " + col.getRed() / normalise + ","
968 + col.getGreen() / normalise + "," + col.getBlue()
969 / normalise + " ::" + res + ";");
972 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
973 viewerCommandHistory(true);
977 * called when the binding thinks the UI needs to be refreshed after a Chimera
978 * state change. this could be because structures were loaded, or because an
979 * error has occurred.
981 public abstract void refreshGUI();
984 public void setLoadingFromArchive(boolean loadingFromArchive)
986 this.loadingFromArchive = loadingFromArchive;
991 * @return true if Chimeral is still restoring state or loading is still going
992 * on (see setFinsihedLoadingFromArchive)
995 public boolean isLoadingFromArchive()
997 return loadingFromArchive && !loadingFinished;
1001 * modify flag which controls if sequence colouring events are honoured by the
1002 * binding. Should be true for normal operation
1004 * @param finishedLoading
1007 public void setFinishedLoadingFromArchive(boolean finishedLoading)
1009 loadingFinished = finishedLoading;
1013 * Send the Chimera 'background solid <color>" command.
1016 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1020 public void setBackgroundColour(Color col)
1022 viewerCommandHistory(false);
1023 double normalise = 255D;
1024 final String command = "background solid " + col.getRed() / normalise
1025 + "," + col.getGreen() / normalise + "," + col.getBlue()
1027 viewer.sendChimeraCommand(command, false);
1028 viewerCommandHistory(true);
1032 * Ask Chimera to save its session to the given file. Returns true if
1033 * successful, else false.
1038 public boolean saveSession(String filepath)
1040 if (isChimeraRunning())
1042 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1044 if (reply.contains("Session written"))
1051 .error("Error saving Chimera session: " + reply.toString());
1058 * Ask Chimera to open a session file. Returns true if successful, else false.
1059 * The filename must have a .py extension for this command to work.
1064 public boolean openSession(String filepath)
1066 sendChimeraCommand("open " + filepath, true);
1067 // todo: test for failure - how?
1072 * Returns a list of chains mapped in this viewer. Note this list is not
1073 * currently scoped per structure.
1077 public List<String> getChainNames()
1079 List<String> names = new ArrayList<String>();
1080 String[][] allNames = getChains();
1081 if (allNames != null)
1083 for (String[] chainsForPdb : allNames)
1085 if (chainsForPdb != null)
1087 for (String chain : chainsForPdb)
1089 if (chain != null && !names.contains(chain))
1101 * Send a 'focus' command to Chimera to recentre the visible display
1103 public void focusView()
1105 sendChimeraCommand("focus", false);
1109 * Send a 'show' command for all atoms in the currently selected columns
1111 * TODO: pull up to abstract structure viewer interface
1115 public void highlightSelection(AlignmentViewPanel vp)
1117 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1119 AlignmentI alignment = vp.getAlignment();
1120 StructureSelectionManager sm = getSsm();
1121 for (SequenceI seq : alignment.getSequences())
1124 * convert selected columns into sequence positions
1126 int[] positions = new int[cols.size()];
1128 for (Integer col : cols)
1130 positions[i++] = seq.findPosition(col);
1132 sm.highlightStructure(this, seq, positions);
1137 * Constructs and send commands to Chimera to set attributes on residues for
1138 * features visible in Jalview
1142 public void sendFeaturesToViewer(AlignmentViewPanel avp)
1144 // TODO refactor as required to pull up to an interface
1145 AlignmentI alignment = avp.getAlignment();
1146 FeatureRenderer fr = getFeatureRenderer(avp);
1149 * fr is null if feature display is turned off
1156 String[] files = getPdbFile();
1162 StructureMappingcommandSet commandSet = ChimeraCommands
1163 .getSetAttributeCommandsForFeatures(getSsm(), files,
1164 getSequence(), fr, alignment);
1165 String[] commands = commandSet.commands;
1166 if (commands.length > 10)
1168 sendCommandsByFile(commands);
1172 for (String command : commands)
1174 sendAsynchronousCommand(command, null);
1180 * Write commands to a temporary file, and send a command to Chimera to open
1181 * the file as a commands script. For use when sending a large number of
1182 * separate commands would overload the REST interface mechanism.
1186 protected void sendCommandsByFile(String[] commands)
1190 File tmp = File.createTempFile("chim", ".com");
1192 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1193 for (String command : commands)
1195 out.println(command);
1199 String path = tmp.getAbsolutePath();
1200 sendAsynchronousCommand("open cmd:" + path, null);
1201 } catch (IOException e)
1204 .println("Sending commands to Chimera via file failed with "
1210 * Get Chimera residues which have the named attribute, find the mapped
1211 * positions in the Jalview sequence(s), and set as sequence features
1214 * @param alignmentPanel
1216 public void copyStructureAttributesToFeatures(String attName,
1217 AlignmentViewPanel alignmentPanel)
1219 // todo pull up to AAStructureBindingModel (and interface?)
1222 * ask Chimera to list residues with the attribute, reporting its value
1224 String cmd = "list residues spec ':*/" + attName + "' attr " + attName;
1225 List<String> residues = sendChimeraCommand(cmd, true);
1228 * TODO check if Jalview already has this feature name, if so give it a
1229 * distinguishing prefix e.g. chim_
1231 FeatureRenderer fr = alignmentPanel.getFeatureRenderer();
1232 fr.getFeaturesDisplayed().getVisibleFeatureCount();
1235 * Expect 0, 1 or more reply lines of the format (chi2 is attName):
1236 * residue id #0:5.A chi2 -155.000836316 index 5
1238 Map<String, Map<SequenceI, List<Integer>>> attsMap = new HashMap<String, Map<SequenceI, List<Integer>>>();
1239 for (String residue : residues)
1241 String[] tokens = residue.split(" ");
1242 if (tokens.length > 4)
1244 String atomSpec = tokens[2];
1245 String attValue = tokens[4];
1246 // TODO find mapping of atomspec to Jalview residue if any
1247 // build a map of { attValue, Map<SequenceI, List<Integer>> }
1248 // sort the integer lists
1249 // and create a feature for each contiguous integer range
1250 SequenceI seq = null; // mapped-to sequence
1251 int seqPos = 0; // mapped-to sequence position
1254 * record attribute value / sequence / sequence position
1256 Map<SequenceI, List<Integer>> seqMap = attsMap.get(attValue);
1259 seqMap = new HashMap<SequenceI, List<Integer>>();
1260 attsMap.put(attValue, seqMap);
1262 List<Integer> seqPositions = seqMap.get(seq);
1263 if (seqPositions == null)
1265 seqPositions = new ArrayList<Integer>();
1266 seqMap.put(seq, seqPositions);
1268 seqPositions.add(seqPos);
1273 * traverse values and sequences
1275 for (String val : attsMap.keySet())
1277 for (SequenceI seq : attsMap.get(val).keySet())
1279 List<Integer> positions = attsMap.get(val).get(seq);
1280 Collections.sort(positions);
1281 // TODO find reusable code that compacts the list
1282 List<int[]> ranges = null;// compacted list
1283 for (int[] range : ranges)
1285 float score = Float.NaN;
1288 score = Float.valueOf(val);
1289 } catch (NumberFormatException e)
1291 // was not a float value
1293 String featureGroup = getViewerFeatureGroup();
1294 SequenceFeature sf = new SequenceFeature(attName, val, range[0],
1295 range[1], score, featureGroup);
1296 // note: repeating the action shouldn't duplicate features
1297 seq.addSequenceFeature(sf);
1304 * Answers the feature group name to apply to features created in Jalview from
1305 * Chimera attributes
1309 protected String getViewerFeatureGroup()
1311 // todo pull up to interface