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.structures.JalviewStructureDisplayI;
25 import jalview.bin.Cache;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SearchResultMatchI;
29 import jalview.datamodel.SearchResultsI;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.StructureViewer.ViewerType;
33 import jalview.httpserver.AbstractRequestHandler;
34 import jalview.io.DataSourceType;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureCommand;
37 import jalview.structure.StructureCommandI;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.structures.models.AAStructureBindingModel;
42 import java.io.FileOutputStream;
43 import java.io.IOException;
44 import java.io.PrintWriter;
45 import java.net.BindException;
46 import java.util.ArrayList;
47 import java.util.Collections;
48 import java.util.Iterator;
49 import java.util.LinkedHashMap;
50 import java.util.List;
53 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
54 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
55 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
56 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
58 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
60 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
62 // Chimera clause to exclude alternate locations in atom selection
63 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
65 private static final boolean debug = false;
67 private static final String PHOSPHORUS = "P";
69 private static final String ALPHACARBON = "CA";
72 * Object through which we talk to Chimera
74 private ChimeraManager chimeraManager;
77 * Object which listens to Chimera notifications
79 private AbstractRequestHandler chimeraListener;
82 * Map of ChimeraModel objects keyed by PDB full local file name
84 protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
86 String lastHighlightCommand;
88 private Thread chimeraMonitor;
91 * Open a PDB structure file in Chimera and set up mappings from Jalview.
93 * We check if the PDB model id is already loaded in Chimera, if so don't reopen
94 * it. This is the case if Chimera has opened a saved session file.
99 public boolean openFile(PDBEntry pe)
101 String file = pe.getFile();
104 List<ChimeraModel> modelsToMap = new ArrayList<>();
105 List<ChimeraModel> oldList = chimeraManager.getModelList();
106 boolean alreadyOpen = false;
109 * If Chimera already has this model, don't reopen it, but do remap it.
111 for (ChimeraModel open : oldList)
113 if (open.getModelName().equals(pe.getId()))
116 modelsToMap.add(open);
121 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
122 * the model name(s) added by Chimera.
126 chimeraManager.openModel(file, pe.getId(), ModelType.PDB_MODEL);
127 addChimeraModel(pe, modelsToMap);
130 chimeraMaps.put(file, modelsToMap);
132 if (getSsm() != null)
134 getSsm().addStructureViewerListener(this);
137 } catch (Exception q)
139 log("Exception when trying to open model " + file + "\n"
147 * Adds the ChimeraModel corresponding to the given PDBEntry, based on model
148 * name matching PDB id
153 protected void addChimeraModel(PDBEntry pe,
154 List<ChimeraModel> modelsToMap)
157 * Chimera: query for actual models and find the one with
158 * matching model name - already set in viewer.openModel()
160 List<ChimeraModel> newList = chimeraManager.getModelList();
161 // JAL-1728 newList.removeAll(oldList) does not work
162 for (ChimeraModel cm : newList)
164 if (cm.getModelName().equals(pe.getId()))
179 public JalviewChimeraBinding(StructureSelectionManager ssm,
180 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
181 DataSourceType protocol)
183 super(ssm, pdbentry, sequenceIs, protocol);
184 chimeraManager = new ChimeraManager(new StructureManager(true));
185 chimeraManager.setChimeraX(ViewerType.CHIMERAX.equals(getViewerType()));
186 setStructureCommands(new ChimeraCommands());
190 protected ViewerType getViewerType()
192 return ViewerType.CHIMERA;
196 * Starts a thread that waits for the Chimera process to finish, so that we can
197 * then close the associated resources. This avoids leaving orphaned Chimera
198 * viewer panels in Jalview if the user closes Chimera.
200 protected void startChimeraProcessMonitor()
202 final Process p = chimeraManager.getChimeraProcess();
203 chimeraMonitor = new Thread(new Runnable()
212 JalviewStructureDisplayI display = getViewer();
215 display.closeViewer(false);
217 } catch (InterruptedException e)
219 // exit thread if Chimera Viewer is closed in Jalview
223 chimeraMonitor.start();
227 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
230 public void startChimeraListener()
234 chimeraListener = new ChimeraListener(this);
235 chimeraManager.startListening(chimeraListener.getUri());
236 } catch (BindException e)
239 "Failed to start Chimera listener: " + e.getMessage());
244 * Close down the Jalview viewer and listener, and (optionally) the associated
247 public void closeViewer(boolean closeChimera)
249 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
252 chimeraManager.exitChimera();
254 if (this.chimeraListener != null)
256 chimeraListener.shutdown();
257 chimeraListener = null;
259 chimeraManager = null;
261 if (chimeraMonitor != null)
263 chimeraMonitor.interrupt();
265 releaseUIResources();
269 * Helper method to construct model spec in Chimera format:
271 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
272 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
274 * Note for now we only ever choose the first of multiple models. This
275 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
276 * future if there is a need to select specific sub-models.
281 protected String getModelSpec(int pdbfnum)
283 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
285 return "#" + pdbfnum; // temp hack for ChimeraX
289 * For now, the test for having sub-models is whether multiple Chimera
290 * models are mapped for the PDB file; the models are returned as a response
291 * to the Chimera command 'list models type molecule', see
292 * ChimeraManager.getModelList().
294 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
295 boolean hasSubModels = maps != null && maps.size() > 1;
296 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
300 * Launch Chimera, unless an instance linked to this object is already
301 * running. Returns true if Chimera is successfully launched, or already
302 * running, else false.
306 public boolean launchChimera()
308 if (chimeraManager.isChimeraLaunched())
313 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
316 startChimeraProcessMonitor();
320 log("Failed to launch Chimera!");
326 * Returns a list of candidate paths to the Chimera program executable
330 protected List<String> getChimeraPaths()
332 return StructureManager.getChimeraPaths(false);
336 * Answers true if the Chimera process is still running, false if ended or not
341 public boolean isChimeraRunning()
343 return chimeraManager.isChimeraLaunched();
347 * Send a command to Chimera, and optionally log and return any responses.
353 public List<String> executeCommand(final StructureCommandI command,
356 if (chimeraManager == null || command == null)
358 // ? thread running after viewer shut down
361 List<String> reply = null;
362 // trim command or it may never find a match in the replyLog!!
363 String cmd = command.getCommand().trim();
364 List<String> lastReply = chimeraManager
365 .sendChimeraCommand(cmd, getResponse);
371 log("Response from command ('" + cmd + "') was:\n" + lastReply);
379 public synchronized String[] getStructureFiles()
381 if (chimeraManager == null)
383 return new String[0];
386 return chimeraMaps.keySet()
387 .toArray(modelFileNames = new String[chimeraMaps.size()]);
391 * Construct and send a command to highlight zero, one or more atoms. We do this
392 * by sending an "rlabel" command to show the residue label at that position.
395 public void highlightAtoms(List<AtomSpec> atoms)
397 if (atoms == null || atoms.size() == 0)
402 boolean forChimeraX = chimeraManager.isChimeraX();
403 StringBuilder cmd = new StringBuilder(128);
404 boolean first = true;
405 boolean found = false;
407 for (AtomSpec atom : atoms)
409 int pdbResNum = atom.getPdbResNum();
410 String chain = atom.getChain();
411 String pdbfile = atom.getPdbFile();
412 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
413 if (cms != null && !cms.isEmpty())
417 cmd.append(forChimeraX ? "label #" : "rlabel #");
426 cmd.append(cms.get(0).getModelNumber())
427 .append("/").append(chain).append(":").append(pdbResNum);
431 cmd.append(cms.get(0).getModelNumber())
432 .append(":").append(pdbResNum);
433 if (!chain.equals(" ") && !forChimeraX)
435 cmd.append(".").append(chain);
441 String command = cmd.toString();
444 * avoid repeated commands for the same residue
446 if (command.equals(lastHighlightCommand))
452 * unshow the label for the previous residue
454 if (lastHighlightCommand != null)
456 chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
460 chimeraManager.sendChimeraCommand(command, false);
462 this.lastHighlightCommand = command;
466 * Query Chimera for its current selection, and highlight it on the alignment
468 public void highlightChimeraSelection()
471 * Ask Chimera for its current selection
473 List<String> selection = chimeraManager.getSelectedResidueSpecs();
476 * Parse model number, residue and chain for each selected position,
477 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
479 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
483 * Broadcast the selection (which may be empty, if the user just cleared all
486 getSsm().mouseOverStructure(atomSpecs);
490 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
491 * corresponding residues (if any) in Jalview
493 * @param structureSelection
496 protected List<AtomSpec> convertStructureResiduesToAlignment(
497 List<String> structureSelection)
499 boolean chimeraX = chimeraManager.isChimeraX();
500 List<AtomSpec> atomSpecs = new ArrayList<>();
501 for (String atomSpec : structureSelection)
505 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
506 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
507 spec.setPdbFile(pdbfilename);
509 } catch (IllegalArgumentException e)
511 System.err.println("Failed to parse atomspec: " + atomSpec);
521 protected String getPdbFileForModel(int modelId)
524 * Work out the pdbfilename from the model number
526 String pdbfilename = modelFileNames[0];
527 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
529 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
531 if (cm.getModelNumber() == modelId)
533 pdbfilename = pdbfile;
541 private void log(String message)
543 System.err.println("## Chimera log: " + message);
547 * Ask Chimera to save its session to the given file. Returns true if
548 * successful, else false.
553 public boolean saveSession(String filepath)
555 if (isChimeraRunning())
558 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
559 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/save.html
561 String command = getCommandGenerator().saveSession(filepath)
563 List<String> reply = chimeraManager.sendChimeraCommand(command, true);
564 if (reply.contains("Session written"))
571 .error("Error saving Chimera session: " + reply.toString());
578 * Ask Chimera to open a session file. Returns true if successful, else false.
579 * The filename must have a .py (Chimera) or .cxs (ChimeraX) extension for
580 * this command to work.
585 public boolean openSession(String filepath)
588 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/open.html
589 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/open.html
591 executeCommand(getCommandGenerator().loadFile(filepath), true);
592 // todo: test for failure - how?
597 * Send a 'show' command for all atoms in the currently selected columns
599 * TODO: pull up to abstract structure viewer interface
603 public void highlightSelection(AlignmentViewPanel vp)
605 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
607 AlignmentI alignment = vp.getAlignment();
608 StructureSelectionManager sm = getSsm();
609 for (SequenceI seq : alignment.getSequences())
612 * convert selected columns into sequence positions
614 int[] positions = new int[cols.size()];
616 for (Integer col : cols)
618 positions[i++] = seq.findPosition(col);
620 sm.highlightStructure(this, seq, positions);
625 * Constructs and send commands to Chimera to set attributes on residues for
626 * features visible in Jalview
631 public int sendFeaturesToViewer(AlignmentViewPanel avp)
633 // TODO refactor as required to pull up to an interface
634 String[] files = getStructureFiles();
640 List<StructureCommandI> commands = getCommandGenerator()
641 .setAttributesForFeatures(getSsm(), files, getSequence(), avp);
642 if (commands.size() > 10)
644 sendCommandsByFile(commands);
648 for (StructureCommandI command : commands)
650 sendAsynchronousCommand(command, null);
653 return commands.size();
657 * Write commands to a temporary file, and send a command to Chimera to open the
658 * file as a commands script. For use when sending a large number of separate
659 * commands would overload the REST interface mechanism.
663 protected void sendCommandsByFile(List<StructureCommandI> commands)
667 File tmp = File.createTempFile("chim", getCommandFileExtension());
669 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
670 for (StructureCommandI command : commands)
672 out.println(command.getCommand());
676 String path = tmp.getAbsolutePath();
677 StructureCommandI command = getCommandGenerator()
678 .openCommandFile(path);
679 sendAsynchronousCommand(command, null);
680 } catch (IOException e)
682 System.err.println("Sending commands to Chimera via file failed with "
688 * Returns the file extension required for a file of commands to be read by
689 * the structure viewer
692 protected String getCommandFileExtension()
698 * Get Chimera residues which have the named attribute, find the mapped
699 * positions in the Jalview sequence(s), and set as sequence features
702 * @param alignmentPanel
704 public void copyStructureAttributesToFeatures(String attName,
705 AlignmentViewPanel alignmentPanel)
707 // todo pull up to AAStructureBindingModel (and interface?)
710 * ask Chimera to list residues with the attribute, reporting its value
712 // this alternative command
713 // list residues spec ':*/attName' attr attName
714 // doesn't report 'None' values (which is good), but
715 // fails for 'average.bfactor' (which is bad):
717 String cmd = "list residues attr '" + attName + "'";
718 List<String> residues = executeCommand(new StructureCommand(cmd), true);
720 boolean featureAdded = createFeaturesForAttributes(attName, residues);
723 alignmentPanel.getFeatureRenderer().featuresAdded();
728 * Create features in Jalview for the given attribute name and structure
732 * The residue list should be 0, 1 or more reply lines of the format:
733 * residue id #0:5.A isHelix -155.000836316 index 5
735 * residue id #0:6.A isHelix None
742 protected boolean createFeaturesForAttributes(String attName,
743 List<String> residues)
745 boolean featureAdded = false;
746 String featureGroup = getViewerFeatureGroup();
747 boolean chimeraX = chimeraManager.isChimeraX();
749 for (String residue : residues)
751 AtomSpec spec = null;
752 String[] tokens = residue.split(" ");
753 if (tokens.length < 5)
757 String atomSpec = tokens[2];
758 String attValue = tokens[4];
761 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
763 if ("None".equalsIgnoreCase(attValue)
764 || "False".equalsIgnoreCase(attValue))
771 spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
772 } catch (IllegalArgumentException e)
774 System.err.println("Problem parsing atomspec " + atomSpec);
778 String chainId = spec.getChain();
779 String description = attValue;
780 float score = Float.NaN;
783 score = Float.valueOf(attValue);
784 description = chainId;
785 } catch (NumberFormatException e)
787 // was not a float value
790 String pdbFile = getPdbFileForModel(spec.getModelNumber());
791 spec.setPdbFile(pdbFile);
793 List<AtomSpec> atoms = Collections.singletonList(spec);
796 * locate the mapped position in the alignment (if any)
798 SearchResultsI sr = getSsm()
799 .findAlignmentPositionsForStructurePositions(atoms);
802 * expect one matched alignment position, or none
803 * (if the structure position is not mapped)
805 for (SearchResultMatchI m : sr.getResults())
807 SequenceI seq = m.getSequence();
808 int start = m.getStart();
809 int end = m.getEnd();
810 SequenceFeature sf = new SequenceFeature(attName, description,
811 start, end, score, featureGroup);
812 // todo: should SequenceFeature have an explicit property for chain?
813 // note: repeating the action shouldn't duplicate features
814 featureAdded |= seq.addSequenceFeature(sf);
821 * Answers the feature group name to apply to features created in Jalview from
826 protected String getViewerFeatureGroup()
828 // todo pull up to interface
829 return CHIMERA_FEATURE_GROUP;
833 public String getModelIdForFile(String pdbFile)
835 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
836 if (foundModels != null && !foundModels.isEmpty())
838 return String.valueOf(foundModels.get(0).getModelNumber());
844 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
845 * any which were added from Jalview
849 public List<String> getChimeraAttributes()
851 List<String> atts = chimeraManager.getAttrList();
852 Iterator<String> it = atts.iterator();
855 if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
858 * attribute added from Jalview - exclude it
867 * Returns the file extension to use for a saved viewer session file
871 public String getSessionFileExtension()
876 public String getHelpURL()
878 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";