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.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.structures.JalviewStructureDisplayI;
27 import jalview.bin.Cache;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SearchResultMatchI;
32 import jalview.datamodel.SearchResultsI;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceI;
35 import jalview.datamodel.VisibleContigsIterator;
36 import jalview.httpserver.AbstractRequestHandler;
37 import jalview.io.DataSourceType;
38 import jalview.schemes.ColourSchemeI;
39 import jalview.schemes.ResidueProperties;
40 import jalview.structure.AtomSpec;
41 import jalview.structure.StructureMapping;
42 import jalview.structure.StructureMappingcommandSet;
43 import jalview.structure.StructureSelectionManager;
44 import jalview.structures.models.AAStructureBindingModel;
45 import jalview.util.MessageManager;
47 import java.awt.Color;
49 import java.io.FileOutputStream;
50 import java.io.IOException;
51 import java.io.PrintWriter;
52 import java.net.BindException;
53 import java.util.ArrayList;
54 import java.util.BitSet;
55 import java.util.Collections;
56 import java.util.Hashtable;
57 import java.util.LinkedHashMap;
58 import java.util.List;
61 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
62 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
63 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
64 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
66 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
68 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
70 // Chimera clause to exclude alternate locations in atom selection
71 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
73 private static final String COLOURING_CHIMERA = MessageManager
74 .getString("status.colouring_chimera");
76 private static final boolean debug = false;
78 private static final String PHOSPHORUS = "P";
80 private static final String ALPHACARBON = "CA";
82 private List<String> chainNames = new ArrayList<>();
84 private Hashtable<String, String> chainFile = new Hashtable<>();
87 * Object through which we talk to Chimera
89 private ChimeraManager viewer;
92 * Object which listens to Chimera notifications
94 private AbstractRequestHandler chimeraListener;
97 * set if chimera state is being restored from some source - instructs binding
98 * not to apply default display style when structure set is updated for first
101 private boolean loadingFromArchive = false;
104 * flag to indicate if the Chimera viewer should ignore sequence colouring
105 * events from the structure manager because the GUI is still setting up
107 private boolean loadingFinished = true;
110 * Map of ChimeraModel objects keyed by PDB full local file name
112 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
114 String lastHighlightCommand;
117 * incremented every time a load notification is successfully handled -
118 * lightweight mechanism for other threads to detect when they can start
119 * referring to new structures.
121 private long loadNotifiesHandled = 0;
123 private Thread chimeraMonitor;
126 * Open a PDB structure file in Chimera and set up mappings from Jalview.
128 * We check if the PDB model id is already loaded in Chimera, if so don't
129 * reopen it. This is the case if Chimera has opened a saved session file.
134 public boolean openFile(PDBEntry pe)
136 String file = pe.getFile();
139 List<ChimeraModel> modelsToMap = new ArrayList<>();
140 List<ChimeraModel> oldList = viewer.getModelList();
141 boolean alreadyOpen = false;
144 * If Chimera already has this model, don't reopen it, but do remap it.
146 for (ChimeraModel open : oldList)
148 if (open.getModelName().equals(pe.getId()))
151 modelsToMap.add(open);
156 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
157 * the model name(s) added by Chimera.
161 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
162 List<ChimeraModel> newList = viewer.getModelList();
163 // JAL-1728 newList.removeAll(oldList) does not work
164 for (ChimeraModel cm : newList)
166 if (cm.getModelName().equals(pe.getId()))
173 chimeraMaps.put(file, modelsToMap);
175 if (getSsm() != null)
177 getSsm().addStructureViewerListener(this);
180 } catch (Exception q)
182 log("Exception when trying to open model " + file + "\n"
197 public JalviewChimeraBinding(StructureSelectionManager ssm,
198 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
199 DataSourceType protocol)
201 super(ssm, pdbentry, sequenceIs, protocol);
202 viewer = new ChimeraManager(new StructureManager(true));
206 * Starts a thread that waits for the Chimera process to finish, so that we
207 * can then close the associated resources. This avoids leaving orphaned
208 * Chimera viewer panels in Jalview if the user closes Chimera.
210 protected void startChimeraProcessMonitor()
212 final Process p = viewer.getChimeraProcess();
213 chimeraMonitor = new Thread(new Runnable()
222 JalviewStructureDisplayI display = getViewer();
225 display.closeViewer(false);
227 } catch (InterruptedException e)
229 // exit thread if Chimera Viewer is closed in Jalview
233 chimeraMonitor.start();
237 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
238 * it to start listening
240 public void startChimeraListener()
244 chimeraListener = new ChimeraListener(this);
245 viewer.startListening(chimeraListener.getUri());
246 } catch (BindException e)
249 "Failed to start Chimera listener: " + e.getMessage());
254 * Tells Chimera to display only the specified chains
258 public void showChains(List<String> toshow)
261 * Construct a chimera command like
263 * ~display #*;~ribbon #*;ribbon :.A,:.B
265 StringBuilder cmd = new StringBuilder(64);
266 boolean first = true;
267 for (String chain : toshow)
269 int modelNumber = getModelNoForChain(chain);
270 String showChainCmd = modelNumber == -1 ? ""
271 : modelNumber + ":." + chain.split(":")[1];
276 cmd.append(showChainCmd);
281 * could append ";focus" to this command to resize the display to fill the
282 * window, but it looks more helpful not to (easier to relate chains to the
285 final String command = "~display #*; ~ribbon #*; ribbon :"
287 sendChimeraCommand(command, false);
291 * Close down the Jalview viewer and listener, and (optionally) the associated
294 public void closeViewer(boolean closeChimera)
296 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
299 viewer.exitChimera();
301 if (this.chimeraListener != null)
303 chimeraListener.shutdown();
304 chimeraListener = null;
308 if (chimeraMonitor != null)
310 chimeraMonitor.interrupt();
312 releaseUIResources();
316 public void colourByChain()
318 colourBySequence = false;
319 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
323 * Constructs and sends a Chimera command to colour by charge
325 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
326 * <li>Lysine and Arginine (positive charge) blue</li>
327 * <li>Cysteine - yellow</li>
328 * <li>all others - white</li>
332 public void colourByCharge()
334 colourBySequence = false;
335 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
336 sendAsynchronousCommand(command, COLOURING_CHIMERA);
343 public String superposeStructures(AlignmentI[] _alignment,
344 int[] _refStructure, HiddenColumns[] _hiddenCols)
346 StringBuilder allComs = new StringBuilder(128);
347 String[] files = getStructureFiles();
349 if (!waitForFileLoad(files))
355 StringBuilder selectioncom = new StringBuilder(256);
356 for (int a = 0; a < _alignment.length; a++)
358 int refStructure = _refStructure[a];
359 AlignmentI alignment = _alignment[a];
360 HiddenColumns hiddenCols = _hiddenCols[a];
362 if (refStructure >= files.length)
364 System.err.println("Ignoring invalid reference structure value "
370 * 'matched' bit i will be set for visible alignment columns i where
371 * all sequences have a residue with a mapping to the PDB structure
373 BitSet matched = new BitSet();
374 for (int m = 0; m < alignment.getWidth(); m++)
376 if (hiddenCols == null || hiddenCols.isVisible(m))
382 SuperposeData[] structures = new SuperposeData[files.length];
383 for (int f = 0; f < files.length; f++)
385 structures[f] = new SuperposeData(alignment.getWidth());
389 * Calculate the superposable alignment columns ('matched'), and the
390 * corresponding structure residue positions (structures.pdbResNo)
392 int candidateRefStructure = findSuperposableResidues(alignment,
393 matched, structures);
394 if (refStructure < 0)
397 * If no reference structure was specified, pick the first one that has
398 * a mapping in the alignment
400 refStructure = candidateRefStructure;
403 int nmatched = matched.cardinality();
406 return MessageManager.formatMessage("label.insufficient_residues",
411 * Generate select statements to select regions to superimpose structures
413 String[] selcom = new String[files.length];
414 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
416 String chainCd = "." + structures[pdbfnum].chain;
419 StringBuilder molsel = new StringBuilder();
421 int nextColumnMatch = matched.nextSetBit(0);
422 while (nextColumnMatch != -1)
424 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
425 if (lpos != pdbResNum - 1)
428 * discontiguous - append last residue now
432 molsel.append(String.valueOf(lpos));
433 molsel.append(chainCd);
441 * extending a contiguous run
446 * start the range selection
448 molsel.append(String.valueOf(lpos));
454 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
458 * and terminate final selection
462 molsel.append(String.valueOf(lpos));
463 molsel.append(chainCd);
465 if (molsel.length() > 1)
467 selcom[pdbfnum] = molsel.toString();
468 selectioncom.append("#").append(String.valueOf(pdbfnum))
470 selectioncom.append(selcom[pdbfnum]);
471 selectioncom.append(" ");
472 if (pdbfnum < files.length - 1)
474 selectioncom.append("| ");
479 selcom[pdbfnum] = null;
483 StringBuilder command = new StringBuilder(256);
484 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
486 if (pdbfnum == refStructure || selcom[pdbfnum] == null
487 || selcom[refStructure] == null)
491 if (command.length() > 0)
497 * Form Chimera match command, from the 'new' structure to the
498 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
500 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
503 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
505 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
506 command.append(selcom[pdbfnum]);
507 command.append("@").append(
508 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
509 // JAL-1757 exclude alternate CA locations
510 command.append(NO_ALTLOCS);
511 command.append(" ").append(getModelSpec(refStructure)).append(":");
512 command.append(selcom[refStructure]);
513 command.append("@").append(
514 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
515 command.append(NO_ALTLOCS);
517 if (selectioncom.length() > 0)
521 System.out.println("Select regions:\n" + selectioncom.toString());
523 "Superimpose command(s):\n" + command.toString());
525 allComs/*.append("~display all; chain @CA|P; ribbon ")
526 .append(selectioncom.toString())*/
527 .append(";" + command.toString());
532 if (selectioncom.length() > 0)
534 // TODO: visually distinguish regions that were superposed
535 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
537 selectioncom.setLength(selectioncom.length() - 1);
541 System.out.println("Select regions:\n" + selectioncom.toString());
543 allComs.append("; ~display "); // all");
544 if (!isShowAlignmentOnly())
546 allComs.append("; ribbon; chain @CA|P");
550 allComs.append("; ~ribbon");
552 allComs.append("; ribbon ").append(selectioncom.toString())
554 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
556 for (String reply : chimeraReplies)
558 String lowerCase = reply.toLowerCase();
559 if (lowerCase.contains("unequal numbers of atoms")
560 || lowerCase.contains("at least"))
570 * Helper method to construct model spec in Chimera format:
572 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
573 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
575 * Note for now we only ever choose the first of multiple models. This
576 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
577 * future if there is a need to select specific sub-models.
582 protected String getModelSpec(int pdbfnum)
584 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
590 * For now, the test for having sub-models is whether multiple Chimera
591 * models are mapped for the PDB file; the models are returned as a response
592 * to the Chimera command 'list models type molecule', see
593 * ChimeraManager.getModelList().
595 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
596 boolean hasSubModels = maps != null && maps.size() > 1;
597 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
601 * Launch Chimera, unless an instance linked to this object is already
602 * running. Returns true if Chimera is successfully launched, or already
603 * running, else false.
607 public boolean launchChimera()
609 if (viewer.isChimeraLaunched())
614 boolean launched = viewer
615 .launchChimera(StructureManager.getChimeraPaths());
618 startChimeraProcessMonitor();
622 log("Failed to launch Chimera!");
628 * Answers true if the Chimera process is still running, false if ended or not
633 public boolean isChimeraRunning()
635 return viewer.isChimeraLaunched();
639 * Send a command to Chimera, and optionally log and return any responses.
641 * Does nothing, and returns null, if the command is the same as the last one
647 public List<String> sendChimeraCommand(final String command,
652 // ? thread running after viewer shut down
655 List<String> reply = null;
656 viewerCommandHistory(false);
657 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
659 // trim command or it may never find a match in the replyLog!!
660 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
667 log("Response from command ('" + command + "') was:\n"
672 viewerCommandHistory(true);
678 * Send a Chimera command asynchronously in a new thread. If the progress
679 * message is not null, display this message while the command is executing.
684 protected abstract void sendAsynchronousCommand(String command,
688 * Sends a set of colour commands to the structure viewer
690 * @param colourBySequenceCommands
693 protected void colourBySequence(
694 StructureMappingcommandSet[] colourBySequenceCommands)
696 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
698 for (String command : cpdbbyseq.commands)
700 sendAsynchronousCommand(command, COLOURING_CHIMERA);
712 protected StructureMappingcommandSet[] getColourBySequenceCommands(
713 String[] files, SequenceRenderer sr, AlignmentViewPanel viewPanel)
715 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
716 getSequence(), sr, viewPanel);
722 protected void executeWhenReady(String command)
725 sendChimeraCommand(command, false);
729 private void waitForChimera()
731 while (viewer != null && viewer.isBusy())
736 } catch (InterruptedException q)
742 // End StructureListener
743 // //////////////////////////
746 * instruct the Jalview binding to update the pdbentries vector if necessary
747 * prior to matching the viewer's contents to the list of structure files
748 * Jalview knows about.
750 public abstract void refreshPdbEntries();
753 * map between index of model filename returned from getPdbFile and the first
754 * index of models from this file in the viewer. Note - this is not trimmed -
755 * use getPdbFile to get number of unique models.
757 private int _modelFileNameMap[];
759 // ////////////////////////////////
760 // /StructureListener
762 public synchronized String[] getStructureFiles()
766 return new String[0];
769 return chimeraMaps.keySet()
770 .toArray(modelFileNames = new String[chimeraMaps.size()]);
774 * Construct and send a command to highlight zero, one or more atoms. We do
775 * this by sending an "rlabel" command to show the residue label at that
779 public void highlightAtoms(List<AtomSpec> atoms)
781 if (atoms == null || atoms.size() == 0)
786 StringBuilder cmd = new StringBuilder(128);
787 boolean first = true;
788 boolean found = false;
790 for (AtomSpec atom : atoms)
792 int pdbResNum = atom.getPdbResNum();
793 String chain = atom.getChain();
794 String pdbfile = atom.getPdbFile();
795 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
796 if (cms != null && !cms.isEmpty())
800 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
808 cmd.append(pdbResNum);
809 if (!chain.equals(" "))
811 cmd.append(".").append(chain);
816 String command = cmd.toString();
819 * avoid repeated commands for the same residue
821 if (command.equals(lastHighlightCommand))
827 * unshow the label for the previous residue
829 if (lastHighlightCommand != null)
831 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
835 viewer.sendChimeraCommand(command, false);
837 this.lastHighlightCommand = command;
841 * Query Chimera for its current selection, and highlight it on the alignment
843 public void highlightChimeraSelection()
846 * Ask Chimera for its current selection
848 List<String> selection = viewer.getSelectedResidueSpecs();
851 * Parse model number, residue and chain for each selected position,
852 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
854 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
858 * Broadcast the selection (which may be empty, if the user just cleared all
861 getSsm().mouseOverStructure(atomSpecs);
865 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
866 * corresponding residues (if any) in Jalview
868 * @param structureSelection
871 protected List<AtomSpec> convertStructureResiduesToAlignment(
872 List<String> structureSelection)
874 List<AtomSpec> atomSpecs = new ArrayList<>();
875 for (String atomSpec : structureSelection)
879 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
880 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
881 spec.setPdbFile(pdbfilename);
883 } catch (IllegalArgumentException e)
885 System.err.println("Failed to parse atomspec: " + atomSpec);
895 protected String getPdbFileForModel(int modelId)
898 * Work out the pdbfilename from the model number
900 String pdbfilename = modelFileNames[0];
901 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
903 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
905 if (cm.getModelNumber() == modelId)
907 pdbfilename = pdbfile;
915 private void log(String message)
917 System.err.println("## Chimera log: " + message);
920 private void viewerCommandHistory(boolean enable)
922 // log("(Not yet implemented) History "
923 // + ((debug || enable) ? "on" : "off"));
926 public long getLoadNotifiesHandled()
928 return loadNotifiesHandled;
932 public void setJalviewColourScheme(ColourSchemeI cs)
934 colourBySequence = false;
941 // Chimera expects RBG values in the range 0-1
942 final double normalise = 255D;
943 viewerCommandHistory(false);
944 StringBuilder command = new StringBuilder(128);
946 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
948 for (String resName : residueSet)
950 char res = resName.length() == 3
951 ? ResidueProperties.getSingleCharacterCode(resName)
953 Color col = cs.findColour(res, 0, null, null, 0f);
954 command.append("color " + col.getRed() / normalise + ","
955 + col.getGreen() / normalise + "," + col.getBlue() / normalise
956 + " ::" + resName + ";");
959 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
960 viewerCommandHistory(true);
964 * called when the binding thinks the UI needs to be refreshed after a Chimera
965 * state change. this could be because structures were loaded, or because an
966 * error has occurred.
968 public abstract void refreshGUI();
971 public void setLoadingFromArchive(boolean loadingFromArchive)
973 this.loadingFromArchive = loadingFromArchive;
978 * @return true if Chimeral is still restoring state or loading is still going
979 * on (see setFinsihedLoadingFromArchive)
982 public boolean isLoadingFromArchive()
984 return loadingFromArchive && !loadingFinished;
988 * modify flag which controls if sequence colouring events are honoured by the
989 * binding. Should be true for normal operation
991 * @param finishedLoading
994 public void setFinishedLoadingFromArchive(boolean finishedLoading)
996 loadingFinished = finishedLoading;
1000 * Send the Chimera 'background solid <color>" command.
1003 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1008 public void setBackgroundColour(Color col)
1010 viewerCommandHistory(false);
1011 double normalise = 255D;
1012 final String command = "background solid " + col.getRed() / normalise
1013 + "," + col.getGreen() / normalise + ","
1014 + col.getBlue() / normalise + ";";
1015 viewer.sendChimeraCommand(command, false);
1016 viewerCommandHistory(true);
1020 * Ask Chimera to save its session to the given file. Returns true if
1021 * successful, else false.
1026 public boolean saveSession(String filepath)
1028 if (isChimeraRunning())
1030 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1032 if (reply.contains("Session written"))
1039 .error("Error saving Chimera session: " + reply.toString());
1046 * Ask Chimera to open a session file. Returns true if successful, else false.
1047 * The filename must have a .py extension for this command to work.
1052 public boolean openSession(String filepath)
1054 sendChimeraCommand("open " + filepath, true);
1055 // todo: test for failure - how?
1060 * Returns a list of chains mapped in this viewer. Note this list is not
1061 * currently scoped per structure.
1066 public List<String> getChainNames()
1072 * Send a 'focus' command to Chimera to recentre the visible display
1074 public void focusView()
1076 sendChimeraCommand("focus", false);
1080 * Send a 'show' command for all atoms in the currently selected columns
1082 * TODO: pull up to abstract structure viewer interface
1086 public void highlightSelection(AlignmentViewPanel vp)
1088 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1090 AlignmentI alignment = vp.getAlignment();
1091 StructureSelectionManager sm = getSsm();
1092 for (SequenceI seq : alignment.getSequences())
1095 * convert selected columns into sequence positions
1097 int[] positions = new int[cols.size()];
1099 for (Integer col : cols)
1101 positions[i++] = seq.findPosition(col);
1103 sm.highlightStructure(this, seq, positions);
1108 * Constructs and send commands to Chimera to set attributes on residues for
1109 * features visible in Jalview
1114 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1116 // TODO refactor as required to pull up to an interface
1117 AlignmentI alignment = avp.getAlignment();
1119 String[] files = getStructureFiles();
1125 StructureMappingcommandSet commandSet = ChimeraCommands
1126 .getSetAttributeCommandsForFeatures(getSsm(), files,
1127 getSequence(), avp);
1128 String[] commands = commandSet.commands;
1129 if (commands.length > 10)
1131 sendCommandsByFile(commands);
1135 for (String command : commands)
1137 sendAsynchronousCommand(command, null);
1140 return commands.length;
1144 * Write commands to a temporary file, and send a command to Chimera to open
1145 * the file as a commands script. For use when sending a large number of
1146 * separate commands would overload the REST interface mechanism.
1150 protected void sendCommandsByFile(String[] commands)
1154 File tmp = File.createTempFile("chim", ".com");
1156 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1157 for (String command : commands)
1159 out.println(command);
1163 String path = tmp.getAbsolutePath();
1164 sendAsynchronousCommand("open cmd:" + path, null);
1165 } catch (IOException e)
1167 System.err.println("Sending commands to Chimera via file failed with "
1173 * Get Chimera residues which have the named attribute, find the mapped
1174 * positions in the Jalview sequence(s), and set as sequence features
1177 * @param alignmentPanel
1179 public void copyStructureAttributesToFeatures(String attName,
1180 AlignmentViewPanel alignmentPanel)
1182 // todo pull up to AAStructureBindingModel (and interface?)
1185 * ask Chimera to list residues with the attribute, reporting its value
1187 // this alternative command
1188 // list residues spec ':*/attName' attr attName
1189 // doesn't report 'None' values (which is good), but
1190 // fails for 'average.bfactor' (which is bad):
1192 String cmd = "list residues attr '" + attName + "'";
1193 List<String> residues = sendChimeraCommand(cmd, true);
1195 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1198 alignmentPanel.getFeatureRenderer().featuresAdded();
1203 * Create features in Jalview for the given attribute name and structure
1207 * The residue list should be 0, 1 or more reply lines of the format:
1208 * residue id #0:5.A isHelix -155.000836316 index 5
1210 * residue id #0:6.A isHelix None
1217 protected boolean createFeaturesForAttributes(String attName,
1218 List<String> residues)
1220 boolean featureAdded = false;
1221 String featureGroup = getViewerFeatureGroup();
1223 for (String residue : residues)
1225 AtomSpec spec = null;
1226 String[] tokens = residue.split(" ");
1227 if (tokens.length < 5)
1231 String atomSpec = tokens[2];
1232 String attValue = tokens[4];
1235 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1237 if ("None".equalsIgnoreCase(attValue)
1238 || "False".equalsIgnoreCase(attValue))
1245 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1246 } catch (IllegalArgumentException e)
1248 System.err.println("Problem parsing atomspec " + atomSpec);
1252 String chainId = spec.getChain();
1253 String description = attValue;
1254 float score = Float.NaN;
1257 score = Float.valueOf(attValue);
1258 description = chainId;
1259 } catch (NumberFormatException e)
1261 // was not a float value
1264 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1265 spec.setPdbFile(pdbFile);
1267 List<AtomSpec> atoms = Collections.singletonList(spec);
1270 * locate the mapped position in the alignment (if any)
1272 SearchResultsI sr = getSsm()
1273 .findAlignmentPositionsForStructurePositions(atoms);
1276 * expect one matched alignment position, or none
1277 * (if the structure position is not mapped)
1279 for (SearchResultMatchI m : sr.getResults())
1281 SequenceI seq = m.getSequence();
1282 int start = m.getStart();
1283 int end = m.getEnd();
1284 SequenceFeature sf = new SequenceFeature(attName, description,
1285 start, end, score, featureGroup);
1286 // todo: should SequenceFeature have an explicit property for chain?
1287 // note: repeating the action shouldn't duplicate features
1288 featureAdded |= seq.addSequenceFeature(sf);
1291 return featureAdded;
1295 * Answers the feature group name to apply to features created in Jalview from
1296 * Chimera attributes
1300 protected String getViewerFeatureGroup()
1302 // todo pull up to interface
1303 return CHIMERA_FEATURE_GROUP;
1306 public Hashtable<String, String> getChainFile()
1311 public List<ChimeraModel> getChimeraModelByChain(String chain)
1313 return chimeraMaps.get(chainFile.get(chain));
1316 public int getModelNoForChain(String chain)
1318 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1319 if (foundModels != null && !foundModels.isEmpty())
1321 return foundModels.get(0).getModelNumber();
1327 public void showStructures(AlignViewportI av)
1329 StringBuilder cmd = new StringBuilder(128);
1330 cmd.append("~display; ~ribbon;");
1331 if (isShowAlignmentOnly())
1333 String atomSpec = getMappedResidues(av);
1334 cmd.append("ribbon ").append(atomSpec);
1338 cmd.append("chain @CA|P; ribbon");
1340 cmd.append("; focus");
1341 sendChimeraCommand(cmd.toString(), false);
1345 * Builds a Chimera atomSpec of residues mapped from sequences, of the format
1346 * (#model:residues.chain)
1349 * #0:2-94.A | #1:1-93.C | #2:1-93.A
1352 * Only residues visible in the alignment are included, that is, hidden columns
1353 * and sequences are excluded.
1358 private String getMappedResidues(AlignViewportI av)
1360 AlignmentI alignment = av.getAlignment();
1361 final int width = alignment.getWidth();
1363 String[] files = getStructureFiles();
1365 StringBuilder atomSpec = new StringBuilder(256);
1367 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1369 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
1372 * Find the first mapped sequence (if any) for this PDB entry which is in
1375 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
1376 for (int s = 0; s < seqCountForPdbFile; s++)
1378 for (StructureMapping mapping : mappings)
1380 final SequenceI theSequence = getSequence()[pdbfnum][s];
1381 if (mapping.getSequence() == theSequence
1382 && alignment.findIndex(theSequence) > -1)
1384 String chainCd = mapping.getChain();
1386 // TODO only process sequence ranges within visible columns
1387 VisibleContigsIterator visible = alignment.getHiddenColumns()
1388 .getVisContigsIterator(0, width, true);
1389 while (visible.hasNext())
1391 int[] visibleRegion = visible.next();
1392 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1393 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1394 List<int[]> residueRanges = mapping
1395 .getPDBResNumRanges(seqStartPos, seqEndPos);
1396 if (!residueRanges.isEmpty())
1398 if (atomSpec.length() > 0)
1400 atomSpec.append("| ");
1402 atomSpec.append(getModelSpec(pdbfnum)).append(":");
1403 boolean first = true;
1404 for (int[] range : residueRanges)
1408 atomSpec.append(",");
1411 atomSpec.append(range[0]).append("-").append(range[1]);
1412 atomSpec.append(".").append(chainCd);
1421 return atomSpec.toString();