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.LinkedHashMap;
55 import java.util.List;
58 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
59 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
60 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
61 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
63 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
65 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
67 // Chimera clause to exclude alternate locations in atom selection
68 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
70 private static final String COLOURING_CHIMERA = MessageManager
71 .getString("status.colouring_chimera");
73 private static final boolean debug = false;
75 private static final String PHOSPHORUS = "P";
77 private static final String ALPHACARBON = "CA";
79 private List<String> chainNames = new ArrayList<String>();
81 private Hashtable<String, String> chainFile = new Hashtable<String, String>();
84 * Object through which we talk to Chimera
86 private ChimeraManager viewer;
89 * Object which listens to Chimera notifications
91 private AbstractRequestHandler chimeraListener;
94 * set if chimera state is being restored from some source - instructs binding
95 * not to apply default display style when structure set is updated for first
98 private boolean loadingFromArchive = false;
101 * flag to indicate if the Chimera viewer should ignore sequence colouring
102 * events from the structure manager because the GUI is still setting up
104 private boolean loadingFinished = true;
107 * Map of ChimeraModel objects keyed by PDB full local file name
109 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
111 String lastHighlightCommand;
114 * incremented every time a load notification is successfully handled -
115 * lightweight mechanism for other threads to detect when they can start
116 * referring to new structures.
118 private long loadNotifiesHandled = 0;
120 private Thread chimeraMonitor;
123 * Open a PDB structure file in Chimera and set up mappings from Jalview.
125 * We check if the PDB model id is already loaded in Chimera, if so don't
126 * reopen it. This is the case if Chimera has opened a saved session file.
131 public boolean openFile(PDBEntry pe)
133 String file = pe.getFile();
136 List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
137 List<ChimeraModel> oldList = viewer.getModelList();
138 boolean alreadyOpen = false;
141 * If Chimera already has this model, don't reopen it, but do remap it.
143 for (ChimeraModel open : oldList)
145 if (open.getModelName().equals(pe.getId()))
148 modelsToMap.add(open);
153 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
154 * the model name(s) added by Chimera.
158 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
159 List<ChimeraModel> newList = viewer.getModelList();
160 // JAL-1728 newList.removeAll(oldList) does not work
161 for (ChimeraModel cm : newList)
163 if (cm.getModelName().equals(pe.getId()))
170 chimeraMaps.put(file, modelsToMap);
172 if (getSsm() != null)
174 getSsm().addStructureViewerListener(this);
177 } catch (Exception q)
179 log("Exception when trying to open model " + file + "\n"
194 public JalviewChimeraBinding(StructureSelectionManager ssm,
195 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
196 DataSourceType protocol)
198 super(ssm, pdbentry, sequenceIs, protocol);
199 viewer = new ChimeraManager(new StructureManager(true));
203 * Starts a thread that waits for the Chimera process to finish, so that we
204 * can then close the associated resources. This avoids leaving orphaned
205 * Chimera viewer panels in Jalview if the user closes Chimera.
207 protected void startChimeraProcessMonitor()
209 final Process p = viewer.getChimeraProcess();
210 chimeraMonitor = new Thread(new Runnable()
219 JalviewStructureDisplayI display = getViewer();
222 display.closeViewer(false);
224 } catch (InterruptedException e)
226 // exit thread if Chimera Viewer is closed in Jalview
230 chimeraMonitor.start();
234 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
235 * it to start listening
237 public void startChimeraListener()
241 chimeraListener = new ChimeraListener(this);
242 viewer.startListening(chimeraListener.getUri());
243 } catch (BindException e)
246 "Failed to start Chimera listener: " + e.getMessage());
251 * Tells Chimera to display only the specified chains
255 public void showChains(List<String> toshow)
258 * Construct a chimera command like
260 * ~display #*;~ribbon #*;ribbon :.A,:.B
262 StringBuilder cmd = new StringBuilder(64);
263 boolean first = true;
264 for (String chain : toshow)
266 int modelNumber = getModelNoForChain(chain);
267 String showChainCmd = modelNumber == -1 ? ""
268 : modelNumber + ":." + chain.split(":")[1];
273 cmd.append(showChainCmd);
278 * could append ";focus" to this command to resize the display to fill the
279 * window, but it looks more helpful not to (easier to relate chains to the
282 final String command = "~display #*; ~ribbon #*; ribbon :"
284 sendChimeraCommand(command, false);
288 * Close down the Jalview viewer and listener, and (optionally) the associated
291 public void closeViewer(boolean closeChimera)
293 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
296 viewer.exitChimera();
298 if (this.chimeraListener != null)
300 chimeraListener.shutdown();
301 chimeraListener = null;
305 if (chimeraMonitor != null)
307 chimeraMonitor.interrupt();
309 releaseUIResources();
313 public void colourByChain()
315 colourBySequence = false;
316 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
320 * Constructs and sends a Chimera command to colour by charge
322 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
323 * <li>Lysine and Arginine (positive charge) blue</li>
324 * <li>Cysteine - yellow</li>
325 * <li>all others - white</li>
329 public void colourByCharge()
331 colourBySequence = false;
332 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
333 sendAsynchronousCommand(command, COLOURING_CHIMERA);
340 public String superposeStructures(AlignmentI[] _alignment,
341 int[] _refStructure, HiddenColumns[] _hiddenCols)
343 StringBuilder allComs = new StringBuilder(128);
344 String[] files = getStructureFiles();
346 if (!waitForFileLoad(files))
352 StringBuilder selectioncom = new StringBuilder(256);
353 for (int a = 0; a < _alignment.length; a++)
355 int refStructure = _refStructure[a];
356 AlignmentI alignment = _alignment[a];
357 HiddenColumns hiddenCols = _hiddenCols[a];
359 if (refStructure >= files.length)
361 System.err.println("Ignoring invalid reference structure value "
367 * 'matched' bit i will be set for visible alignment columns i where
368 * all sequences have a residue with a mapping to the PDB structure
370 BitSet matched = new BitSet();
371 for (int m = 0; m < alignment.getWidth(); m++)
373 if (hiddenCols == null || hiddenCols.isVisible(m))
379 SuperposeData[] structures = new SuperposeData[files.length];
380 for (int f = 0; f < files.length; f++)
382 structures[f] = new SuperposeData(alignment.getWidth());
386 * Calculate the superposable alignment columns ('matched'), and the
387 * corresponding structure residue positions (structures.pdbResNo)
389 int candidateRefStructure = findSuperposableResidues(alignment,
390 matched, structures);
391 if (refStructure < 0)
394 * If no reference structure was specified, pick the first one that has
395 * a mapping in the alignment
397 refStructure = candidateRefStructure;
400 int nmatched = matched.cardinality();
403 return MessageManager.formatMessage("label.insufficient_residues",
408 * Generate select statements to select regions to superimpose structures
410 String[] selcom = new String[files.length];
411 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
413 String chainCd = "." + structures[pdbfnum].chain;
416 StringBuilder molsel = new StringBuilder();
418 int nextColumnMatch = matched.nextSetBit(0);
419 while (nextColumnMatch != -1)
421 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
422 if (lpos != pdbResNum - 1)
425 * discontiguous - append last residue now
429 molsel.append(String.valueOf(lpos));
430 molsel.append(chainCd);
438 * extending a contiguous run
443 * start the range selection
445 molsel.append(String.valueOf(lpos));
451 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
455 * and terminate final selection
459 molsel.append(String.valueOf(lpos));
460 molsel.append(chainCd);
462 if (molsel.length() > 1)
464 selcom[pdbfnum] = molsel.toString();
465 selectioncom.append("#").append(String.valueOf(pdbfnum))
467 selectioncom.append(selcom[pdbfnum]);
468 selectioncom.append(" ");
469 if (pdbfnum < files.length - 1)
471 selectioncom.append("| ");
476 selcom[pdbfnum] = null;
480 StringBuilder command = new StringBuilder(256);
481 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
483 if (pdbfnum == refStructure || selcom[pdbfnum] == null
484 || selcom[refStructure] == null)
488 if (command.length() > 0)
494 * Form Chimera match command, from the 'new' structure to the
495 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
497 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
500 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
502 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
503 command.append(selcom[pdbfnum]);
504 command.append("@").append(
505 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
506 // JAL-1757 exclude alternate CA locations
507 command.append(NO_ALTLOCS);
508 command.append(" ").append(getModelSpec(refStructure)).append(":");
509 command.append(selcom[refStructure]);
510 command.append("@").append(
511 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
512 command.append(NO_ALTLOCS);
514 if (selectioncom.length() > 0)
518 System.out.println("Select regions:\n" + selectioncom.toString());
520 "Superimpose command(s):\n" + command.toString());
522 allComs.append("~display all; chain @CA|P; ribbon ")
523 .append(selectioncom.toString())
524 .append(";" + command.toString());
529 if (selectioncom.length() > 0)
531 // TODO: visually distinguish regions that were superposed
532 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
534 selectioncom.setLength(selectioncom.length() - 1);
538 System.out.println("Select regions:\n" + selectioncom.toString());
540 allComs.append("; ~display all; chain @CA|P; ribbon ")
541 .append(selectioncom.toString()).append("; focus");
542 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
544 for (String reply : chimeraReplies)
546 if (reply.toLowerCase().contains("unequal numbers of atoms"))
556 * Helper method to construct model spec in Chimera format:
558 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
559 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
561 * Note for now we only ever choose the first of multiple models. This
562 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
563 * future if there is a need to select specific sub-models.
568 protected String getModelSpec(int pdbfnum)
570 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
576 * For now, the test for having sub-models is whether multiple Chimera
577 * models are mapped for the PDB file; the models are returned as a response
578 * to the Chimera command 'list models type molecule', see
579 * ChimeraManager.getModelList().
581 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
582 boolean hasSubModels = maps != null && maps.size() > 1;
583 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
587 * Launch Chimera, unless an instance linked to this object is already
588 * running. Returns true if Chimera is successfully launched, or already
589 * running, else false.
593 public boolean launchChimera()
595 if (viewer.isChimeraLaunched())
600 boolean launched = viewer
601 .launchChimera(StructureManager.getChimeraPaths());
604 startChimeraProcessMonitor();
608 log("Failed to launch Chimera!");
614 * Answers true if the Chimera process is still running, false if ended or not
619 public boolean isChimeraRunning()
621 return viewer.isChimeraLaunched();
625 * Send a command to Chimera, and optionally log and return any responses.
627 * Does nothing, and returns null, if the command is the same as the last one
633 public List<String> sendChimeraCommand(final String command,
638 // ? thread running after viewer shut down
641 List<String> reply = null;
642 viewerCommandHistory(false);
643 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
645 // trim command or it may never find a match in the replyLog!!
646 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
653 log("Response from command ('" + command + "') was:\n"
658 viewerCommandHistory(true);
664 * Send a Chimera command asynchronously in a new thread. If the progress
665 * message is not null, display this message while the command is executing.
670 protected abstract void sendAsynchronousCommand(String command,
674 * Sends a set of colour commands to the structure viewer
676 * @param colourBySequenceCommands
679 protected void colourBySequence(
680 StructureMappingcommandSet[] colourBySequenceCommands)
682 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
684 for (String command : cpdbbyseq.commands)
686 sendAsynchronousCommand(command, COLOURING_CHIMERA);
698 protected StructureMappingcommandSet[] getColourBySequenceCommands(
699 String[] files, SequenceRenderer sr, AlignmentViewPanel viewPanel)
701 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
702 getSequence(), sr, viewPanel);
708 protected void executeWhenReady(String command)
711 sendChimeraCommand(command, false);
715 private void waitForChimera()
717 while (viewer != null && viewer.isBusy())
722 } catch (InterruptedException q)
728 // End StructureListener
729 // //////////////////////////
732 * instruct the Jalview binding to update the pdbentries vector if necessary
733 * prior to matching the viewer's contents to the list of structure files
734 * Jalview knows about.
736 public abstract void refreshPdbEntries();
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[] getStructureFiles()
752 return new String[0];
755 return chimeraMaps.keySet()
756 .toArray(modelFileNames = new String[chimeraMaps.size()]);
760 * Construct and send a command to highlight zero, one or more atoms. We do
761 * this by sending an "rlabel" command to show the residue label at that
765 public void highlightAtoms(List<AtomSpec> atoms)
767 if (atoms == null || atoms.size() == 0)
772 StringBuilder cmd = new StringBuilder(128);
773 boolean first = true;
774 boolean found = false;
776 for (AtomSpec atom : atoms)
778 int pdbResNum = atom.getPdbResNum();
779 String chain = atom.getChain();
780 String pdbfile = atom.getPdbFile();
781 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
782 if (cms != null && !cms.isEmpty())
786 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
794 cmd.append(pdbResNum);
795 if (!chain.equals(" "))
797 cmd.append(".").append(chain);
802 String command = cmd.toString();
805 * avoid repeated commands for the same residue
807 if (command.equals(lastHighlightCommand))
813 * unshow the label for the previous residue
815 if (lastHighlightCommand != null)
817 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
821 viewer.sendChimeraCommand(command, false);
823 this.lastHighlightCommand = command;
827 * Query Chimera for its current selection, and highlight it on the alignment
829 public void highlightChimeraSelection()
832 * Ask Chimera for its current selection
834 List<String> selection = viewer.getSelectedResidueSpecs();
837 * Parse model number, residue and chain for each selected position,
838 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
840 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
844 * Broadcast the selection (which may be empty, if the user just cleared all
847 getSsm().mouseOverStructure(atomSpecs);
851 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
852 * corresponding residues (if any) in Jalview
854 * @param structureSelection
857 protected List<AtomSpec> convertStructureResiduesToAlignment(
858 List<String> structureSelection)
860 List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
861 for (String atomSpec : structureSelection)
865 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
866 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
867 spec.setPdbFile(pdbfilename);
869 } catch (IllegalArgumentException e)
871 System.err.println("Failed to parse atomspec: " + atomSpec);
881 protected String getPdbFileForModel(int modelId)
884 * Work out the pdbfilename from the model number
886 String pdbfilename = modelFileNames[0];
887 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
889 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
891 if (cm.getModelNumber() == modelId)
893 pdbfilename = pdbfile;
901 private void log(String message)
903 System.err.println("## Chimera log: " + message);
906 private void viewerCommandHistory(boolean enable)
908 // log("(Not yet implemented) History "
909 // + ((debug || enable) ? "on" : "off"));
912 public long getLoadNotifiesHandled()
914 return loadNotifiesHandled;
918 public void setJalviewColourScheme(ColourSchemeI cs)
920 colourBySequence = false;
927 // Chimera expects RBG values in the range 0-1
928 final double normalise = 255D;
929 viewerCommandHistory(false);
930 StringBuilder command = new StringBuilder(128);
932 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
934 for (String resName : residueSet)
936 char res = resName.length() == 3
937 ? ResidueProperties.getSingleCharacterCode(resName)
939 Color col = cs.findColour(res, 0, null, null, 0f);
940 command.append("color " + col.getRed() / normalise + ","
941 + col.getGreen() / normalise + "," + col.getBlue() / normalise
942 + " ::" + resName + ";");
945 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
946 viewerCommandHistory(true);
950 * called when the binding thinks the UI needs to be refreshed after a Chimera
951 * state change. this could be because structures were loaded, or because an
952 * error has occurred.
954 public abstract void refreshGUI();
957 public void setLoadingFromArchive(boolean loadingFromArchive)
959 this.loadingFromArchive = loadingFromArchive;
964 * @return true if Chimeral is still restoring state or loading is still going
965 * on (see setFinsihedLoadingFromArchive)
968 public boolean isLoadingFromArchive()
970 return loadingFromArchive && !loadingFinished;
974 * modify flag which controls if sequence colouring events are honoured by the
975 * binding. Should be true for normal operation
977 * @param finishedLoading
980 public void setFinishedLoadingFromArchive(boolean finishedLoading)
982 loadingFinished = finishedLoading;
986 * Send the Chimera 'background solid <color>" command.
989 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
994 public void setBackgroundColour(Color col)
996 viewerCommandHistory(false);
997 double normalise = 255D;
998 final String command = "background solid " + col.getRed() / normalise
999 + "," + col.getGreen() / normalise + ","
1000 + col.getBlue() / normalise + ";";
1001 viewer.sendChimeraCommand(command, false);
1002 viewerCommandHistory(true);
1006 * Ask Chimera to save its session to the given file. Returns true if
1007 * successful, else false.
1012 public boolean saveSession(String filepath)
1014 if (isChimeraRunning())
1016 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1018 if (reply.contains("Session written"))
1025 .error("Error saving Chimera session: " + reply.toString());
1032 * Ask Chimera to open a session file. Returns true if successful, else false.
1033 * The filename must have a .py extension for this command to work.
1038 public boolean openSession(String filepath)
1040 sendChimeraCommand("open " + filepath, true);
1041 // todo: test for failure - how?
1046 * Returns a list of chains mapped in this viewer. Note this list is not
1047 * currently scoped per structure.
1052 public List<String> getChainNames()
1058 * Send a 'focus' command to Chimera to recentre the visible display
1060 public void focusView()
1062 sendChimeraCommand("focus", false);
1066 * Send a 'show' command for all atoms in the currently selected columns
1068 * TODO: pull up to abstract structure viewer interface
1072 public void highlightSelection(AlignmentViewPanel vp)
1074 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1076 AlignmentI alignment = vp.getAlignment();
1077 StructureSelectionManager sm = getSsm();
1078 for (SequenceI seq : alignment.getSequences())
1081 * convert selected columns into sequence positions
1083 int[] positions = new int[cols.size()];
1085 for (Integer col : cols)
1087 positions[i++] = seq.findPosition(col);
1089 sm.highlightStructure(this, seq, positions);
1094 * Constructs and send commands to Chimera to set attributes on residues for
1095 * features visible in Jalview
1100 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1102 // TODO refactor as required to pull up to an interface
1103 AlignmentI alignment = avp.getAlignment();
1105 String[] files = getStructureFiles();
1111 StructureMappingcommandSet commandSet = ChimeraCommands
1112 .getSetAttributeCommandsForFeatures(getSsm(), files,
1113 getSequence(), avp);
1114 String[] commands = commandSet.commands;
1115 if (commands.length > 10)
1117 sendCommandsByFile(commands);
1121 for (String command : commands)
1123 sendAsynchronousCommand(command, null);
1126 return commands.length;
1130 * Write commands to a temporary file, and send a command to Chimera to open
1131 * the file as a commands script. For use when sending a large number of
1132 * separate commands would overload the REST interface mechanism.
1136 protected void sendCommandsByFile(String[] commands)
1140 File tmp = File.createTempFile("chim", ".com");
1142 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1143 for (String command : commands)
1145 out.println(command);
1149 String path = tmp.getAbsolutePath();
1150 sendAsynchronousCommand("open cmd:" + path, null);
1151 } catch (IOException e)
1153 System.err.println("Sending commands to Chimera via file failed with "
1159 * Get Chimera residues which have the named attribute, find the mapped
1160 * positions in the Jalview sequence(s), and set as sequence features
1163 * @param alignmentPanel
1165 public void copyStructureAttributesToFeatures(String attName,
1166 AlignmentViewPanel alignmentPanel)
1168 // todo pull up to AAStructureBindingModel (and interface?)
1171 * ask Chimera to list residues with the attribute, reporting its value
1173 // this alternative command
1174 // list residues spec ':*/attName' attr attName
1175 // doesn't report 'None' values (which is good), but
1176 // fails for 'average.bfactor' (which is bad):
1178 String cmd = "list residues attr '" + attName + "'";
1179 List<String> residues = sendChimeraCommand(cmd, true);
1181 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1184 alignmentPanel.getFeatureRenderer().featuresAdded();
1189 * Create features in Jalview for the given attribute name and structure
1193 * The residue list should be 0, 1 or more reply lines of the format:
1194 * residue id #0:5.A isHelix -155.000836316 index 5
1196 * residue id #0:6.A isHelix None
1203 protected boolean createFeaturesForAttributes(String attName,
1204 List<String> residues)
1206 boolean featureAdded = false;
1207 String featureGroup = getViewerFeatureGroup();
1209 for (String residue : residues)
1211 AtomSpec spec = null;
1212 String[] tokens = residue.split(" ");
1213 if (tokens.length < 5)
1217 String atomSpec = tokens[2];
1218 String attValue = tokens[4];
1221 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1223 if ("None".equalsIgnoreCase(attValue)
1224 || "False".equalsIgnoreCase(attValue))
1231 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1232 } catch (IllegalArgumentException e)
1234 System.err.println("Problem parsing atomspec " + atomSpec);
1238 String chainId = spec.getChain();
1239 String description = attValue;
1240 float score = Float.NaN;
1243 score = Float.valueOf(attValue);
1244 description = chainId;
1245 } catch (NumberFormatException e)
1247 // was not a float value
1250 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1251 spec.setPdbFile(pdbFile);
1253 List<AtomSpec> atoms = Collections.singletonList(spec);
1256 * locate the mapped position in the alignment (if any)
1258 SearchResultsI sr = getSsm()
1259 .findAlignmentPositionsForStructurePositions(atoms);
1262 * expect one matched alignment position, or none
1263 * (if the structure position is not mapped)
1265 for (SearchResultMatchI m : sr.getResults())
1267 SequenceI seq = m.getSequence();
1268 int start = m.getStart();
1269 int end = m.getEnd();
1270 SequenceFeature sf = new SequenceFeature(attName, description,
1271 start, end, score, featureGroup);
1272 // todo: should SequenceFeature have an explicit property for chain?
1273 // note: repeating the action shouldn't duplicate features
1274 featureAdded |= seq.addSequenceFeature(sf);
1277 return featureAdded;
1281 * Answers the feature group name to apply to features created in Jalview from
1282 * Chimera attributes
1286 protected String getViewerFeatureGroup()
1288 // todo pull up to interface
1289 return CHIMERA_FEATURE_GROUP;
1292 public Hashtable<String, String> getChainFile()
1297 public List<ChimeraModel> getChimeraModelByChain(String chain)
1299 return chimeraMaps.get(chainFile.get(chain));
1302 public int getModelNoForChain(String chain)
1304 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1305 if (foundModels != null && !foundModels.isEmpty())
1307 return foundModels.get(0).getModelNumber();