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.SearchResults;
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.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);
175 // ssm.addSelectionListener(this);
176 FeatureRenderer fr = getFeatureRenderer(null);
184 } catch (Exception q)
186 log("Exception when trying to open model " + file + "\n"
201 public JalviewChimeraBinding(StructureSelectionManager ssm,
202 PDBEntry[] pdbentry, SequenceI[][] sequenceIs, DataSourceType protocol)
204 super(ssm, pdbentry, sequenceIs, protocol);
205 viewer = new ChimeraManager(new StructureManager(true));
209 * Starts a thread that waits for the Chimera process to finish, so that we
210 * can then close the associated resources. This avoids leaving orphaned
211 * Chimera viewer panels in Jalview if the user closes Chimera.
213 protected void startChimeraProcessMonitor()
215 final Process p = viewer.getChimeraProcess();
216 chimeraMonitor = new Thread(new Runnable()
225 JalviewStructureDisplayI display = getViewer();
228 display.closeViewer(false);
230 } catch (InterruptedException e)
232 // exit thread if Chimera Viewer is closed in Jalview
236 chimeraMonitor.start();
240 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
241 * it to start listening
243 public void startChimeraListener()
247 chimeraListener = new ChimeraListener(this);
248 viewer.startListening(chimeraListener.getUri());
249 } catch (BindException e)
251 System.err.println("Failed to start Chimera listener: "
257 * Tells Chimera to display only the specified chains
261 public void showChains(List<String> toshow)
264 * Construct a chimera command like
266 * ~display #*;~ribbon #*;ribbon :.A,:.B
268 StringBuilder cmd = new StringBuilder(64);
269 boolean first = true;
270 for (String chain : toshow)
272 int modelNumber = getModelNoForChain(chain);
273 String showChainCmd = modelNumber == -1 ? "" : modelNumber + ":."
274 + chain.split(":")[1];
279 cmd.append(showChainCmd);
284 * could append ";focus" to this command to resize the display to fill the
285 * window, but it looks more helpful not to (easier to relate chains to the
288 final String command = "~display #*; ~ribbon #*; ribbon :"
290 sendChimeraCommand(command, false);
294 * Close down the Jalview viewer and listener, and (optionally) the associated
297 public void closeViewer(boolean closeChimera)
299 getSsm().removeStructureViewerListener(this, this.getPdbFile());
302 viewer.exitChimera();
304 if (this.chimeraListener != null)
306 chimeraListener.shutdown();
307 chimeraListener = null;
311 if (chimeraMonitor != null)
313 chimeraMonitor.interrupt();
315 releaseUIResources();
319 public void colourByChain()
321 colourBySequence = false;
322 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
326 * Constructs and sends a Chimera command to colour by charge
328 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
329 * <li>Lysine and Arginine (positive charge) blue</li>
330 * <li>Cysteine - yellow</li>
331 * <li>all others - white</li>
335 public void colourByCharge()
337 colourBySequence = false;
338 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
339 sendAsynchronousCommand(command, COLOURING_CHIMERA);
343 * Construct and send a command to align structures against a reference
344 * structure, based on one or more sequence alignments
347 * an array of alignments to process
348 * @param _refStructure
349 * an array of corresponding reference structures (index into pdb
350 * file array); if a negative value is passed, the first PDB file
351 * mapped to an alignment sequence is used as the reference for
354 * an array of corresponding hidden columns for each alignment
357 public void superposeStructures(AlignmentI[] _alignment,
358 int[] _refStructure, ColumnSelection[] _hiddenCols)
360 StringBuilder allComs = new StringBuilder(128);
361 String[] files = getPdbFile();
363 if (!waitForFileLoad(files))
369 StringBuilder selectioncom = new StringBuilder(256);
370 for (int a = 0; a < _alignment.length; a++)
372 int refStructure = _refStructure[a];
373 AlignmentI alignment = _alignment[a];
374 ColumnSelection hiddenCols = _hiddenCols[a];
376 if (refStructure >= files.length)
378 System.err.println("Ignoring invalid reference structure value "
384 * 'matched' array will hold 'true' for visible alignment columns where
385 * all sequences have a residue with a mapping to the PDB structure
387 boolean matched[] = new boolean[alignment.getWidth()];
388 for (int m = 0; m < matched.length; m++)
390 matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
393 SuperposeData[] structures = new SuperposeData[files.length];
394 for (int f = 0; f < files.length; f++)
396 structures[f] = new SuperposeData(alignment.getWidth());
400 * Calculate the superposable alignment columns ('matched'), and the
401 * corresponding structure residue positions (structures.pdbResNo)
403 int candidateRefStructure = findSuperposableResidues(alignment,
404 matched, structures);
405 if (refStructure < 0)
408 * If no reference structure was specified, pick the first one that has
409 * a mapping in the alignment
411 refStructure = candidateRefStructure;
415 for (boolean b : matched)
424 // TODO: bail out here because superposition illdefined?
428 * Generate select statements to select regions to superimpose structures
430 String[] selcom = new String[files.length];
431 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
433 String chainCd = "." + structures[pdbfnum].chain;
436 StringBuilder molsel = new StringBuilder();
437 for (int r = 0; r < matched.length; r++)
441 int pdbResNum = structures[pdbfnum].pdbResNo[r];
442 if (lpos != pdbResNum - 1)
445 * discontiguous - append last residue now
449 molsel.append(String.valueOf(lpos));
450 molsel.append(chainCd);
458 * extending a contiguous run
463 * start the range selection
465 molsel.append(String.valueOf(lpos));
475 * and terminate final selection
479 molsel.append(String.valueOf(lpos));
480 molsel.append(chainCd);
482 if (molsel.length() > 1)
484 selcom[pdbfnum] = molsel.toString();
485 selectioncom.append("#").append(String.valueOf(pdbfnum))
487 selectioncom.append(selcom[pdbfnum]);
488 selectioncom.append(" ");
489 if (pdbfnum < files.length - 1)
491 selectioncom.append("| ");
496 selcom[pdbfnum] = null;
500 StringBuilder command = new StringBuilder(256);
501 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
503 if (pdbfnum == refStructure || selcom[pdbfnum] == null
504 || selcom[refStructure] == null)
508 if (command.length() > 0)
514 * Form Chimera match command, from the 'new' structure to the
515 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
517 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
520 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
522 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
523 command.append(selcom[pdbfnum]);
524 command.append("@").append(
525 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
526 // JAL-1757 exclude alternate CA locations
527 command.append(NO_ALTLOCS);
528 command.append(" ").append(getModelSpec(refStructure)).append(":");
529 command.append(selcom[refStructure]);
530 command.append("@").append(
531 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
532 command.append(NO_ALTLOCS);
534 if (selectioncom.length() > 0)
538 System.out.println("Select regions:\n" + selectioncom.toString());
539 System.out.println("Superimpose command(s):\n"
540 + command.toString());
542 allComs.append("~display all; chain @CA|P; ribbon ")
543 .append(selectioncom.toString())
544 .append(";" + command.toString());
547 if (selectioncom.length() > 0)
549 // TODO: visually distinguish regions that were superposed
550 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
552 selectioncom.setLength(selectioncom.length() - 1);
556 System.out.println("Select regions:\n" + selectioncom.toString());
558 allComs.append("; ~display all; chain @CA|P; ribbon ")
559 .append(selectioncom.toString()).append("; focus");
560 sendChimeraCommand(allComs.toString(), false);
566 * Helper method to construct model spec in Chimera format:
568 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
569 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
571 * Note for now we only ever choose the first of multiple models. This
572 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
573 * future if there is a need to select specific sub-models.
578 protected String getModelSpec(int pdbfnum)
580 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
586 * For now, the test for having sub-models is whether multiple Chimera
587 * models are mapped for the PDB file; the models are returned as a response
588 * to the Chimera command 'list models type molecule', see
589 * ChimeraManager.getModelList().
591 List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
592 boolean hasSubModels = maps != null && maps.size() > 1;
593 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
597 * Launch Chimera, unless an instance linked to this object is already
598 * running. Returns true if Chimera is successfully launched, or already
599 * running, else false.
603 public boolean launchChimera()
605 if (viewer.isChimeraLaunched())
610 boolean launched = viewer.launchChimera(StructureManager
614 startChimeraProcessMonitor();
618 log("Failed to launch Chimera!");
624 * Answers true if the Chimera process is still running, false if ended or not
629 public boolean isChimeraRunning()
631 return viewer.isChimeraLaunched();
635 * Send a command to Chimera, and optionally log and return any responses.
637 * Does nothing, and returns null, if the command is the same as the last one
643 public List<String> sendChimeraCommand(final String command,
648 // ? thread running after viewer shut down
651 List<String> reply = null;
652 viewerCommandHistory(false);
653 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
655 // trim command or it may never find a match in the replyLog!!
656 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
663 log("Response from command ('" + command + "') was:\n"
668 viewerCommandHistory(true);
674 * Send a Chimera command asynchronously in a new thread. If the progress
675 * message is not null, display this message while the command is executing.
680 protected abstract void sendAsynchronousCommand(String command,
684 * Sends a set of colour commands to the structure viewer
686 * @param colourBySequenceCommands
689 protected void colourBySequence(
690 StructureMappingcommandSet[] colourBySequenceCommands)
692 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
694 for (String command : cpdbbyseq.commands)
696 sendAsynchronousCommand(command, COLOURING_CHIMERA);
709 protected StructureMappingcommandSet[] getColourBySequenceCommands(
710 String[] files, SequenceRenderer sr, FeatureRenderer fr,
711 AlignmentI alignment)
713 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
714 getSequence(), sr, fr, alignment);
720 protected void executeWhenReady(String command)
723 sendChimeraCommand(command, false);
727 private void waitForChimera()
729 while (viewer != null && viewer.isBusy())
734 } catch (InterruptedException q)
740 // End StructureListener
741 // //////////////////////////
744 * instruct the Jalview binding to update the pdbentries vector if necessary
745 * prior to matching the viewer's contents to the list of structure files
746 * Jalview knows about.
748 public abstract void refreshPdbEntries();
751 * map between index of model filename returned from getPdbFile and the first
752 * index of models from this file in the viewer. Note - this is not trimmed -
753 * use getPdbFile to get number of unique models.
755 private int _modelFileNameMap[];
758 // ////////////////////////////////
759 // /StructureListener
761 public synchronized String[] getPdbFile()
765 return new String[0];
768 return chimeraMaps.keySet().toArray(
769 modelFileNames = new String[chimeraMaps.size()]);
773 * Construct and send a command to highlight zero, one or more atoms. We do
774 * this by sending an "rlabel" command to show the residue label at that
778 public void highlightAtoms(List<AtomSpec> atoms)
780 if (atoms == null || atoms.size() == 0)
785 StringBuilder cmd = new StringBuilder(128);
786 boolean first = true;
787 boolean found = false;
789 for (AtomSpec atom : atoms)
791 int pdbResNum = atom.getPdbResNum();
792 String chain = atom.getChain();
793 String pdbfile = atom.getPdbFile();
794 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
795 if (cms != null && !cms.isEmpty())
799 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
807 cmd.append(pdbResNum);
808 if (!chain.equals(" "))
810 cmd.append(".").append(chain);
815 String command = cmd.toString();
818 * avoid repeated commands for the same residue
820 if (command.equals(lastHighlightCommand))
826 * unshow the label for the previous residue
828 if (lastHighlightCommand != null)
830 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
834 viewer.sendChimeraCommand(command, false);
836 this.lastHighlightCommand = command;
840 * Query Chimera for its current selection, and highlight it on the alignment
842 public void highlightChimeraSelection()
845 * Ask Chimera for its current selection
847 List<String> selection = viewer.getSelectedResidueSpecs();
850 * Parse model number, residue and chain for each selected position,
851 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
853 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(selection);
856 * Broadcast the selection (which may be empty, if the user just cleared all
859 getSsm().mouseOverStructure(atomSpecs);
863 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
864 * corresponding residues (if any) in Jalview
866 * @param structureSelection
869 protected List<AtomSpec> convertStructureResiduesToAlignment(
870 List<String> structureSelection)
872 List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
873 for (String atomSpec : structureSelection)
877 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
878 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
879 spec.setPdbFile(pdbfilename);
881 } catch (IllegalArgumentException e)
883 System.err.println("Failed to parse atomspec: " + atomSpec);
893 protected String getPdbFileForModel(int modelId)
896 * Work out the pdbfilename from the model number
898 String pdbfilename = modelFileNames[0];
899 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
901 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
903 if (cm.getModelNumber() == modelId)
905 pdbfilename = pdbfile;
913 private void log(String message)
915 System.err.println("## Chimera log: " + message);
918 private void viewerCommandHistory(boolean enable)
920 // log("(Not yet implemented) History "
921 // + ((debug || enable) ? "on" : "off"));
924 public long getLoadNotifiesHandled()
926 return loadNotifiesHandled;
930 public void setJalviewColourScheme(ColourSchemeI cs)
932 colourBySequence = false;
939 // Chimera expects RBG values in the range 0-1
940 final double normalise = 255D;
941 viewerCommandHistory(false);
942 StringBuilder command = new StringBuilder(128);
944 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
946 for (String resName : residueSet)
948 char res = resName.length() == 3 ? ResidueProperties
949 .getSingleCharacterCode(resName) : resName.charAt(0);
950 Color col = cs.findColour(res, 0, null, null, 0f);
951 command.append("color " + col.getRed() / normalise + ","
952 + col.getGreen() / normalise + "," + col.getBlue()
953 / normalise + " ::" + resName + ";");
956 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
957 viewerCommandHistory(true);
961 * called when the binding thinks the UI needs to be refreshed after a Chimera
962 * state change. this could be because structures were loaded, or because an
963 * error has occurred.
965 public abstract void refreshGUI();
968 public void setLoadingFromArchive(boolean loadingFromArchive)
970 this.loadingFromArchive = loadingFromArchive;
975 * @return true if Chimeral is still restoring state or loading is still going
976 * on (see setFinsihedLoadingFromArchive)
979 public boolean isLoadingFromArchive()
981 return loadingFromArchive && !loadingFinished;
985 * modify flag which controls if sequence colouring events are honoured by the
986 * binding. Should be true for normal operation
988 * @param finishedLoading
991 public void setFinishedLoadingFromArchive(boolean finishedLoading)
993 loadingFinished = finishedLoading;
997 * Send the Chimera 'background solid <color>" command.
1000 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1005 public void setBackgroundColour(Color col)
1007 viewerCommandHistory(false);
1008 double normalise = 255D;
1009 final String command = "background solid " + col.getRed() / normalise
1010 + "," + col.getGreen() / normalise + "," + col.getBlue()
1012 viewer.sendChimeraCommand(command, false);
1013 viewerCommandHistory(true);
1017 * Ask Chimera to save its session to the given file. Returns true if
1018 * successful, else false.
1023 public boolean saveSession(String filepath)
1025 if (isChimeraRunning())
1027 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1029 if (reply.contains("Session written"))
1036 .error("Error saving Chimera session: " + reply.toString());
1043 * Ask Chimera to open a session file. Returns true if successful, else false.
1044 * The filename must have a .py extension for this command to work.
1049 public boolean openSession(String filepath)
1051 sendChimeraCommand("open " + filepath, true);
1052 // todo: test for failure - how?
1057 * Returns a list of chains mapped in this viewer. Note this list is not
1058 * currently scoped per structure.
1063 public List<String> getChainNames()
1069 * Send a 'focus' command to Chimera to recentre the visible display
1071 public void focusView()
1073 sendChimeraCommand("focus", false);
1077 * Send a 'show' command for all atoms in the currently selected columns
1079 * TODO: pull up to abstract structure viewer interface
1083 public void highlightSelection(AlignmentViewPanel vp)
1085 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1087 AlignmentI alignment = vp.getAlignment();
1088 StructureSelectionManager sm = getSsm();
1089 for (SequenceI seq : alignment.getSequences())
1092 * convert selected columns into sequence positions
1094 int[] positions = new int[cols.size()];
1096 for (Integer col : cols)
1098 positions[i++] = seq.findPosition(col);
1100 sm.highlightStructure(this, seq, positions);
1105 * Constructs and send commands to Chimera to set attributes on residues for
1106 * features visible in Jalview
1110 public void sendFeaturesToViewer(AlignmentViewPanel avp)
1112 // TODO refactor as required to pull up to an interface
1113 AlignmentI alignment = avp.getAlignment();
1114 FeatureRenderer fr = getFeatureRenderer(avp);
1117 * fr is null if feature display is turned off
1124 String[] files = getPdbFile();
1130 StructureMappingcommandSet commandSet = ChimeraCommands
1131 .getSetAttributeCommandsForFeatures(getSsm(), files,
1132 getSequence(), fr, alignment);
1133 String[] commands = commandSet.commands;
1134 if (commands.length > 10)
1136 sendCommandsByFile(commands);
1140 for (String command : commands)
1142 sendAsynchronousCommand(command, null);
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 SearchResults 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();