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.FeatureRenderer;
26 import jalview.api.SequenceRenderer;
27 import jalview.api.structures.JalviewStructureDisplayI;
28 import jalview.bin.Cache;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SearchResultMatchI;
33 import jalview.datamodel.SearchResultsI;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceI;
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.StructureMappingcommandSet;
42 import jalview.structure.StructureSelectionManager;
43 import jalview.structures.models.AAStructureBindingModel;
44 import jalview.util.MessageManager;
46 import java.awt.Color;
48 import java.io.FileOutputStream;
49 import java.io.IOException;
50 import java.io.PrintWriter;
51 import java.net.BindException;
52 import java.util.ArrayList;
53 import java.util.BitSet;
54 import java.util.Collections;
55 import java.util.Hashtable;
56 import java.util.LinkedHashMap;
57 import java.util.List;
60 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
61 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
62 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
63 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
65 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
67 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
69 // Chimera clause to exclude alternate locations in atom selection
70 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
72 private static final String COLOURING_CHIMERA = MessageManager
73 .getString("status.colouring_chimera");
75 private static final boolean debug = false;
77 private static final String PHOSPHORUS = "P";
79 private static final String ALPHACARBON = "CA";
81 private List<String> chainNames = new ArrayList<String>();
83 private Hashtable<String, String> chainFile = new Hashtable<String, String>();
86 * Object through which we talk to Chimera
88 private ChimeraManager viewer;
91 * Object which listens to Chimera notifications
93 private AbstractRequestHandler chimeraListener;
96 * set if chimera state is being restored from some source - instructs binding
97 * not to apply default display style when structure set is updated for first
100 private boolean loadingFromArchive = false;
103 * flag to indicate if the Chimera viewer should ignore sequence colouring
104 * events from the structure manager because the GUI is still setting up
106 private boolean loadingFinished = true;
109 * Map of ChimeraModel objects keyed by PDB full local file name
111 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
113 String lastHighlightCommand;
116 * incremented every time a load notification is successfully handled -
117 * lightweight mechanism for other threads to detect when they can start
118 * referring to new structures.
120 private long loadNotifiesHandled = 0;
122 private Thread chimeraMonitor;
125 * Open a PDB structure file in Chimera and set up mappings from Jalview.
127 * We check if the PDB model id is already loaded in Chimera, if so don't
128 * reopen it. This is the case if Chimera has opened a saved session file.
133 public boolean openFile(PDBEntry pe)
135 String file = pe.getFile();
138 List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
139 List<ChimeraModel> oldList = 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 List<ChimeraModel> newList = viewer.getModelList();
162 // JAL-1728 newList.removeAll(oldList) does not work
163 for (ChimeraModel cm : newList)
165 if (cm.getModelName().equals(pe.getId()))
172 chimeraMaps.put(file, modelsToMap);
174 if (getSsm() != null)
176 getSsm().addStructureViewerListener(this);
177 // ssm.addSelectionListener(this);
178 FeatureRenderer fr = getFeatureRenderer(null);
186 } catch (Exception q)
188 log("Exception when trying to open model " + file + "\n"
203 public JalviewChimeraBinding(StructureSelectionManager ssm,
204 PDBEntry[] pdbentry, SequenceI[][] sequenceIs, DataSourceType protocol)
206 super(ssm, pdbentry, sequenceIs, protocol);
207 viewer = new ChimeraManager(new StructureManager(true));
211 * Starts a thread that waits for the Chimera process to finish, so that we
212 * can then close the associated resources. This avoids leaving orphaned
213 * Chimera viewer panels in Jalview if the user closes Chimera.
215 protected void startChimeraProcessMonitor()
217 final Process p = viewer.getChimeraProcess();
218 chimeraMonitor = new Thread(new Runnable()
227 JalviewStructureDisplayI display = getViewer();
230 display.closeViewer(false);
232 } catch (InterruptedException e)
234 // exit thread if Chimera Viewer is closed in Jalview
238 chimeraMonitor.start();
242 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
243 * it to start listening
245 public void startChimeraListener()
249 chimeraListener = new ChimeraListener(this);
250 viewer.startListening(chimeraListener.getUri());
251 } catch (BindException e)
253 System.err.println("Failed to start Chimera listener: "
259 * Tells Chimera to display only the specified chains
263 public void showChains(List<String> toshow)
266 * Construct a chimera command like
268 * ~display #*;~ribbon #*;ribbon :.A,:.B
270 StringBuilder cmd = new StringBuilder(64);
271 boolean first = true;
272 for (String chain : toshow)
274 int modelNumber = getModelNoForChain(chain);
275 String showChainCmd = modelNumber == -1 ? "" : modelNumber + ":."
276 + chain.split(":")[1];
281 cmd.append(showChainCmd);
286 * could append ";focus" to this command to resize the display to fill the
287 * window, but it looks more helpful not to (easier to relate chains to the
290 final String command = "~display #*; ~ribbon #*; ribbon :"
292 sendChimeraCommand(command, false);
296 * Close down the Jalview viewer and listener, and (optionally) the associated
299 public void closeViewer(boolean closeChimera)
301 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
304 viewer.exitChimera();
306 if (this.chimeraListener != null)
308 chimeraListener.shutdown();
309 chimeraListener = null;
313 if (chimeraMonitor != null)
315 chimeraMonitor.interrupt();
317 releaseUIResources();
321 public void colourByChain()
323 colourBySequence = false;
324 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
328 * Constructs and sends a Chimera command to colour by charge
330 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
331 * <li>Lysine and Arginine (positive charge) blue</li>
332 * <li>Cysteine - yellow</li>
333 * <li>all others - white</li>
337 public void colourByCharge()
339 colourBySequence = false;
340 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
341 sendAsynchronousCommand(command, COLOURING_CHIMERA);
348 public String superposeStructures(AlignmentI[] _alignment,
349 int[] _refStructure, ColumnSelection[] _hiddenCols)
351 StringBuilder allComs = new StringBuilder(128);
352 String[] files = getStructureFiles();
354 if (!waitForFileLoad(files))
360 StringBuilder selectioncom = new StringBuilder(256);
361 for (int a = 0; a < _alignment.length; a++)
363 int refStructure = _refStructure[a];
364 AlignmentI alignment = _alignment[a];
365 ColumnSelection hiddenCols = _hiddenCols[a];
367 if (refStructure >= files.length)
369 System.err.println("Ignoring invalid reference structure value "
375 * 'matched' bit i will be set for visible alignment columns i where
376 * all sequences have a residue with a mapping to the PDB structure
378 BitSet matched = new BitSet();
379 for (int m = 0; m < alignment.getWidth(); m++)
381 if (hiddenCols == null || hiddenCols.isVisible(m))
387 SuperposeData[] structures = new SuperposeData[files.length];
388 for (int f = 0; f < files.length; f++)
390 structures[f] = new SuperposeData(alignment.getWidth());
394 * Calculate the superposable alignment columns ('matched'), and the
395 * corresponding structure residue positions (structures.pdbResNo)
397 int candidateRefStructure = findSuperposableResidues(alignment,
398 matched, structures);
399 if (refStructure < 0)
402 * If no reference structure was specified, pick the first one that has
403 * a mapping in the alignment
405 refStructure = candidateRefStructure;
408 int nmatched = matched.cardinality();
411 return MessageManager.formatMessage("label.insufficient_residues",
416 * Generate select statements to select regions to superimpose structures
418 String[] selcom = new String[files.length];
419 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
421 String chainCd = "." + structures[pdbfnum].chain;
424 StringBuilder molsel = new StringBuilder();
426 int nextColumnMatch = matched.nextSetBit(0);
427 while (nextColumnMatch != -1)
429 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
430 if (lpos != pdbResNum - 1)
433 * discontiguous - append last residue now
437 molsel.append(String.valueOf(lpos));
438 molsel.append(chainCd);
446 * extending a contiguous run
451 * start the range selection
453 molsel.append(String.valueOf(lpos));
459 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
463 * and terminate final selection
467 molsel.append(String.valueOf(lpos));
468 molsel.append(chainCd);
470 if (molsel.length() > 1)
472 selcom[pdbfnum] = molsel.toString();
473 selectioncom.append("#").append(String.valueOf(pdbfnum))
475 selectioncom.append(selcom[pdbfnum]);
476 selectioncom.append(" ");
477 if (pdbfnum < files.length - 1)
479 selectioncom.append("| ");
484 selcom[pdbfnum] = null;
488 StringBuilder command = new StringBuilder(256);
489 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
491 if (pdbfnum == refStructure || selcom[pdbfnum] == null
492 || selcom[refStructure] == null)
496 if (command.length() > 0)
502 * Form Chimera match command, from the 'new' structure to the
503 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
505 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
508 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
510 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
511 command.append(selcom[pdbfnum]);
512 command.append("@").append(
513 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
514 // JAL-1757 exclude alternate CA locations
515 command.append(NO_ALTLOCS);
516 command.append(" ").append(getModelSpec(refStructure)).append(":");
517 command.append(selcom[refStructure]);
518 command.append("@").append(
519 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
520 command.append(NO_ALTLOCS);
522 if (selectioncom.length() > 0)
526 System.out.println("Select regions:\n" + selectioncom.toString());
527 System.out.println("Superimpose command(s):\n"
528 + command.toString());
530 allComs.append("~display all; chain @CA|P; ribbon ")
531 .append(selectioncom.toString())
532 .append(";" + command.toString());
537 if (selectioncom.length() > 0)
539 // TODO: visually distinguish regions that were superposed
540 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
542 selectioncom.setLength(selectioncom.length() - 1);
546 System.out.println("Select regions:\n" + selectioncom.toString());
548 allComs.append("; ~display all; chain @CA|P; ribbon ")
549 .append(selectioncom.toString()).append("; focus");
550 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
552 for (String reply : chimeraReplies)
554 if (reply.toLowerCase().contains("unequal numbers of atoms"))
564 * Helper method to construct model spec in Chimera format:
566 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
567 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
569 * Note for now we only ever choose the first of multiple models. This
570 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
571 * future if there is a need to select specific sub-models.
576 protected String getModelSpec(int pdbfnum)
578 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
584 * For now, the test for having sub-models is whether multiple Chimera
585 * models are mapped for the PDB file; the models are returned as a response
586 * to the Chimera command 'list models type molecule', see
587 * ChimeraManager.getModelList().
589 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
590 boolean hasSubModels = maps != null && maps.size() > 1;
591 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
595 * Launch Chimera, unless an instance linked to this object is already
596 * running. Returns true if Chimera is successfully launched, or already
597 * running, else false.
601 public boolean launchChimera()
603 if (viewer.isChimeraLaunched())
608 boolean launched = viewer.launchChimera(StructureManager
612 startChimeraProcessMonitor();
616 log("Failed to launch Chimera!");
622 * Answers true if the Chimera process is still running, false if ended or not
627 public boolean isChimeraRunning()
629 return viewer.isChimeraLaunched();
633 * Send a command to Chimera, and optionally log and return any responses.
635 * Does nothing, and returns null, if the command is the same as the last one
641 public List<String> sendChimeraCommand(final String command,
646 // ? thread running after viewer shut down
649 List<String> reply = null;
650 viewerCommandHistory(false);
651 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
653 // trim command or it may never find a match in the replyLog!!
654 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
661 log("Response from command ('" + command + "') was:\n"
666 viewerCommandHistory(true);
672 * Send a Chimera command asynchronously in a new thread. If the progress
673 * message is not null, display this message while the command is executing.
678 protected abstract void sendAsynchronousCommand(String command,
682 * Sends a set of colour commands to the structure viewer
684 * @param colourBySequenceCommands
687 protected void colourBySequence(
688 StructureMappingcommandSet[] colourBySequenceCommands)
690 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
692 for (String command : cpdbbyseq.commands)
694 sendAsynchronousCommand(command, COLOURING_CHIMERA);
707 protected StructureMappingcommandSet[] getColourBySequenceCommands(
708 String[] files, SequenceRenderer sr, FeatureRenderer fr,
709 AlignViewportI viewport)
711 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
712 getSequence(), sr, fr, viewport);
718 protected void executeWhenReady(String command)
721 sendChimeraCommand(command, false);
725 private void waitForChimera()
727 while (viewer != null && viewer.isBusy())
732 } catch (InterruptedException q)
738 // End StructureListener
739 // //////////////////////////
742 * instruct the Jalview binding to update the pdbentries vector if necessary
743 * prior to matching the viewer's contents to the list of structure files
744 * Jalview knows about.
746 public abstract void refreshPdbEntries();
749 * map between index of model filename returned from getPdbFile and the first
750 * index of models from this file in the viewer. Note - this is not trimmed -
751 * use getPdbFile to get number of unique models.
753 private int _modelFileNameMap[];
756 // ////////////////////////////////
757 // /StructureListener
759 public synchronized String[] getStructureFiles()
763 return new String[0];
766 return chimeraMaps.keySet().toArray(
767 modelFileNames = new String[chimeraMaps.size()]);
771 * Construct and send a command to highlight zero, one or more atoms. We do
772 * this by sending an "rlabel" command to show the residue label at that
776 public void highlightAtoms(List<AtomSpec> atoms)
778 if (atoms == null || atoms.size() == 0)
783 StringBuilder cmd = new StringBuilder(128);
784 boolean first = true;
785 boolean found = false;
787 for (AtomSpec atom : atoms)
789 int pdbResNum = atom.getPdbResNum();
790 String chain = atom.getChain();
791 String pdbfile = atom.getPdbFile();
792 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
793 if (cms != null && !cms.isEmpty())
797 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
805 cmd.append(pdbResNum);
806 if (!chain.equals(" "))
808 cmd.append(".").append(chain);
813 String command = cmd.toString();
816 * avoid repeated commands for the same residue
818 if (command.equals(lastHighlightCommand))
824 * unshow the label for the previous residue
826 if (lastHighlightCommand != null)
828 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
832 viewer.sendChimeraCommand(command, false);
834 this.lastHighlightCommand = command;
838 * Query Chimera for its current selection, and highlight it on the alignment
840 public void highlightChimeraSelection()
843 * Ask Chimera for its current selection
845 List<String> selection = viewer.getSelectedResidueSpecs();
848 * Parse model number, residue and chain for each selected position,
849 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
851 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(selection);
854 * Broadcast the selection (which may be empty, if the user just cleared all
857 getSsm().mouseOverStructure(atomSpecs);
861 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
862 * corresponding residues (if any) in Jalview
864 * @param structureSelection
867 protected List<AtomSpec> convertStructureResiduesToAlignment(
868 List<String> structureSelection)
870 List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
871 for (String atomSpec : structureSelection)
875 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
876 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
877 spec.setPdbFile(pdbfilename);
879 } catch (IllegalArgumentException e)
881 System.err.println("Failed to parse atomspec: " + atomSpec);
891 protected String getPdbFileForModel(int modelId)
894 * Work out the pdbfilename from the model number
896 String pdbfilename = modelFileNames[0];
897 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
899 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
901 if (cm.getModelNumber() == modelId)
903 pdbfilename = pdbfile;
911 private void log(String message)
913 System.err.println("## Chimera log: " + message);
916 private void viewerCommandHistory(boolean enable)
918 // log("(Not yet implemented) History "
919 // + ((debug || enable) ? "on" : "off"));
922 public long getLoadNotifiesHandled()
924 return loadNotifiesHandled;
928 public void setJalviewColourScheme(ColourSchemeI cs)
930 colourBySequence = false;
937 // Chimera expects RBG values in the range 0-1
938 final double normalise = 255D;
939 viewerCommandHistory(false);
940 StringBuilder command = new StringBuilder(128);
942 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
944 for (String resName : residueSet)
946 char res = resName.length() == 3 ? ResidueProperties
947 .getSingleCharacterCode(resName) : resName.charAt(0);
948 Color col = cs.findColour(res, 0, null, null, 0f);
949 command.append("color " + col.getRed() / normalise + ","
950 + col.getGreen() / normalise + "," + col.getBlue()
951 / normalise + " ::" + resName + ";");
954 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
955 viewerCommandHistory(true);
959 * called when the binding thinks the UI needs to be refreshed after a Chimera
960 * state change. this could be because structures were loaded, or because an
961 * error has occurred.
963 public abstract void refreshGUI();
966 public void setLoadingFromArchive(boolean loadingFromArchive)
968 this.loadingFromArchive = loadingFromArchive;
973 * @return true if Chimeral is still restoring state or loading is still going
974 * on (see setFinsihedLoadingFromArchive)
977 public boolean isLoadingFromArchive()
979 return loadingFromArchive && !loadingFinished;
983 * modify flag which controls if sequence colouring events are honoured by the
984 * binding. Should be true for normal operation
986 * @param finishedLoading
989 public void setFinishedLoadingFromArchive(boolean finishedLoading)
991 loadingFinished = finishedLoading;
995 * Send the Chimera 'background solid <color>" command.
998 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1003 public void setBackgroundColour(Color col)
1005 viewerCommandHistory(false);
1006 double normalise = 255D;
1007 final String command = "background solid " + col.getRed() / normalise
1008 + "," + col.getGreen() / normalise + "," + col.getBlue()
1010 viewer.sendChimeraCommand(command, false);
1011 viewerCommandHistory(true);
1015 * Ask Chimera to save its session to the given file. Returns true if
1016 * successful, else false.
1021 public boolean saveSession(String filepath)
1023 if (isChimeraRunning())
1025 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1027 if (reply.contains("Session written"))
1034 .error("Error saving Chimera session: " + reply.toString());
1041 * Ask Chimera to open a session file. Returns true if successful, else false.
1042 * The filename must have a .py extension for this command to work.
1047 public boolean openSession(String filepath)
1049 sendChimeraCommand("open " + filepath, true);
1050 // todo: test for failure - how?
1055 * Returns a list of chains mapped in this viewer. Note this list is not
1056 * currently scoped per structure.
1061 public List<String> getChainNames()
1067 * Send a 'focus' command to Chimera to recentre the visible display
1069 public void focusView()
1071 sendChimeraCommand("focus", false);
1075 * Send a 'show' command for all atoms in the currently selected columns
1077 * TODO: pull up to abstract structure viewer interface
1081 public void highlightSelection(AlignmentViewPanel vp)
1083 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1085 AlignmentI alignment = vp.getAlignment();
1086 StructureSelectionManager sm = getSsm();
1087 for (SequenceI seq : alignment.getSequences())
1090 * convert selected columns into sequence positions
1092 int[] positions = new int[cols.size()];
1094 for (Integer col : cols)
1096 positions[i++] = seq.findPosition(col);
1098 sm.highlightStructure(this, seq, positions);
1103 * Constructs and send commands to Chimera to set attributes on residues for
1104 * features visible in Jalview
1109 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1111 // TODO refactor as required to pull up to an interface
1112 AlignmentI alignment = avp.getAlignment();
1113 FeatureRenderer fr = getFeatureRenderer(avp);
1116 * fr is null if feature display is turned off
1123 String[] files = getStructureFiles();
1129 StructureMappingcommandSet commandSet = ChimeraCommands
1130 .getSetAttributeCommandsForFeatures(getSsm(), files,
1131 getSequence(), fr, alignment);
1132 String[] commands = commandSet.commands;
1133 if (commands.length > 10)
1135 sendCommandsByFile(commands);
1139 for (String command : commands)
1141 sendAsynchronousCommand(command, null);
1144 return commands.length;
1148 * Write commands to a temporary file, and send a command to Chimera to open
1149 * the file as a commands script. For use when sending a large number of
1150 * separate commands would overload the REST interface mechanism.
1154 protected void sendCommandsByFile(String[] commands)
1158 File tmp = File.createTempFile("chim", ".com");
1160 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1161 for (String command : commands)
1163 out.println(command);
1167 String path = tmp.getAbsolutePath();
1168 sendAsynchronousCommand("open cmd:" + path, null);
1169 } catch (IOException e)
1172 .println("Sending commands to Chimera via file failed with "
1178 * Get Chimera residues which have the named attribute, find the mapped
1179 * positions in the Jalview sequence(s), and set as sequence features
1182 * @param alignmentPanel
1184 public void copyStructureAttributesToFeatures(String attName,
1185 AlignmentViewPanel alignmentPanel)
1187 // todo pull up to AAStructureBindingModel (and interface?)
1190 * ask Chimera to list residues with the attribute, reporting its value
1192 // this alternative command
1193 // list residues spec ':*/attName' attr attName
1194 // doesn't report 'None' values (which is good), but
1195 // fails for 'average.bfactor' (which is bad):
1197 String cmd = "list residues attr '" + attName + "'";
1198 List<String> residues = sendChimeraCommand(cmd, true);
1200 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1203 alignmentPanel.getFeatureRenderer().featuresAdded();
1208 * Create features in Jalview for the given attribute name and structure
1212 * The residue list should be 0, 1 or more reply lines of the format:
1213 * residue id #0:5.A isHelix -155.000836316 index 5
1215 * residue id #0:6.A isHelix None
1222 protected boolean createFeaturesForAttributes(String attName,
1223 List<String> residues)
1225 boolean featureAdded = false;
1226 String featureGroup = getViewerFeatureGroup();
1228 for (String residue : residues)
1230 AtomSpec spec = null;
1231 String[] tokens = residue.split(" ");
1232 if (tokens.length < 5)
1236 String atomSpec = tokens[2];
1237 String attValue = tokens[4];
1240 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1242 if ("None".equalsIgnoreCase(attValue)
1243 || "False".equalsIgnoreCase(attValue))
1250 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1251 } catch (IllegalArgumentException e)
1253 System.err.println("Problem parsing atomspec " + atomSpec);
1257 String chainId = spec.getChain();
1258 String description = attValue;
1259 float score = Float.NaN;
1262 score = Float.valueOf(attValue);
1263 description = chainId;
1264 } catch (NumberFormatException e)
1266 // was not a float value
1269 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1270 spec.setPdbFile(pdbFile);
1272 List<AtomSpec> atoms = Collections.singletonList(spec);
1275 * locate the mapped position in the alignment (if any)
1277 SearchResultsI sr = getSsm()
1278 .findAlignmentPositionsForStructurePositions(atoms);
1281 * expect one matched alignment position, or none
1282 * (if the structure position is not mapped)
1284 for (SearchResultMatchI m : sr.getResults())
1286 SequenceI seq = m.getSequence();
1287 int start = m.getStart();
1288 int end = m.getEnd();
1289 SequenceFeature sf = new SequenceFeature(attName, description,
1290 start, end, score, featureGroup);
1291 // todo: should SequenceFeature have an explicit property for chain?
1292 // note: repeating the action shouldn't duplicate features
1293 featureAdded |= seq.addSequenceFeature(sf);
1296 return featureAdded;
1300 * Answers the feature group name to apply to features created in Jalview from
1301 * Chimera attributes
1305 protected String getViewerFeatureGroup()
1307 // todo pull up to interface
1308 return CHIMERA_FEATURE_GROUP;
1312 public Hashtable<String, String> getChainFile()
1317 public List<ChimeraModel> getChimeraModelByChain(String chain)
1319 return chimeraMaps.get(chainFile.get(chain));
1322 public int getModelNoForChain(String chain)
1324 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1325 if (foundModels != null && !foundModels.isEmpty())
1327 return foundModels.get(0).getModelNumber();