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.bin.Cache;
42 import jalview.datamodel.AlignmentI;
43 import jalview.datamodel.PDBEntry;
44 import jalview.datamodel.SearchResultMatchI;
45 import jalview.datamodel.SearchResultsI;
46 import jalview.datamodel.SequenceFeature;
47 import jalview.datamodel.SequenceI;
48 import jalview.gui.StructureViewer.ViewerType;
49 import jalview.httpserver.AbstractRequestHandler;
50 import jalview.io.DataSourceType;
51 import jalview.structure.AtomSpec;
52 import jalview.structure.StructureCommand;
53 import jalview.structure.StructureCommandI;
54 import jalview.structure.StructureSelectionManager;
55 import jalview.structures.models.AAStructureBindingModel;
57 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
59 public static final String CHIMERA_SESSION_EXTENSION = ".py";
61 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
63 // Chimera clause to exclude alternate locations in atom selection
64 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
66 private static final boolean debug = false;
68 private static final String PHOSPHORUS = "P";
70 private static final String ALPHACARBON = "CA";
73 * Object through which we talk to Chimera
75 private ChimeraManager chimeraManager;
78 * Object which listens to Chimera notifications
80 private AbstractRequestHandler chimeraListener;
83 * Map of ChimeraModel objects keyed by PDB full local file name
85 protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
87 String lastHighlightCommand;
89 private Thread chimeraMonitor;
92 * Open a PDB structure file in Chimera and set up mappings from Jalview.
94 * We check if the PDB model id is already loaded in Chimera, if so don't reopen
95 * it. This is the case if Chimera has opened a saved session file.
100 public boolean openFile(PDBEntry pe)
102 String file = pe.getFile();
105 List<ChimeraModel> modelsToMap = new ArrayList<>();
106 List<ChimeraModel> oldList = chimeraManager.getModelList();
107 boolean alreadyOpen = false;
110 * If Chimera already has this model, don't reopen it, but do remap it.
112 for (ChimeraModel open : oldList)
114 if (open.getModelName().equals(pe.getId()))
117 modelsToMap.add(open);
122 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
123 * the model name(s) added by Chimera.
127 chimeraManager.openModel(file, pe.getId(), ModelType.PDB_MODEL);
128 addChimeraModel(pe, modelsToMap);
131 chimeraMaps.put(file, modelsToMap);
133 if (getSsm() != null)
135 getSsm().addStructureViewerListener(this);
138 } catch (Exception q)
140 log("Exception when trying to open model " + file + "\n"
148 * Adds the ChimeraModel corresponding to the given PDBEntry, based on model
149 * name matching PDB id
154 protected void addChimeraModel(PDBEntry pe,
155 List<ChimeraModel> modelsToMap)
158 * Chimera: query for actual models and find the one with
159 * matching model name - already set in viewer.openModel()
161 List<ChimeraModel> newList = chimeraManager.getModelList();
162 // JAL-1728 newList.removeAll(oldList) does not work
163 for (ChimeraModel cm : newList)
165 if (cm.getModelName().equals(pe.getId()))
180 public JalviewChimeraBinding(StructureSelectionManager ssm,
181 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
182 DataSourceType protocol)
184 super(ssm, pdbentry, sequenceIs, protocol);
185 chimeraManager = new ChimeraManager(new StructureManager(true));
186 chimeraManager.setChimeraX(ViewerType.CHIMERAX.equals(getViewerType()));
187 setStructureCommands(new ChimeraCommands());
191 protected ViewerType getViewerType()
193 return ViewerType.CHIMERA;
197 * Starts a thread that waits for the Chimera process to finish, so that we can
198 * then close the associated resources. This avoids leaving orphaned Chimera
199 * viewer panels in Jalview if the user closes Chimera.
201 protected void startChimeraProcessMonitor()
203 final Process p = chimeraManager.getChimeraProcess();
204 chimeraMonitor = new Thread(new Runnable()
213 JalviewStructureDisplayI display = getViewer();
216 display.closeViewer(false);
218 } catch (InterruptedException e)
220 // exit thread if Chimera Viewer is closed in Jalview
224 chimeraMonitor.start();
228 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
231 public void startChimeraListener()
235 chimeraListener = new ChimeraListener(this);
236 chimeraManager.startListening(chimeraListener.getUri());
237 } catch (BindException e)
240 "Failed to start Chimera listener: " + e.getMessage());
245 * Close down the Jalview viewer and listener, and (optionally) the associated
248 public void closeViewer(boolean closeChimera)
250 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
253 chimeraManager.exitChimera();
255 if (this.chimeraListener != null)
257 chimeraListener.shutdown();
258 chimeraListener = null;
260 chimeraManager = null;
262 if (chimeraMonitor != null)
264 chimeraMonitor.interrupt();
266 releaseUIResources();
270 * Helper method to construct model spec in Chimera format:
272 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
273 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
275 * Note for now we only ever choose the first of multiple models. This
276 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
277 * future if there is a need to select specific sub-models.
282 protected String getModelSpec(int pdbfnum)
284 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
286 return "#" + pdbfnum; // temp hack for ChimeraX
290 * For now, the test for having sub-models is whether multiple Chimera
291 * models are mapped for the PDB file; the models are returned as a response
292 * to the Chimera command 'list models type molecule', see
293 * ChimeraManager.getModelList().
295 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
296 boolean hasSubModels = maps != null && maps.size() > 1;
297 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
301 * Launch Chimera, unless an instance linked to this object is already
302 * running. Returns true if Chimera is successfully launched, or already
303 * running, else false.
307 public boolean launchChimera()
309 if (chimeraManager.isChimeraLaunched())
314 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
317 startChimeraProcessMonitor();
321 log("Failed to launch Chimera!");
327 * Returns a list of candidate paths to the Chimera program executable
331 protected List<String> getChimeraPaths()
333 return StructureManager.getChimeraPaths(false);
337 * Answers true if the Chimera process is still running, false if ended or not
342 public boolean isChimeraRunning()
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 save its session to the given file. Returns true if
549 * successful, else false.
554 public boolean saveSession(String filepath)
556 if (isChimeraRunning())
559 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
560 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/save.html
562 String command = getCommandGenerator().saveSession(filepath)
564 List<String> reply = chimeraManager.sendChimeraCommand(command, true);
565 if (reply.contains("Session written"))
572 .error("Error saving Chimera session: " + reply.toString());
579 * Ask Chimera to open a session file. Returns true if successful, else false.
580 * The filename must have a .py (Chimera) or .cxs (ChimeraX) extension for
581 * this command to work.
586 public boolean openSession(String filepath)
589 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/open.html
590 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/open.html
592 executeCommand(getCommandGenerator().loadFile(filepath), true);
593 // todo: test for failure - how?
598 * Send a 'show' command for all atoms in the currently selected columns
600 * TODO: pull up to abstract structure viewer interface
604 public void highlightSelection(AlignmentViewPanel vp)
606 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
608 AlignmentI alignment = vp.getAlignment();
609 StructureSelectionManager sm = getSsm();
610 for (SequenceI seq : alignment.getSequences())
613 * convert selected columns into sequence positions
615 int[] positions = new int[cols.size()];
617 for (Integer col : cols)
619 positions[i++] = seq.findPosition(col);
621 sm.highlightStructure(this, seq, positions);
626 * Constructs and send commands to Chimera to set attributes on residues for
627 * features visible in Jalview
632 public int sendFeaturesToViewer(AlignmentViewPanel avp)
634 // TODO refactor as required to pull up to an interface
635 String[] files = getStructureFiles();
641 List<StructureCommandI> commands = getCommandGenerator()
642 .setAttributesForFeatures(getSsm(), files, getSequence(), avp);
643 if (commands.size() > 10)
645 sendCommandsByFile(commands);
649 for (StructureCommandI command : commands)
651 sendAsynchronousCommand(command, null);
654 return commands.size();
658 * Write commands to a temporary file, and send a command to Chimera to open the
659 * file as a commands script. For use when sending a large number of separate
660 * commands would overload the REST interface mechanism.
664 protected void sendCommandsByFile(List<StructureCommandI> commands)
668 File tmp = File.createTempFile("chim", getCommandFileExtension());
670 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
671 for (StructureCommandI command : commands)
673 out.println(command.getCommand());
677 String path = tmp.getAbsolutePath();
678 StructureCommandI command = getCommandGenerator()
679 .openCommandFile(path);
680 sendAsynchronousCommand(command, null);
681 } catch (IOException e)
683 System.err.println("Sending commands to Chimera via file failed with "
689 * Returns the file extension required for a file of commands to be read by
690 * the structure viewer
693 protected String getCommandFileExtension()
699 * Get Chimera residues which have the named attribute, find the mapped
700 * positions in the Jalview sequence(s), and set as sequence features
703 * @param alignmentPanel
705 public void copyStructureAttributesToFeatures(String attName,
706 AlignmentViewPanel alignmentPanel)
708 // todo pull up to AAStructureBindingModel (and interface?)
711 * ask Chimera to list residues with the attribute, reporting its value
713 // this alternative command
714 // list residues spec ':*/attName' attr attName
715 // doesn't report 'None' values (which is good), but
716 // fails for 'average.bfactor' (which is bad):
718 String cmd = "list residues attr '" + attName + "'";
719 List<String> residues = executeCommand(new StructureCommand(cmd), true);
721 boolean featureAdded = createFeaturesForAttributes(attName, residues);
724 alignmentPanel.getFeatureRenderer().featuresAdded();
729 * Create features in Jalview for the given attribute name and structure
733 * The residue list should be 0, 1 or more reply lines of the format:
734 * residue id #0:5.A isHelix -155.000836316 index 5
736 * residue id #0:6.A isHelix None
743 protected boolean createFeaturesForAttributes(String attName,
744 List<String> residues)
746 boolean featureAdded = false;
747 String featureGroup = getViewerFeatureGroup();
748 boolean chimeraX = chimeraManager.isChimeraX();
750 for (String residue : residues)
752 AtomSpec spec = null;
753 String[] tokens = residue.split(" ");
754 if (tokens.length < 5)
758 String atomSpec = tokens[2];
759 String attValue = tokens[4];
762 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
764 if ("None".equalsIgnoreCase(attValue)
765 || "False".equalsIgnoreCase(attValue))
772 spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
773 } catch (IllegalArgumentException e)
775 System.err.println("Problem parsing atomspec " + atomSpec);
779 String chainId = spec.getChain();
780 String description = attValue;
781 float score = Float.NaN;
784 score = Float.valueOf(attValue);
785 description = chainId;
786 } catch (NumberFormatException e)
788 // was not a float value
791 String pdbFile = getPdbFileForModel(spec.getModelNumber());
792 spec.setPdbFile(pdbFile);
794 List<AtomSpec> atoms = Collections.singletonList(spec);
797 * locate the mapped position in the alignment (if any)
799 SearchResultsI sr = getSsm()
800 .findAlignmentPositionsForStructurePositions(atoms);
803 * expect one matched alignment position, or none
804 * (if the structure position is not mapped)
806 for (SearchResultMatchI m : sr.getResults())
808 SequenceI seq = m.getSequence();
809 int start = m.getStart();
810 int end = m.getEnd();
811 SequenceFeature sf = new SequenceFeature(attName, description,
812 start, end, score, featureGroup);
813 // todo: should SequenceFeature have an explicit property for chain?
814 // note: repeating the action shouldn't duplicate features
815 featureAdded |= seq.addSequenceFeature(sf);
822 * Answers the feature group name to apply to features created in Jalview from
827 protected String getViewerFeatureGroup()
829 // todo pull up to interface
830 return CHIMERA_FEATURE_GROUP;
834 public String getModelIdForFile(String pdbFile)
836 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
837 if (foundModels != null && !foundModels.isEmpty())
839 return String.valueOf(foundModels.get(0).getModelNumber());
845 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
846 * any which were added from Jalview
850 public List<String> getChimeraAttributes()
852 List<String> atts = chimeraManager.getAttrList();
853 Iterator<String> it = atts.iterator();
856 if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
859 * attribute added from Jalview - exclude it
868 * Returns the file extension to use for a saved viewer session file (.py)
873 public String getSessionFileExtension()
875 return CHIMERA_SESSION_EXTENSION;
878 public String getHelpURL()
880 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";