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.SequenceRenderer;
25 import jalview.api.structures.JalviewStructureDisplayI;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SearchResultMatchI;
31 import jalview.datamodel.SearchResultsI;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.httpserver.AbstractRequestHandler;
35 import jalview.io.DataSourceType;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ResidueProperties;
38 import jalview.structure.AtomSpec;
39 import jalview.structure.StructureMappingcommandSet;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.structures.models.AAStructureBindingModel;
42 import jalview.util.MessageManager;
44 import java.awt.Color;
46 import java.io.FileOutputStream;
47 import java.io.IOException;
48 import java.io.PrintWriter;
49 import java.net.BindException;
50 import java.util.ArrayList;
51 import java.util.BitSet;
52 import java.util.Collections;
53 import java.util.Hashtable;
54 import java.util.Iterator;
55 import java.util.LinkedHashMap;
56 import java.util.List;
59 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
60 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
61 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
62 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
64 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
66 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
68 // Chimera clause to exclude alternate locations in atom selection
69 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
71 private static final String COLOURING_CHIMERA = MessageManager
72 .getString("status.colouring_chimera");
74 private static final boolean debug = false;
76 private static final String PHOSPHORUS = "P";
78 private static final String ALPHACARBON = "CA";
80 private List<String> chainNames = new ArrayList<>();
82 private Hashtable<String, String> chainFile = new Hashtable<>();
85 * Object through which we talk to Chimera
87 private ChimeraManager viewer;
90 * Object which listens to Chimera notifications
92 private AbstractRequestHandler chimeraListener;
95 * set if chimera state is being restored from some source - instructs binding
96 * not to apply default display style when structure set is updated for first
99 private boolean loadingFromArchive = false;
102 * flag to indicate if the Chimera viewer should ignore sequence colouring
103 * events from the structure manager because the GUI is still setting up
105 private boolean loadingFinished = true;
108 * Map of ChimeraModel objects keyed by PDB full local file name
110 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
112 String lastHighlightCommand;
115 * incremented every time a load notification is successfully handled -
116 * lightweight mechanism for other threads to detect when they can start
117 * referring to new structures.
119 private long loadNotifiesHandled = 0;
121 private Thread chimeraMonitor;
124 * Open a PDB structure file in Chimera and set up mappings from Jalview.
126 * We check if the PDB model id is already loaded in Chimera, if so don't reopen
127 * it. This is the case if Chimera has opened a saved session file.
132 public boolean openFile(PDBEntry pe)
134 String file = pe.getFile();
137 List<ChimeraModel> modelsToMap = new ArrayList<>();
138 List<ChimeraModel> oldList = viewer.isChimeraX() ? new ArrayList<>()
139 : viewer.getModelList();
140 boolean alreadyOpen = false;
143 * If Chimera already has this model, don't reopen it, but do remap it.
145 for (ChimeraModel open : oldList)
147 if (open.getModelName().equals(pe.getId()))
150 modelsToMap.add(open);
155 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
156 * the model name(s) added by Chimera.
160 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
161 if (viewer.isChimeraX())
164 * ChimeraX hack: force chimera model name to pdbId
166 int modelNumber = chimeraMaps.size() + 1;
167 String command = "setattr #" + modelNumber + " models name "
169 sendChimeraCommand(command, false);
170 modelsToMap.add(new ChimeraModel(pe.getId(), ModelType.PDB_MODEL,
176 * Chimera: query for actual models and find the one with
177 * matching model name - set in viewer.openModel()
179 List<ChimeraModel> newList = viewer.getModelList();
180 // JAL-1728 newList.removeAll(oldList) does not work
181 for (ChimeraModel cm : newList)
183 if (cm.getModelName().equals(pe.getId()))
191 chimeraMaps.put(file, modelsToMap);
193 if (getSsm() != null)
195 getSsm().addStructureViewerListener(this);
198 } catch (Exception q)
200 log("Exception when trying to open model " + file + "\n"
215 public JalviewChimeraBinding(StructureSelectionManager ssm,
216 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
217 DataSourceType protocol)
219 super(ssm, pdbentry, sequenceIs, protocol);
220 viewer = new ChimeraManager(new StructureManager(true));
224 * Starts a thread that waits for the Chimera process to finish, so that we can
225 * then close the associated resources. This avoids leaving orphaned Chimera
226 * viewer panels in Jalview if the user closes Chimera.
228 protected void startChimeraProcessMonitor()
230 final Process p = viewer.getChimeraProcess();
231 chimeraMonitor = new Thread(new Runnable()
240 JalviewStructureDisplayI display = getViewer();
243 display.closeViewer(false);
245 } catch (InterruptedException e)
247 // exit thread if Chimera Viewer is closed in Jalview
251 chimeraMonitor.start();
255 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
258 public void startChimeraListener()
262 chimeraListener = new ChimeraListener(this);
263 viewer.startListening(chimeraListener.getUri());
264 } catch (BindException e)
267 "Failed to start Chimera listener: " + e.getMessage());
272 * Tells Chimera to display only the specified chains
276 public void showChains(List<String> toshow)
279 * Construct a chimera command like
281 * ~display #*;~ribbon #*;ribbon :.A,:.B
283 StringBuilder cmd = new StringBuilder(64);
284 boolean first = true;
285 for (String chain : toshow)
287 int modelNumber = getModelNoForChain(chain);
288 String showChainCmd = modelNumber == -1 ? ""
289 : modelNumber + ":." + chain.split(":")[1];
294 cmd.append(showChainCmd);
299 * could append ";focus" to this command to resize the display to fill the
300 * window, but it looks more helpful not to (easier to relate chains to the
303 final String command = "~display #*; ~ribbon #*; ribbon :"
305 sendChimeraCommand(command, false);
309 * Close down the Jalview viewer and listener, and (optionally) the associated
312 public void closeViewer(boolean closeChimera)
314 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
317 viewer.exitChimera();
319 if (this.chimeraListener != null)
321 chimeraListener.shutdown();
322 chimeraListener = null;
326 if (chimeraMonitor != null)
328 chimeraMonitor.interrupt();
330 releaseUIResources();
334 public void colourByChain()
336 colourBySequence = false;
337 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
341 * Constructs and sends a Chimera command to colour by charge
343 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
344 * <li>Lysine and Arginine (positive charge) blue</li>
345 * <li>Cysteine - yellow</li>
346 * <li>all others - white</li>
350 public void colourByCharge()
352 colourBySequence = false;
353 String command = viewer.isChimeraX()
354 ? "color white;color :ASP,GLU red;color :LYS,ARG blue;color :CYS yellow"
355 : "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
356 sendAsynchronousCommand(command, COLOURING_CHIMERA);
363 public String superposeStructures(AlignmentI[] _alignment,
364 int[] _refStructure, HiddenColumns[] _hiddenCols)
366 StringBuilder allComs = new StringBuilder(128);
367 String[] files = getStructureFiles();
369 if (!waitForFileLoad(files))
375 StringBuilder selectioncom = new StringBuilder(256);
376 boolean chimeraX = viewer.isChimeraX();
377 for (int a = 0; a < _alignment.length; a++)
379 int refStructure = _refStructure[a];
380 AlignmentI alignment = _alignment[a];
381 HiddenColumns hiddenCols = _hiddenCols[a];
383 if (refStructure >= files.length)
385 System.err.println("Ignoring invalid reference structure value "
391 * 'matched' bit i will be set for visible alignment columns i where
392 * all sequences have a residue with a mapping to the PDB structure
394 BitSet matched = new BitSet();
395 for (int m = 0; m < alignment.getWidth(); m++)
397 if (hiddenCols == null || hiddenCols.isVisible(m))
403 SuperposeData[] structures = new SuperposeData[files.length];
404 for (int f = 0; f < files.length; f++)
406 structures[f] = new SuperposeData(alignment.getWidth());
410 * Calculate the superposable alignment columns ('matched'), and the
411 * corresponding structure residue positions (structures.pdbResNo)
413 int candidateRefStructure = findSuperposableResidues(alignment,
414 matched, structures);
415 if (refStructure < 0)
418 * If no reference structure was specified, pick the first one that has
419 * a mapping in the alignment
421 refStructure = candidateRefStructure;
424 int nmatched = matched.cardinality();
427 return MessageManager.formatMessage("label.insufficient_residues",
432 * Generate select statements to select regions to superimpose structures
434 String[] selcom = new String[files.length];
435 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
437 final int modelNo = pdbfnum + (chimeraX ? 1 : 0);
438 // todo correct resolution to model number
439 String chainCd = "." + structures[pdbfnum].chain;
442 StringBuilder molsel = new StringBuilder();
445 molsel.append("/" + structures[pdbfnum].chain + ":");
448 int nextColumnMatch = matched.nextSetBit(0);
449 while (nextColumnMatch != -1)
451 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
452 if (lpos != pdbResNum - 1)
455 * discontiguous - append last residue now
459 molsel.append(String.valueOf(lpos));
462 molsel.append(chainCd);
471 * extending a contiguous run
476 * start the range selection
478 molsel.append(String.valueOf(lpos));
484 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
488 * and terminate final selection
492 molsel.append(String.valueOf(lpos));
495 molsel.append(chainCd);
498 if (molsel.length() > 1)
500 selcom[pdbfnum] = molsel.toString();
501 selectioncom.append("#").append(String.valueOf(modelNo));
504 selectioncom.append(":");
506 selectioncom.append(selcom[pdbfnum]);
507 // selectioncom.append(" ");
508 if (pdbfnum < files.length - 1)
510 selectioncom.append("|");
515 selcom[pdbfnum] = null;
519 StringBuilder command = new StringBuilder(256);
520 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
522 final int modelNo = pdbfnum + (chimeraX ? 1 : 0);
523 if (pdbfnum == refStructure || selcom[pdbfnum] == null
524 || selcom[refStructure] == null)
528 if (command.length() > 0)
534 * Form Chimera match command, from the 'new' structure to the
535 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
537 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
540 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
542 command.append(chimeraX ? "align " : "match ");
543 command.append(getModelSpec(modelNo));
548 command.append(selcom[pdbfnum]);
549 command.append("@").append(
550 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
551 // JAL-1757 exclude alternate CA locations - ChimeraX syntax tbd
554 command.append(NO_ALTLOCS);
556 command.append(chimeraX ? " toAtoms " : " ")
557 .append(getModelSpec(refStructure + (chimeraX ? 1 : 0)));
562 command.append(selcom[refStructure]);
563 command.append("@").append(
564 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
567 command.append(NO_ALTLOCS);
570 if (selectioncom.length() > 0)
574 System.out.println("Select regions:\n" + selectioncom.toString());
576 "Superimpose command(s):\n" + command.toString());
578 // allComs.append("~display all; ");
581 // allComs.append("show ").append(selectioncom.toString())
582 // .append(" pbonds");
586 // allComs.append("chain @CA|P; ribbon ");
587 // allComs.append(selectioncom.toString());
589 if (allComs.length() > 0) {
592 allComs.append(command.toString());
597 if (selectioncom.length() > 0)
599 // TODO: visually distinguish regions that were superposed
600 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
602 selectioncom.setLength(selectioncom.length() - 1);
606 System.out.println("Select regions:\n" + selectioncom.toString());
608 allComs.append(";~display all; ");
611 allComs.append("show @CA|P pbonds; show ")
612 .append(selectioncom.toString()).append(" ribbons; view");
616 allComs.append("chain @CA|P; ribbon ; focus");
617 allComs.append(selectioncom.toString());
619 // allComs.append("; ~display all; chain @CA|P; ribbon ")
620 // .append(selectioncom.toString()).append("; focus");
621 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
623 for (String reply : chimeraReplies)
625 if (reply.toLowerCase().contains("unequal numbers of atoms"))
635 * Helper method to construct model spec in Chimera format:
637 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
638 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
640 * Note for now we only ever choose the first of multiple models. This
641 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
642 * future if there is a need to select specific sub-models.
647 protected String getModelSpec(int pdbfnum)
649 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
651 return "#" + pdbfnum; // temp hack for ChimeraX
655 * For now, the test for having sub-models is whether multiple Chimera
656 * models are mapped for the PDB file; the models are returned as a response
657 * to the Chimera command 'list models type molecule', see
658 * ChimeraManager.getModelList().
660 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
661 boolean hasSubModels = maps != null && maps.size() > 1;
662 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
666 * Launch Chimera, unless an instance linked to this object is already
667 * running. Returns true if Chimera is successfully launched, or already
668 * running, else false.
672 public boolean launchChimera()
674 if (viewer.isChimeraLaunched())
679 boolean launched = viewer
680 .launchChimera(StructureManager.getChimeraPaths());
683 startChimeraProcessMonitor();
687 log("Failed to launch Chimera!");
693 * Answers true if the Chimera process is still running, false if ended or not
698 public boolean isChimeraRunning()
700 return viewer.isChimeraLaunched();
704 * Send a command to Chimera, and optionally log and return any responses.
706 * Does nothing, and returns null, if the command is the same as the last one
712 public List<String> sendChimeraCommand(final String command,
717 // ? thread running after viewer shut down
720 List<String> reply = null;
721 viewerCommandHistory(false);
722 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
724 // trim command or it may never find a match in the replyLog!!
725 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
732 log("Response from command ('" + command + "') was:\n"
737 viewerCommandHistory(true);
743 * Send a Chimera command asynchronously in a new thread. If the progress
744 * message is not null, display this message while the command is executing.
749 protected abstract void sendAsynchronousCommand(String command,
753 * Sends a set of colour commands to the structure viewer
755 * @param colourBySequenceCommands
758 protected void colourBySequence(
759 StructureMappingcommandSet[] colourBySequenceCommands)
761 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
763 for (String command : cpdbbyseq.commands)
765 sendAsynchronousCommand(command, COLOURING_CHIMERA);
777 protected StructureMappingcommandSet[] getColourBySequenceCommands(
778 String[] files, SequenceRenderer sr, AlignmentViewPanel viewPanel)
780 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
781 getSequence(), sr, viewPanel, viewer.isChimeraX());
787 protected void executeWhenReady(String command)
790 sendChimeraCommand(command, false);
794 private void waitForChimera()
796 while (viewer != null && viewer.isBusy())
801 } catch (InterruptedException q)
807 // End StructureListener
808 // //////////////////////////
811 * instruct the Jalview binding to update the pdbentries vector if necessary
812 * prior to matching the viewer's contents to the list of structure files
813 * Jalview knows about.
815 public abstract void refreshPdbEntries();
818 * map between index of model filename returned from getPdbFile and the first
819 * index of models from this file in the viewer. Note - this is not trimmed -
820 * use getPdbFile to get number of unique models.
822 private int _modelFileNameMap[];
824 // ////////////////////////////////
825 // /StructureListener
827 public synchronized String[] getStructureFiles()
831 return new String[0];
834 return chimeraMaps.keySet()
835 .toArray(modelFileNames = new String[chimeraMaps.size()]);
839 * Construct and send a command to highlight zero, one or more atoms. We do this
840 * by sending an "rlabel" command to show the residue label at that position.
843 public void highlightAtoms(List<AtomSpec> atoms)
845 if (atoms == null || atoms.size() == 0)
850 boolean forChimeraX = viewer.isChimeraX();
851 StringBuilder cmd = new StringBuilder(128);
852 boolean first = true;
853 boolean found = false;
855 for (AtomSpec atom : atoms)
857 int pdbResNum = atom.getPdbResNum();
858 String chain = atom.getChain();
859 String pdbfile = atom.getPdbFile();
860 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
861 if (cms != null && !cms.isEmpty())
865 cmd.append(forChimeraX ? "label #" : "rlabel #");
874 cmd.append(cms.get(0).getModelNumber())
875 .append("/").append(chain).append(":").append(pdbResNum);
879 cmd.append(cms.get(0).getModelNumber())
880 .append(":").append(pdbResNum);
881 if (!chain.equals(" ") && !forChimeraX)
883 cmd.append(".").append(chain);
889 String command = cmd.toString();
892 * avoid repeated commands for the same residue
894 if (command.equals(lastHighlightCommand))
900 * unshow the label for the previous residue
902 if (lastHighlightCommand != null)
904 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
908 viewer.sendChimeraCommand(command, false);
910 this.lastHighlightCommand = command;
914 * Query Chimera for its current selection, and highlight it on the alignment
916 public void highlightChimeraSelection()
919 * Ask Chimera for its current selection
921 List<String> selection = viewer.getSelectedResidueSpecs();
924 * Parse model number, residue and chain for each selected position,
925 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
927 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
931 * Broadcast the selection (which may be empty, if the user just cleared all
934 getSsm().mouseOverStructure(atomSpecs);
938 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
939 * corresponding residues (if any) in Jalview
941 * @param structureSelection
944 protected List<AtomSpec> convertStructureResiduesToAlignment(
945 List<String> structureSelection)
947 boolean chimeraX = viewer.isChimeraX();
948 List<AtomSpec> atomSpecs = new ArrayList<>();
949 for (String atomSpec : structureSelection)
953 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
954 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
955 spec.setPdbFile(pdbfilename);
957 } catch (IllegalArgumentException e)
959 System.err.println("Failed to parse atomspec: " + atomSpec);
969 protected String getPdbFileForModel(int modelId)
972 * Work out the pdbfilename from the model number
974 String pdbfilename = modelFileNames[0];
975 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
977 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
979 if (cm.getModelNumber() == modelId)
981 pdbfilename = pdbfile;
989 private void log(String message)
991 System.err.println("## Chimera log: " + message);
994 private void viewerCommandHistory(boolean enable)
996 // log("(Not yet implemented) History "
997 // + ((debug || enable) ? "on" : "off"));
1000 public long getLoadNotifiesHandled()
1002 return loadNotifiesHandled;
1006 public void setJalviewColourScheme(ColourSchemeI cs)
1008 colourBySequence = false;
1015 viewerCommandHistory(false);
1016 StringBuilder command = new StringBuilder(128);
1018 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
1022 * concatenate colour commands, one per residue symbol
1023 * Chimera format: color 0.000000,0.372549,0.627451 ::VAL
1024 * ChimeraX format: color :VAL rgb(73,73,182)
1026 boolean chimeraX = viewer.isChimeraX();
1027 for (String resName : residueSet)
1029 char res = resName.length() == 3
1030 ? ResidueProperties.getSingleCharacterCode(resName)
1031 : resName.charAt(0);
1032 Color col = cs.findColour(res, 0, null, null, 0f);
1033 command.append("color ");
1034 String colorSpec = getRgbDescriptor(col, chimeraX);
1037 command.append(":").append(resName).append(" ").append(colorSpec);
1041 command.append(colorSpec).append(" ::").append(resName);
1043 command.append(";");
1046 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
1047 viewerCommandHistory(true);
1051 * called when the binding thinks the UI needs to be refreshed after a Chimera
1052 * state change. this could be because structures were loaded, or because an
1053 * error has occurred.
1055 public abstract void refreshGUI();
1058 public void setLoadingFromArchive(boolean loadingFromArchive)
1060 this.loadingFromArchive = loadingFromArchive;
1065 * @return true if Chimeral is still restoring state or loading is still going
1066 * on (see setFinsihedLoadingFromArchive)
1069 public boolean isLoadingFromArchive()
1071 return loadingFromArchive && !loadingFinished;
1075 * modify flag which controls if sequence colouring events are honoured by the
1076 * binding. Should be true for normal operation
1078 * @param finishedLoading
1081 public void setFinishedLoadingFromArchive(boolean finishedLoading)
1083 loadingFinished = finishedLoading;
1087 * Send the Chimera 'background solid <color>" command.
1090 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1095 public void setBackgroundColour(Color col)
1097 viewerCommandHistory(false);
1098 String command = "set bgColor "
1099 + getRgbDescriptor(col, viewer.isChimeraX());
1100 viewer.sendChimeraCommand(command, false);
1101 viewerCommandHistory(true);
1105 * Answers the Chimera/X format for RGB values of the given colour.
1108 * Chimera: r,g,b with values scaled [0=1]
1109 * ChimeraX: rgb(r,g,b) with values scaled 0-255
1116 private static String getRgbDescriptor(Color col, boolean chimeraX)
1120 return String.format("rgb(%d,%d,%d)", col.getRed(), col.getGreen(),
1125 double scale = 255D;
1126 return String.format("%f,%f,%f", col.getRed() / scale,
1127 col.getGreen() / scale, col.getBlue() / scale);
1132 * Ask Chimera to save its session to the given file. Returns true if
1133 * successful, else false.
1138 public boolean saveSession(String filepath)
1140 if (isChimeraRunning())
1142 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1144 if (reply.contains("Session written"))
1151 .error("Error saving Chimera session: " + reply.toString());
1158 * Ask Chimera to open a session file. Returns true if successful, else false.
1159 * The filename must have a .py extension for this command to work.
1164 public boolean openSession(String filepath)
1166 sendChimeraCommand("open " + filepath, true);
1167 // todo: test for failure - how?
1172 * Returns a list of chains mapped in this viewer. Note this list is not
1173 * currently scoped per structure.
1178 public List<String> getChainNames()
1184 * Send a 'focus' command to Chimera to recentre the visible display
1186 public void focusView()
1188 sendChimeraCommand(viewer.isChimeraX() ? "view" : "focus", false);
1192 * Send a 'show' command for all atoms in the currently selected columns
1194 * TODO: pull up to abstract structure viewer interface
1198 public void highlightSelection(AlignmentViewPanel vp)
1200 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1202 AlignmentI alignment = vp.getAlignment();
1203 StructureSelectionManager sm = getSsm();
1204 for (SequenceI seq : alignment.getSequences())
1207 * convert selected columns into sequence positions
1209 int[] positions = new int[cols.size()];
1211 for (Integer col : cols)
1213 positions[i++] = seq.findPosition(col);
1215 sm.highlightStructure(this, seq, positions);
1220 * Constructs and send commands to Chimera to set attributes on residues for
1221 * features visible in Jalview
1226 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1228 // TODO refactor as required to pull up to an interface
1229 AlignmentI alignment = avp.getAlignment();
1231 String[] files = getStructureFiles();
1237 StructureMappingcommandSet commandSet = ChimeraCommands
1238 .getSetAttributeCommandsForFeatures(getSsm(), files,
1239 getSequence(), avp, viewer.isChimeraX());
1240 String[] commands = commandSet.commands;
1241 if (commands.length > 10)
1243 sendCommandsByFile(commands);
1247 for (String command : commands)
1249 sendAsynchronousCommand(command, null);
1252 return commands.length;
1256 * Write commands to a temporary file, and send a command to Chimera to open the
1257 * file as a commands script. For use when sending a large number of separate
1258 * commands would overload the REST interface mechanism.
1262 protected void sendCommandsByFile(String[] commands)
1264 boolean toChimeraX = viewer.isChimeraX();
1267 File tmp = File.createTempFile("chim", toChimeraX ? ".cxc" : ".com");
1269 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1270 for (String command : commands)
1272 out.println(command);
1276 String path = tmp.getAbsolutePath();
1277 String command = "open " + (toChimeraX ? "" : "cmd:") + path;
1278 sendAsynchronousCommand(command, null);
1279 } catch (IOException e)
1281 System.err.println("Sending commands to Chimera via file failed with "
1287 * Get Chimera residues which have the named attribute, find the mapped
1288 * positions in the Jalview sequence(s), and set as sequence features
1291 * @param alignmentPanel
1293 public void copyStructureAttributesToFeatures(String attName,
1294 AlignmentViewPanel alignmentPanel)
1296 // todo pull up to AAStructureBindingModel (and interface?)
1299 * ask Chimera to list residues with the attribute, reporting its value
1301 // this alternative command
1302 // list residues spec ':*/attName' attr attName
1303 // doesn't report 'None' values (which is good), but
1304 // fails for 'average.bfactor' (which is bad):
1306 String cmd = "list residues attr '" + attName + "'";
1307 List<String> residues = sendChimeraCommand(cmd, true);
1309 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1312 alignmentPanel.getFeatureRenderer().featuresAdded();
1317 * Create features in Jalview for the given attribute name and structure
1321 * The residue list should be 0, 1 or more reply lines of the format:
1322 * residue id #0:5.A isHelix -155.000836316 index 5
1324 * residue id #0:6.A isHelix None
1331 protected boolean createFeaturesForAttributes(String attName,
1332 List<String> residues)
1334 boolean featureAdded = false;
1335 String featureGroup = getViewerFeatureGroup();
1336 boolean chimeraX = viewer.isChimeraX();
1338 for (String residue : residues)
1340 AtomSpec spec = null;
1341 String[] tokens = residue.split(" ");
1342 if (tokens.length < 5)
1346 String atomSpec = tokens[2];
1347 String attValue = tokens[4];
1350 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1352 if ("None".equalsIgnoreCase(attValue)
1353 || "False".equalsIgnoreCase(attValue))
1360 spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
1361 } catch (IllegalArgumentException e)
1363 System.err.println("Problem parsing atomspec " + atomSpec);
1367 String chainId = spec.getChain();
1368 String description = attValue;
1369 float score = Float.NaN;
1372 score = Float.valueOf(attValue);
1373 description = chainId;
1374 } catch (NumberFormatException e)
1376 // was not a float value
1379 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1380 spec.setPdbFile(pdbFile);
1382 List<AtomSpec> atoms = Collections.singletonList(spec);
1385 * locate the mapped position in the alignment (if any)
1387 SearchResultsI sr = getSsm()
1388 .findAlignmentPositionsForStructurePositions(atoms);
1391 * expect one matched alignment position, or none
1392 * (if the structure position is not mapped)
1394 for (SearchResultMatchI m : sr.getResults())
1396 SequenceI seq = m.getSequence();
1397 int start = m.getStart();
1398 int end = m.getEnd();
1399 SequenceFeature sf = new SequenceFeature(attName, description,
1400 start, end, score, featureGroup);
1401 // todo: should SequenceFeature have an explicit property for chain?
1402 // note: repeating the action shouldn't duplicate features
1403 featureAdded |= seq.addSequenceFeature(sf);
1406 return featureAdded;
1410 * Answers the feature group name to apply to features created in Jalview from
1411 * Chimera attributes
1415 protected String getViewerFeatureGroup()
1417 // todo pull up to interface
1418 return CHIMERA_FEATURE_GROUP;
1421 public Hashtable<String, String> getChainFile()
1426 public List<ChimeraModel> getChimeraModelByChain(String chain)
1428 return chimeraMaps.get(chainFile.get(chain));
1431 public int getModelNoForChain(String chain)
1433 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1434 if (foundModels != null && !foundModels.isEmpty())
1436 return foundModels.get(0).getModelNumber();
1442 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
1443 * any which were added from Jalview
1447 public List<String> getChimeraAttributes()
1449 List<String> atts = viewer.getAttrList();
1450 Iterator<String> it = atts.iterator();
1451 while (it.hasNext())
1453 if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
1456 * attribute added from Jalview - exclude it