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;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.PrintWriter;
27 import java.net.BindException;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Iterator;
31 import java.util.LinkedHashMap;
32 import java.util.List;
35 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
36 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
37 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
38 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.api.structures.JalviewStructureDisplayI;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SearchResultMatchI;
44 import jalview.datamodel.SearchResultsI;
45 import jalview.datamodel.SequenceFeature;
46 import jalview.datamodel.SequenceI;
47 import jalview.gui.StructureViewer.ViewerType;
48 import jalview.httpserver.AbstractRequestHandler;
49 import jalview.io.DataSourceType;
50 import jalview.structure.AtomSpec;
51 import jalview.structure.StructureCommand;
52 import jalview.structure.StructureCommandI;
53 import jalview.structure.StructureSelectionManager;
54 import jalview.structures.models.AAStructureBindingModel;
56 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
58 public static final String CHIMERA_SESSION_EXTENSION = ".py";
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
248 public void closeViewer(boolean closeChimera)
250 super.closeViewer(closeChimera);
253 chimeraManager.exitChimera();
255 if (this.chimeraListener != null)
257 chimeraListener.shutdown();
258 chimeraListener = null;
260 chimeraManager = null;
262 if (chimeraMonitor != null)
264 chimeraMonitor.interrupt();
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
342 public boolean isViewerRunning()
344 return chimeraManager.isChimeraLaunched();
348 * Send a command to Chimera, and optionally log and return any responses.
354 public List<String> executeCommand(final StructureCommandI command,
357 if (chimeraManager == null || command == null)
359 // ? thread running after viewer shut down
362 List<String> reply = null;
363 // trim command or it may never find a match in the replyLog!!
364 String cmd = command.getCommand().trim();
365 List<String> lastReply = chimeraManager
366 .sendChimeraCommand(cmd, getResponse);
372 log("Response from command ('" + cmd + "') was:\n" + lastReply);
380 public synchronized String[] getStructureFiles()
382 if (chimeraManager == null)
384 return new String[0];
387 return chimeraMaps.keySet()
388 .toArray(modelFileNames = new String[chimeraMaps.size()]);
392 * Construct and send a command to highlight zero, one or more atoms. We do this
393 * by sending an "rlabel" command to show the residue label at that position.
396 public void highlightAtoms(List<AtomSpec> atoms)
398 if (atoms == null || atoms.size() == 0)
403 boolean forChimeraX = chimeraManager.isChimeraX();
404 StringBuilder cmd = new StringBuilder(128);
405 boolean first = true;
406 boolean found = false;
408 for (AtomSpec atom : atoms)
410 int pdbResNum = atom.getPdbResNum();
411 String chain = atom.getChain();
412 String pdbfile = atom.getPdbFile();
413 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
414 if (cms != null && !cms.isEmpty())
418 cmd.append(forChimeraX ? "label #" : "rlabel #");
427 cmd.append(cms.get(0).getModelNumber())
428 .append("/").append(chain).append(":").append(pdbResNum);
432 cmd.append(cms.get(0).getModelNumber())
433 .append(":").append(pdbResNum);
434 if (!chain.equals(" ") && !forChimeraX)
436 cmd.append(".").append(chain);
442 String command = cmd.toString();
445 * avoid repeated commands for the same residue
447 if (command.equals(lastHighlightCommand))
453 * unshow the label for the previous residue
455 if (lastHighlightCommand != null)
457 chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
461 chimeraManager.sendChimeraCommand(command, false);
463 this.lastHighlightCommand = command;
467 * Query Chimera for its current selection, and highlight it on the alignment
469 public void highlightChimeraSelection()
472 * Ask Chimera for its current selection
474 List<String> selection = chimeraManager.getSelectedResidueSpecs();
477 * Parse model number, residue and chain for each selected position,
478 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
480 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
484 * Broadcast the selection (which may be empty, if the user just cleared all
487 getSsm().mouseOverStructure(atomSpecs);
491 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
492 * corresponding residues (if any) in Jalview
494 * @param structureSelection
497 protected List<AtomSpec> convertStructureResiduesToAlignment(
498 List<String> structureSelection)
500 boolean chimeraX = chimeraManager.isChimeraX();
501 List<AtomSpec> atomSpecs = new ArrayList<>();
502 for (String atomSpec : structureSelection)
506 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
507 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
508 spec.setPdbFile(pdbfilename);
510 } catch (IllegalArgumentException e)
512 System.err.println("Failed to parse atomspec: " + atomSpec);
522 protected String getPdbFileForModel(int modelId)
525 * Work out the pdbfilename from the model number
527 String pdbfilename = modelFileNames[0];
528 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
530 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
532 if (cm.getModelNumber() == modelId)
534 pdbfilename = pdbfile;
542 private void log(String message)
544 System.err.println("## Chimera log: " + message);
548 * Ask Chimera to open a session file. Returns true if successful, else false.
549 * The filename must have a .py (Chimera) or .cxs (ChimeraX) extension for
550 * this command to work.
555 public boolean openSession(String filepath)
558 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/open.html
559 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/open.html
561 executeCommand(getCommandGenerator().loadFile(filepath), true);
562 // todo: test for failure - how?
567 * Send a 'show' command for all atoms in the currently selected columns
569 * TODO: pull up to abstract structure viewer interface
573 public void highlightSelection(AlignmentViewPanel vp)
575 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
577 AlignmentI alignment = vp.getAlignment();
578 StructureSelectionManager sm = getSsm();
579 for (SequenceI seq : alignment.getSequences())
582 * convert selected columns into sequence positions
584 int[] positions = new int[cols.size()];
586 for (Integer col : cols)
588 positions[i++] = seq.findPosition(col);
590 sm.highlightStructure(this, seq, positions);
595 * Constructs and send commands to Chimera to set attributes on residues for
596 * features visible in Jalview
601 public int sendFeaturesToViewer(AlignmentViewPanel avp)
603 // TODO refactor as required to pull up to an interface
604 String[] files = getStructureFiles();
610 List<StructureCommandI> commands = getCommandGenerator()
611 .setAttributesForFeatures(getSsm(), files, getSequence(), avp);
612 if (commands.size() > 10)
614 sendCommandsByFile(commands);
618 for (StructureCommandI command : commands)
620 sendAsynchronousCommand(command, null);
623 return commands.size();
627 * Write commands to a temporary file, and send a command to Chimera to open the
628 * file as a commands script. For use when sending a large number of separate
629 * commands would overload the REST interface mechanism.
633 protected void sendCommandsByFile(List<StructureCommandI> commands)
637 File tmp = File.createTempFile("chim", getCommandFileExtension());
639 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
640 for (StructureCommandI command : commands)
642 out.println(command.getCommand());
646 String path = tmp.getAbsolutePath();
647 StructureCommandI command = getCommandGenerator()
648 .openCommandFile(path);
649 sendAsynchronousCommand(command, null);
650 } catch (IOException e)
652 System.err.println("Sending commands to Chimera via file failed with "
658 * Returns the file extension required for a file of commands to be read by
659 * the structure viewer
662 protected String getCommandFileExtension()
668 * Get Chimera residues which have the named attribute, find the mapped
669 * positions in the Jalview sequence(s), and set as sequence features
672 * @param alignmentPanel
674 public void copyStructureAttributesToFeatures(String attName,
675 AlignmentViewPanel alignmentPanel)
677 // todo pull up to AAStructureBindingModel (and interface?)
680 * ask Chimera to list residues with the attribute, reporting its value
682 // this alternative command
683 // list residues spec ':*/attName' attr attName
684 // doesn't report 'None' values (which is good), but
685 // fails for 'average.bfactor' (which is bad):
687 String cmd = "list residues attr '" + attName + "'";
688 List<String> residues = executeCommand(new StructureCommand(cmd), true);
690 boolean featureAdded = createFeaturesForAttributes(attName, residues);
693 alignmentPanel.getFeatureRenderer().featuresAdded();
698 * Create features in Jalview for the given attribute name and structure
702 * The residue list should be 0, 1 or more reply lines of the format:
703 * residue id #0:5.A isHelix -155.000836316 index 5
705 * residue id #0:6.A isHelix None
712 protected boolean createFeaturesForAttributes(String attName,
713 List<String> residues)
715 boolean featureAdded = false;
716 String featureGroup = getViewerFeatureGroup();
717 boolean chimeraX = chimeraManager.isChimeraX();
719 for (String residue : residues)
721 AtomSpec spec = null;
722 String[] tokens = residue.split(" ");
723 if (tokens.length < 5)
727 String atomSpec = tokens[2];
728 String attValue = tokens[4];
731 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
733 if ("None".equalsIgnoreCase(attValue)
734 || "False".equalsIgnoreCase(attValue))
741 spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
742 } catch (IllegalArgumentException e)
744 System.err.println("Problem parsing atomspec " + atomSpec);
748 String chainId = spec.getChain();
749 String description = attValue;
750 float score = Float.NaN;
753 score = Float.valueOf(attValue);
754 description = chainId;
755 } catch (NumberFormatException e)
757 // was not a float value
760 String pdbFile = getPdbFileForModel(spec.getModelNumber());
761 spec.setPdbFile(pdbFile);
763 List<AtomSpec> atoms = Collections.singletonList(spec);
766 * locate the mapped position in the alignment (if any)
768 SearchResultsI sr = getSsm()
769 .findAlignmentPositionsForStructurePositions(atoms);
772 * expect one matched alignment position, or none
773 * (if the structure position is not mapped)
775 for (SearchResultMatchI m : sr.getResults())
777 SequenceI seq = m.getSequence();
778 int start = m.getStart();
779 int end = m.getEnd();
780 SequenceFeature sf = new SequenceFeature(attName, description,
781 start, end, score, featureGroup);
782 // todo: should SequenceFeature have an explicit property for chain?
783 // note: repeating the action shouldn't duplicate features
784 featureAdded |= seq.addSequenceFeature(sf);
791 * Answers the feature group name to apply to features created in Jalview from
796 protected String getViewerFeatureGroup()
798 // todo pull up to interface
799 return CHIMERA_FEATURE_GROUP;
803 public String getModelIdForFile(String pdbFile)
805 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
806 if (foundModels != null && !foundModels.isEmpty())
808 return String.valueOf(foundModels.get(0).getModelNumber());
814 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
815 * any which were added from Jalview
819 public List<String> getChimeraAttributes()
821 List<String> atts = chimeraManager.getAttrList();
822 Iterator<String> it = atts.iterator();
825 if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
828 * attribute added from Jalview - exclude it
837 * Returns the file extension to use for a saved viewer session file (.py)
842 public String getSessionFileExtension()
844 return CHIMERA_SESSION_EXTENSION;
847 public String getHelpURL()
849 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";