2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ext.rbvi.chimera;
23 import jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.structures.JalviewStructureDisplayI;
27 import jalview.bin.Cache;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
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.httpserver.AbstractRequestHandler;
36 import jalview.io.DataSourceType;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.AtomSpec;
40 import jalview.structure.StructureMappingcommandSet;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.structures.models.AAStructureBindingModel;
43 import jalview.util.MessageManager;
45 import java.awt.Color;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49 import java.io.PrintWriter;
50 import java.net.BindException;
51 import java.util.ArrayList;
52 import java.util.BitSet;
53 import java.util.Collections;
54 import java.util.Hashtable;
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<String>();
82 private Hashtable<String, String> chainFile = new Hashtable<String, String>();
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<String, List<ChimeraModel>>();
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
127 * reopen 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<ChimeraModel>();
138 List<ChimeraModel> oldList = viewer.getModelList();
139 boolean alreadyOpen = false;
142 * If Chimera already has this model, don't reopen it, but do remap it.
144 for (ChimeraModel open : oldList)
146 if (open.getModelName().equals(pe.getId()))
149 modelsToMap.add(open);
154 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
155 * the model name(s) added by Chimera.
159 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
160 List<ChimeraModel> newList = viewer.getModelList();
161 // JAL-1728 newList.removeAll(oldList) does not work
162 for (ChimeraModel cm : newList)
164 if (cm.getModelName().equals(pe.getId()))
171 chimeraMaps.put(file, modelsToMap);
173 if (getSsm() != null)
175 getSsm().addStructureViewerListener(this);
176 // ssm.addSelectionListener(this);
177 FeatureRenderer fr = getFeatureRenderer(null);
185 } catch (Exception q)
187 log("Exception when trying to open model " + file + "\n"
202 public JalviewChimeraBinding(StructureSelectionManager ssm,
203 PDBEntry[] pdbentry, SequenceI[][] sequenceIs, DataSourceType protocol)
205 super(ssm, pdbentry, sequenceIs, protocol);
206 viewer = new ChimeraManager(new StructureManager(true));
210 * Starts a thread that waits for the Chimera process to finish, so that we
211 * can then close the associated resources. This avoids leaving orphaned
212 * Chimera viewer panels in Jalview if the user closes Chimera.
214 protected void startChimeraProcessMonitor()
216 final Process p = viewer.getChimeraProcess();
217 chimeraMonitor = new Thread(new Runnable()
226 JalviewStructureDisplayI display = getViewer();
229 display.closeViewer(false);
231 } catch (InterruptedException e)
233 // exit thread if Chimera Viewer is closed in Jalview
237 chimeraMonitor.start();
241 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
242 * it to start listening
244 public void startChimeraListener()
248 chimeraListener = new ChimeraListener(this);
249 viewer.startListening(chimeraListener.getUri());
250 } catch (BindException e)
252 System.err.println("Failed to start Chimera listener: "
258 * Tells Chimera to display only the specified chains
262 public void showChains(List<String> toshow)
265 * Construct a chimera command like
267 * ~display #*;~ribbon #*;ribbon :.A,:.B
269 StringBuilder cmd = new StringBuilder(64);
270 boolean first = true;
271 for (String chain : toshow)
273 int modelNumber = getModelNoForChain(chain);
274 String showChainCmd = modelNumber == -1 ? "" : modelNumber + ":."
275 + chain.split(":")[1];
280 cmd.append(showChainCmd);
285 * could append ";focus" to this command to resize the display to fill the
286 * window, but it looks more helpful not to (easier to relate chains to the
289 final String command = "~display #*; ~ribbon #*; ribbon :"
291 sendChimeraCommand(command, false);
295 * Close down the Jalview viewer and listener, and (optionally) the associated
298 public void closeViewer(boolean closeChimera)
300 getSsm().removeStructureViewerListener(this, this.getPdbFile());
303 viewer.exitChimera();
305 if (this.chimeraListener != null)
307 chimeraListener.shutdown();
308 chimeraListener = null;
312 if (chimeraMonitor != null)
314 chimeraMonitor.interrupt();
316 releaseUIResources();
320 public void colourByChain()
322 colourBySequence = false;
323 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
327 * Constructs and sends a Chimera command to colour by charge
329 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
330 * <li>Lysine and Arginine (positive charge) blue</li>
331 * <li>Cysteine - yellow</li>
332 * <li>all others - white</li>
336 public void colourByCharge()
338 colourBySequence = false;
339 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
340 sendAsynchronousCommand(command, COLOURING_CHIMERA);
347 public String superposeStructures(AlignmentI[] _alignment,
348 int[] _refStructure, ColumnSelection[] _hiddenCols)
350 StringBuilder allComs = new StringBuilder(128);
351 String[] files = getPdbFile();
353 if (!waitForFileLoad(files))
359 StringBuilder selectioncom = new StringBuilder(256);
360 for (int a = 0; a < _alignment.length; a++)
362 int refStructure = _refStructure[a];
363 AlignmentI alignment = _alignment[a];
364 ColumnSelection hiddenCols = _hiddenCols[a];
366 if (refStructure >= files.length)
368 System.err.println("Ignoring invalid reference structure value "
374 * 'matched' bit i will be set for visible alignment columns i where
375 * all sequences have a residue with a mapping to the PDB structure
377 BitSet matched = new BitSet();
378 for (int m = 0; m < alignment.getWidth(); m++)
380 if (hiddenCols == null || hiddenCols.isVisible(m))
386 SuperposeData[] structures = new SuperposeData[files.length];
387 for (int f = 0; f < files.length; f++)
389 structures[f] = new SuperposeData(alignment.getWidth());
393 * Calculate the superposable alignment columns ('matched'), and the
394 * corresponding structure residue positions (structures.pdbResNo)
396 int candidateRefStructure = findSuperposableResidues(alignment,
397 matched, structures);
398 if (refStructure < 0)
401 * If no reference structure was specified, pick the first one that has
402 * a mapping in the alignment
404 refStructure = candidateRefStructure;
407 int nmatched = matched.cardinality();
410 return MessageManager.formatMessage("label.insufficient_residues",
415 * Generate select statements to select regions to superimpose structures
417 String[] selcom = new String[files.length];
418 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
420 String chainCd = "." + structures[pdbfnum].chain;
423 StringBuilder molsel = new StringBuilder();
425 int nextColumnMatch = matched.nextSetBit(0);
426 while (nextColumnMatch != -1)
428 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
429 if (lpos != pdbResNum - 1)
432 * discontiguous - append last residue now
436 molsel.append(String.valueOf(lpos));
437 molsel.append(chainCd);
445 * extending a contiguous run
450 * start the range selection
452 molsel.append(String.valueOf(lpos));
458 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
462 * and terminate final selection
466 molsel.append(String.valueOf(lpos));
467 molsel.append(chainCd);
469 if (molsel.length() > 1)
471 selcom[pdbfnum] = molsel.toString();
472 selectioncom.append("#").append(String.valueOf(pdbfnum))
474 selectioncom.append(selcom[pdbfnum]);
475 selectioncom.append(" ");
476 if (pdbfnum < files.length - 1)
478 selectioncom.append("| ");
483 selcom[pdbfnum] = null;
487 StringBuilder command = new StringBuilder(256);
488 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
490 if (pdbfnum == refStructure || selcom[pdbfnum] == null
491 || selcom[refStructure] == null)
495 if (command.length() > 0)
501 * Form Chimera match command, from the 'new' structure to the
502 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
504 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
507 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
509 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
510 command.append(selcom[pdbfnum]);
511 command.append("@").append(
512 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
513 // JAL-1757 exclude alternate CA locations
514 command.append(NO_ALTLOCS);
515 command.append(" ").append(getModelSpec(refStructure)).append(":");
516 command.append(selcom[refStructure]);
517 command.append("@").append(
518 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
519 command.append(NO_ALTLOCS);
521 if (selectioncom.length() > 0)
525 System.out.println("Select regions:\n" + selectioncom.toString());
526 System.out.println("Superimpose command(s):\n"
527 + command.toString());
529 allComs.append("~display all; chain @CA|P; ribbon ")
530 .append(selectioncom.toString())
531 .append(";" + command.toString());
536 if (selectioncom.length() > 0)
538 // TODO: visually distinguish regions that were superposed
539 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
541 selectioncom.setLength(selectioncom.length() - 1);
545 System.out.println("Select regions:\n" + selectioncom.toString());
547 allComs.append("; ~display all; chain @CA|P; ribbon ")
548 .append(selectioncom.toString()).append("; focus");
549 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
551 for (String reply : chimeraReplies)
553 if (reply.toLowerCase().contains("unequal numbers of atoms"))
563 * Helper method to construct model spec in Chimera format:
565 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
566 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
568 * Note for now we only ever choose the first of multiple models. This
569 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
570 * future if there is a need to select specific sub-models.
575 protected String getModelSpec(int pdbfnum)
577 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
583 * For now, the test for having sub-models is whether multiple Chimera
584 * models are mapped for the PDB file; the models are returned as a response
585 * to the Chimera command 'list models type molecule', see
586 * ChimeraManager.getModelList().
588 List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
589 boolean hasSubModels = maps != null && maps.size() > 1;
590 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
594 * Launch Chimera, unless an instance linked to this object is already
595 * running. Returns true if Chimera is successfully launched, or already
596 * running, else false.
600 public boolean launchChimera()
602 if (viewer.isChimeraLaunched())
607 boolean launched = viewer.launchChimera(StructureManager
611 startChimeraProcessMonitor();
615 log("Failed to launch Chimera!");
621 * Answers true if the Chimera process is still running, false if ended or not
626 public boolean isChimeraRunning()
628 return viewer.isChimeraLaunched();
632 * Send a command to Chimera, and optionally log and return any responses.
634 * Does nothing, and returns null, if the command is the same as the last one
640 public List<String> sendChimeraCommand(final String command,
645 // ? thread running after viewer shut down
648 List<String> reply = null;
649 viewerCommandHistory(false);
650 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
652 // trim command or it may never find a match in the replyLog!!
653 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
660 log("Response from command ('" + command + "') was:\n"
665 viewerCommandHistory(true);
671 * Send a Chimera command asynchronously in a new thread. If the progress
672 * message is not null, display this message while the command is executing.
677 protected abstract void sendAsynchronousCommand(String command,
681 * Sends a set of colour commands to the structure viewer
683 * @param colourBySequenceCommands
686 protected void colourBySequence(
687 StructureMappingcommandSet[] colourBySequenceCommands)
689 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
691 for (String command : cpdbbyseq.commands)
693 sendAsynchronousCommand(command, COLOURING_CHIMERA);
706 protected StructureMappingcommandSet[] getColourBySequenceCommands(
707 String[] files, SequenceRenderer sr, FeatureRenderer fr,
708 AlignmentI alignment)
710 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
711 getSequence(), sr, fr, alignment);
717 protected void executeWhenReady(String command)
720 sendChimeraCommand(command, false);
724 private void waitForChimera()
726 while (viewer != null && viewer.isBusy())
731 } catch (InterruptedException q)
737 // End StructureListener
738 // //////////////////////////
741 * instruct the Jalview binding to update the pdbentries vector if necessary
742 * prior to matching the viewer's contents to the list of structure files
743 * Jalview knows about.
745 public abstract void refreshPdbEntries();
748 * map between index of model filename returned from getPdbFile and the first
749 * index of models from this file in the viewer. Note - this is not trimmed -
750 * use getPdbFile to get number of unique models.
752 private int _modelFileNameMap[];
755 // ////////////////////////////////
756 // /StructureListener
758 public synchronized String[] getPdbFile()
762 return new String[0];
765 return chimeraMaps.keySet().toArray(
766 modelFileNames = new String[chimeraMaps.size()]);
770 * Construct and send a command to highlight zero, one or more atoms. We do
771 * this by sending an "rlabel" command to show the residue label at that
775 public void highlightAtoms(List<AtomSpec> atoms)
777 if (atoms == null || atoms.size() == 0)
782 StringBuilder cmd = new StringBuilder(128);
783 boolean first = true;
784 boolean found = false;
786 for (AtomSpec atom : atoms)
788 int pdbResNum = atom.getPdbResNum();
789 String chain = atom.getChain();
790 String pdbfile = atom.getPdbFile();
791 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
792 if (cms != null && !cms.isEmpty())
796 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
804 cmd.append(pdbResNum);
805 if (!chain.equals(" "))
807 cmd.append(".").append(chain);
812 String command = cmd.toString();
815 * avoid repeated commands for the same residue
817 if (command.equals(lastHighlightCommand))
823 * unshow the label for the previous residue
825 if (lastHighlightCommand != null)
827 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
831 viewer.sendChimeraCommand(command, false);
833 this.lastHighlightCommand = command;
837 * Query Chimera for its current selection, and highlight it on the alignment
839 public void highlightChimeraSelection()
842 * Ask Chimera for its current selection
844 List<String> selection = viewer.getSelectedResidueSpecs();
847 * Parse model number, residue and chain for each selected position,
848 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
850 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(selection);
853 * Broadcast the selection (which may be empty, if the user just cleared all
856 getSsm().mouseOverStructure(atomSpecs);
860 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
861 * corresponding residues (if any) in Jalview
863 * @param structureSelection
866 protected List<AtomSpec> convertStructureResiduesToAlignment(
867 List<String> structureSelection)
869 List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
870 for (String atomSpec : structureSelection)
874 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
875 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
876 spec.setPdbFile(pdbfilename);
878 } catch (IllegalArgumentException e)
880 System.err.println("Failed to parse atomspec: " + atomSpec);
890 protected String getPdbFileForModel(int modelId)
893 * Work out the pdbfilename from the model number
895 String pdbfilename = modelFileNames[0];
896 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
898 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
900 if (cm.getModelNumber() == modelId)
902 pdbfilename = pdbfile;
910 private void log(String message)
912 System.err.println("## Chimera log: " + message);
915 private void viewerCommandHistory(boolean enable)
917 // log("(Not yet implemented) History "
918 // + ((debug || enable) ? "on" : "off"));
921 public long getLoadNotifiesHandled()
923 return loadNotifiesHandled;
927 public void setJalviewColourScheme(ColourSchemeI cs)
929 colourBySequence = false;
936 // Chimera expects RBG values in the range 0-1
937 final double normalise = 255D;
938 viewerCommandHistory(false);
939 StringBuilder command = new StringBuilder(128);
941 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
943 for (String resName : residueSet)
945 char res = resName.length() == 3 ? ResidueProperties
946 .getSingleCharacterCode(resName) : resName.charAt(0);
947 Color col = cs.findColour(res, 0, null, null, 0f);
948 command.append("color " + col.getRed() / normalise + ","
949 + col.getGreen() / normalise + "," + col.getBlue()
950 / normalise + " ::" + resName + ";");
953 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
954 viewerCommandHistory(true);
958 * called when the binding thinks the UI needs to be refreshed after a Chimera
959 * state change. this could be because structures were loaded, or because an
960 * error has occurred.
962 public abstract void refreshGUI();
965 public void setLoadingFromArchive(boolean loadingFromArchive)
967 this.loadingFromArchive = loadingFromArchive;
972 * @return true if Chimeral is still restoring state or loading is still going
973 * on (see setFinsihedLoadingFromArchive)
976 public boolean isLoadingFromArchive()
978 return loadingFromArchive && !loadingFinished;
982 * modify flag which controls if sequence colouring events are honoured by the
983 * binding. Should be true for normal operation
985 * @param finishedLoading
988 public void setFinishedLoadingFromArchive(boolean finishedLoading)
990 loadingFinished = finishedLoading;
994 * Send the Chimera 'background solid <color>" command.
997 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1002 public void setBackgroundColour(Color col)
1004 viewerCommandHistory(false);
1005 double normalise = 255D;
1006 final String command = "background solid " + col.getRed() / normalise
1007 + "," + col.getGreen() / normalise + "," + col.getBlue()
1009 viewer.sendChimeraCommand(command, false);
1010 viewerCommandHistory(true);
1014 * Ask Chimera to save its session to the given file. Returns true if
1015 * successful, else false.
1020 public boolean saveSession(String filepath)
1022 if (isChimeraRunning())
1024 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1026 if (reply.contains("Session written"))
1033 .error("Error saving Chimera session: " + reply.toString());
1040 * Ask Chimera to open a session file. Returns true if successful, else false.
1041 * The filename must have a .py extension for this command to work.
1046 public boolean openSession(String filepath)
1048 sendChimeraCommand("open " + filepath, true);
1049 // todo: test for failure - how?
1054 * Returns a list of chains mapped in this viewer. Note this list is not
1055 * currently scoped per structure.
1060 public List<String> getChainNames()
1066 * Send a 'focus' command to Chimera to recentre the visible display
1068 public void focusView()
1070 sendChimeraCommand("focus", false);
1074 * Send a 'show' command for all atoms in the currently selected columns
1076 * TODO: pull up to abstract structure viewer interface
1080 public void highlightSelection(AlignmentViewPanel vp)
1082 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1084 AlignmentI alignment = vp.getAlignment();
1085 StructureSelectionManager sm = getSsm();
1086 for (SequenceI seq : alignment.getSequences())
1089 * convert selected columns into sequence positions
1091 int[] positions = new int[cols.size()];
1093 for (Integer col : cols)
1095 positions[i++] = seq.findPosition(col);
1097 sm.highlightStructure(this, seq, positions);
1102 * Constructs and send commands to Chimera to set attributes on residues for
1103 * features visible in Jalview
1108 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1110 // TODO refactor as required to pull up to an interface
1111 AlignmentI alignment = avp.getAlignment();
1112 FeatureRenderer fr = getFeatureRenderer(avp);
1115 * fr is null if feature display is turned off
1122 String[] files = getPdbFile();
1128 StructureMappingcommandSet commandSet = ChimeraCommands
1129 .getSetAttributeCommandsForFeatures(getSsm(), files,
1130 getSequence(), fr, alignment);
1131 String[] commands = commandSet.commands;
1132 if (commands.length > 10)
1134 sendCommandsByFile(commands);
1138 for (String command : commands)
1140 sendAsynchronousCommand(command, null);
1143 return commands.length;
1147 * Write commands to a temporary file, and send a command to Chimera to open
1148 * the file as a commands script. For use when sending a large number of
1149 * separate commands would overload the REST interface mechanism.
1153 protected void sendCommandsByFile(String[] commands)
1157 File tmp = File.createTempFile("chim", ".com");
1159 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1160 for (String command : commands)
1162 out.println(command);
1166 String path = tmp.getAbsolutePath();
1167 sendAsynchronousCommand("open cmd:" + path, null);
1168 } catch (IOException e)
1171 .println("Sending commands to Chimera via file failed with "
1177 * Get Chimera residues which have the named attribute, find the mapped
1178 * positions in the Jalview sequence(s), and set as sequence features
1181 * @param alignmentPanel
1183 public void copyStructureAttributesToFeatures(String attName,
1184 AlignmentViewPanel alignmentPanel)
1186 // todo pull up to AAStructureBindingModel (and interface?)
1189 * ask Chimera to list residues with the attribute, reporting its value
1191 // this alternative command
1192 // list residues spec ':*/attName' attr attName
1193 // doesn't report 'None' values (which is good), but
1194 // fails for 'average.bfactor' (which is bad):
1196 String cmd = "list residues attr '" + attName + "'";
1197 List<String> residues = sendChimeraCommand(cmd, true);
1199 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1202 alignmentPanel.getFeatureRenderer().featuresAdded();
1207 * Create features in Jalview for the given attribute name and structure
1211 * The residue list should be 0, 1 or more reply lines of the format:
1212 * residue id #0:5.A isHelix -155.000836316 index 5
1214 * residue id #0:6.A isHelix None
1221 protected boolean createFeaturesForAttributes(String attName,
1222 List<String> residues)
1224 boolean featureAdded = false;
1225 String featureGroup = getViewerFeatureGroup();
1227 for (String residue : residues)
1229 AtomSpec spec = null;
1230 String[] tokens = residue.split(" ");
1231 if (tokens.length < 5)
1235 String atomSpec = tokens[2];
1236 String attValue = tokens[4];
1239 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1241 if ("None".equalsIgnoreCase(attValue)
1242 || "False".equalsIgnoreCase(attValue))
1249 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1250 } catch (IllegalArgumentException e)
1252 System.err.println("Problem parsing atomspec " + atomSpec);
1256 String chainId = spec.getChain();
1257 String description = attValue;
1258 float score = Float.NaN;
1261 score = Float.valueOf(attValue);
1262 description = chainId;
1263 } catch (NumberFormatException e)
1265 // was not a float value
1268 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1269 spec.setPdbFile(pdbFile);
1271 List<AtomSpec> atoms = Collections.singletonList(spec);
1274 * locate the mapped position in the alignment (if any)
1276 SearchResultsI sr = getSsm()
1277 .findAlignmentPositionsForStructurePositions(atoms);
1280 * expect one matched alignment position, or none
1281 * (if the structure position is not mapped)
1283 for (SearchResultMatchI m : sr.getResults())
1285 SequenceI seq = m.getSequence();
1286 int start = m.getStart();
1287 int end = m.getEnd();
1288 SequenceFeature sf = new SequenceFeature(attName, description,
1289 start, end, score, featureGroup);
1290 // todo: should SequenceFeature have an explicit property for chain?
1291 // note: repeating the action shouldn't duplicate features
1292 featureAdded |= seq.addSequenceFeature(sf);
1295 return featureAdded;
1299 * Answers the feature group name to apply to features created in Jalview from
1300 * Chimera attributes
1304 protected String getViewerFeatureGroup()
1306 // todo pull up to interface
1307 return CHIMERA_FEATURE_GROUP;
1311 public Hashtable<String, String> getChainFile()
1316 public List<ChimeraModel> getChimeraModelByChain(String chain)
1318 return chimeraMaps.get(chainFile.get(chain));
1321 public int getModelNoForChain(String chain)
1323 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1324 if (foundModels != null && !foundModels.isEmpty())
1326 return foundModels.get(0).getModelNumber();