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_FEATURE_GROUP = "Chimera";
61 // Chimera clause to exclude alternate locations in atom selection
62 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
64 private static final boolean debug = false;
66 private static final String PHOSPHORUS = "P";
68 private static final String ALPHACARBON = "CA";
71 * Object through which we talk to Chimera
73 private ChimeraManager chimeraManager;
76 * Object which listens to Chimera notifications
78 private AbstractRequestHandler chimeraListener;
81 * Map of ChimeraModel objects keyed by PDB full local file name
83 protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
85 String lastHighlightCommand;
87 private Thread chimeraMonitor;
90 * Open a PDB structure file in Chimera and set up mappings from Jalview.
92 * We check if the PDB model id is already loaded in Chimera, if so don't reopen
93 * it. This is the case if Chimera has opened a saved session file.
98 public boolean openFile(PDBEntry pe)
100 String file = pe.getFile();
103 List<ChimeraModel> modelsToMap = new ArrayList<>();
104 List<ChimeraModel> oldList = chimeraManager.getModelList();
105 boolean alreadyOpen = false;
108 * If Chimera already has this model, don't reopen it, but do remap it.
110 for (ChimeraModel open : oldList)
112 if (open.getModelName().equals(pe.getId()))
115 modelsToMap.add(open);
120 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
121 * the model name(s) added by Chimera.
125 chimeraManager.openModel(file, pe.getId(), ModelType.PDB_MODEL);
126 addChimeraModel(pe, modelsToMap);
129 chimeraMaps.put(file, modelsToMap);
131 if (getSsm() != null)
133 getSsm().addStructureViewerListener(this);
136 } catch (Exception q)
138 log("Exception when trying to open model " + file + "\n"
146 * Adds the ChimeraModel corresponding to the given PDBEntry, based on model
147 * name matching PDB id
152 protected void addChimeraModel(PDBEntry pe,
153 List<ChimeraModel> modelsToMap)
156 * Chimera: query for actual models and find the one with
157 * matching model name - already set in viewer.openModel()
159 List<ChimeraModel> newList = chimeraManager.getModelList();
160 // JAL-1728 newList.removeAll(oldList) does not work
161 for (ChimeraModel cm : newList)
163 if (cm.getModelName().equals(pe.getId()))
178 public JalviewChimeraBinding(StructureSelectionManager ssm,
179 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
180 DataSourceType protocol)
182 super(ssm, pdbentry, sequenceIs, protocol);
183 chimeraManager = new ChimeraManager(new StructureManager(true));
184 chimeraManager.setChimeraX(ViewerType.CHIMERAX.equals(getViewerType()));
185 setStructureCommands(new ChimeraCommands());
189 protected ViewerType getViewerType()
191 return ViewerType.CHIMERA;
195 * Starts a thread that waits for the Chimera process to finish, so that we can
196 * then close the associated resources. This avoids leaving orphaned Chimera
197 * viewer panels in Jalview if the user closes Chimera.
199 protected void startChimeraProcessMonitor()
201 final Process p = chimeraManager.getChimeraProcess();
202 chimeraMonitor = new Thread(new Runnable()
211 JalviewStructureDisplayI display = getViewer();
214 display.closeViewer(false);
216 } catch (InterruptedException e)
218 // exit thread if Chimera Viewer is closed in Jalview
222 chimeraMonitor.start();
226 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
229 public void startChimeraListener()
233 chimeraListener = new ChimeraListener(this);
234 chimeraManager.startListening(chimeraListener.getUri());
235 } catch (BindException e)
238 "Failed to start Chimera listener: " + e.getMessage());
243 * Close down the Jalview viewer and listener, and (optionally) the associated
246 public void closeViewer(boolean closeChimera)
248 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
251 chimeraManager.exitChimera();
253 if (this.chimeraListener != null)
255 chimeraListener.shutdown();
256 chimeraListener = null;
258 chimeraManager = null;
260 if (chimeraMonitor != null)
262 chimeraMonitor.interrupt();
264 releaseUIResources();
268 * Helper method to construct model spec in Chimera format:
270 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
271 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
273 * Note for now we only ever choose the first of multiple models. This
274 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
275 * future if there is a need to select specific sub-models.
280 protected String getModelSpec(int pdbfnum)
282 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
284 return "#" + pdbfnum; // temp hack for ChimeraX
288 * For now, the test for having sub-models is whether multiple Chimera
289 * models are mapped for the PDB file; the models are returned as a response
290 * to the Chimera command 'list models type molecule', see
291 * ChimeraManager.getModelList().
293 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
294 boolean hasSubModels = maps != null && maps.size() > 1;
295 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
299 * Launch Chimera, unless an instance linked to this object is already
300 * running. Returns true if Chimera is successfully launched, or already
301 * running, else false.
305 public boolean launchChimera()
307 if (chimeraManager.isChimeraLaunched())
312 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
315 startChimeraProcessMonitor();
319 log("Failed to launch Chimera!");
325 * Returns a list of candidate paths to the Chimera program executable
329 protected List<String> getChimeraPaths()
331 return StructureManager.getChimeraPaths(false);
335 * Answers true if the Chimera process is still running, false if ended or not
340 public boolean isChimeraRunning()
342 return chimeraManager.isChimeraLaunched();
346 * Send a command to Chimera, and optionally log and return any responses.
352 public List<String> executeCommand(final StructureCommandI command,
355 if (chimeraManager == null || command == null)
357 // ? thread running after viewer shut down
360 List<String> reply = null;
361 // trim command or it may never find a match in the replyLog!!
362 String cmd = command.getCommand().trim();
363 List<String> lastReply = chimeraManager
364 .sendChimeraCommand(cmd, getResponse);
370 log("Response from command ('" + cmd + "') was:\n" + lastReply);
378 public synchronized String[] getStructureFiles()
380 if (chimeraManager == null)
382 return new String[0];
385 return chimeraMaps.keySet()
386 .toArray(modelFileNames = new String[chimeraMaps.size()]);
390 * Construct and send a command to highlight zero, one or more atoms. We do this
391 * by sending an "rlabel" command to show the residue label at that position.
394 public void highlightAtoms(List<AtomSpec> atoms)
396 if (atoms == null || atoms.size() == 0)
401 boolean forChimeraX = chimeraManager.isChimeraX();
402 StringBuilder cmd = new StringBuilder(128);
403 boolean first = true;
404 boolean found = false;
406 for (AtomSpec atom : atoms)
408 int pdbResNum = atom.getPdbResNum();
409 String chain = atom.getChain();
410 String pdbfile = atom.getPdbFile();
411 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
412 if (cms != null && !cms.isEmpty())
416 cmd.append(forChimeraX ? "label #" : "rlabel #");
425 cmd.append(cms.get(0).getModelNumber())
426 .append("/").append(chain).append(":").append(pdbResNum);
430 cmd.append(cms.get(0).getModelNumber())
431 .append(":").append(pdbResNum);
432 if (!chain.equals(" ") && !forChimeraX)
434 cmd.append(".").append(chain);
440 String command = cmd.toString();
443 * avoid repeated commands for the same residue
445 if (command.equals(lastHighlightCommand))
451 * unshow the label for the previous residue
453 if (lastHighlightCommand != null)
455 chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
459 chimeraManager.sendChimeraCommand(command, false);
461 this.lastHighlightCommand = command;
465 * Query Chimera for its current selection, and highlight it on the alignment
467 public void highlightChimeraSelection()
470 * Ask Chimera for its current selection
472 List<String> selection = chimeraManager.getSelectedResidueSpecs();
475 * Parse model number, residue and chain for each selected position,
476 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
478 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
482 * Broadcast the selection (which may be empty, if the user just cleared all
485 getSsm().mouseOverStructure(atomSpecs);
489 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
490 * corresponding residues (if any) in Jalview
492 * @param structureSelection
495 protected List<AtomSpec> convertStructureResiduesToAlignment(
496 List<String> structureSelection)
498 boolean chimeraX = chimeraManager.isChimeraX();
499 List<AtomSpec> atomSpecs = new ArrayList<>();
500 for (String atomSpec : structureSelection)
504 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
505 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
506 spec.setPdbFile(pdbfilename);
508 } catch (IllegalArgumentException e)
510 System.err.println("Failed to parse atomspec: " + atomSpec);
520 protected String getPdbFileForModel(int modelId)
523 * Work out the pdbfilename from the model number
525 String pdbfilename = modelFileNames[0];
526 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
528 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
530 if (cm.getModelNumber() == modelId)
532 pdbfilename = pdbfile;
540 private void log(String message)
542 System.err.println("## Chimera log: " + message);
546 * Ask Chimera to save its session to the given file. Returns true if
547 * successful, else false.
552 public boolean saveSession(String filepath)
554 if (isChimeraRunning())
557 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
558 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/save.html
560 String command = getCommandGenerator().saveSession(filepath)
562 List<String> reply = chimeraManager.sendChimeraCommand(command, true);
563 if (reply.contains("Session written"))
570 .error("Error saving Chimera session: " + reply.toString());
577 * Ask Chimera to open a session file. Returns true if successful, else false.
578 * The filename must have a .py (Chimera) or .cxs (ChimeraX) extension for
579 * this command to work.
584 public boolean openSession(String filepath)
587 * Chimera: https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/open.html
588 * ChimeraX: https://www.cgl.ucsf.edu/chimerax/docs/user/commands/open.html
590 executeCommand(getCommandGenerator().loadFile(filepath), true);
591 // todo: test for failure - how?
596 * Send a 'show' command for all atoms in the currently selected columns
598 * TODO: pull up to abstract structure viewer interface
602 public void highlightSelection(AlignmentViewPanel vp)
604 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
606 AlignmentI alignment = vp.getAlignment();
607 StructureSelectionManager sm = getSsm();
608 for (SequenceI seq : alignment.getSequences())
611 * convert selected columns into sequence positions
613 int[] positions = new int[cols.size()];
615 for (Integer col : cols)
617 positions[i++] = seq.findPosition(col);
619 sm.highlightStructure(this, seq, positions);
624 * Constructs and send commands to Chimera to set attributes on residues for
625 * features visible in Jalview
630 public int sendFeaturesToViewer(AlignmentViewPanel avp)
632 // TODO refactor as required to pull up to an interface
633 String[] files = getStructureFiles();
639 List<StructureCommandI> commands = getCommandGenerator()
640 .setAttributesForFeatures(getSsm(), files, getSequence(), avp);
641 if (commands.size() > 10)
643 sendCommandsByFile(commands);
647 for (StructureCommandI command : commands)
649 sendAsynchronousCommand(command, null);
652 return commands.size();
656 * Write commands to a temporary file, and send a command to Chimera to open the
657 * file as a commands script. For use when sending a large number of separate
658 * commands would overload the REST interface mechanism.
662 protected void sendCommandsByFile(List<StructureCommandI> commands)
666 File tmp = File.createTempFile("chim", getCommandFileExtension());
668 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
669 for (StructureCommandI command : commands)
671 out.println(command.getCommand());
675 String path = tmp.getAbsolutePath();
676 StructureCommandI command = getCommandGenerator()
677 .openCommandFile(path);
678 sendAsynchronousCommand(command, null);
679 } catch (IOException e)
681 System.err.println("Sending commands to Chimera via file failed with "
687 * Returns the file extension required for a file of commands to be read by
688 * the structure viewer
691 protected String getCommandFileExtension()
697 * Get Chimera residues which have the named attribute, find the mapped
698 * positions in the Jalview sequence(s), and set as sequence features
701 * @param alignmentPanel
703 public void copyStructureAttributesToFeatures(String attName,
704 AlignmentViewPanel alignmentPanel)
706 // todo pull up to AAStructureBindingModel (and interface?)
709 * ask Chimera to list residues with the attribute, reporting its value
711 // this alternative command
712 // list residues spec ':*/attName' attr attName
713 // doesn't report 'None' values (which is good), but
714 // fails for 'average.bfactor' (which is bad):
716 String cmd = "list residues attr '" + attName + "'";
717 List<String> residues = executeCommand(new StructureCommand(cmd), true);
719 boolean featureAdded = createFeaturesForAttributes(attName, residues);
722 alignmentPanel.getFeatureRenderer().featuresAdded();
727 * Create features in Jalview for the given attribute name and structure
731 * The residue list should be 0, 1 or more reply lines of the format:
732 * residue id #0:5.A isHelix -155.000836316 index 5
734 * residue id #0:6.A isHelix None
741 protected boolean createFeaturesForAttributes(String attName,
742 List<String> residues)
744 boolean featureAdded = false;
745 String featureGroup = getViewerFeatureGroup();
746 boolean chimeraX = chimeraManager.isChimeraX();
748 for (String residue : residues)
750 AtomSpec spec = null;
751 String[] tokens = residue.split(" ");
752 if (tokens.length < 5)
756 String atomSpec = tokens[2];
757 String attValue = tokens[4];
760 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
762 if ("None".equalsIgnoreCase(attValue)
763 || "False".equalsIgnoreCase(attValue))
770 spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
771 } catch (IllegalArgumentException e)
773 System.err.println("Problem parsing atomspec " + atomSpec);
777 String chainId = spec.getChain();
778 String description = attValue;
779 float score = Float.NaN;
782 score = Float.valueOf(attValue);
783 description = chainId;
784 } catch (NumberFormatException e)
786 // was not a float value
789 String pdbFile = getPdbFileForModel(spec.getModelNumber());
790 spec.setPdbFile(pdbFile);
792 List<AtomSpec> atoms = Collections.singletonList(spec);
795 * locate the mapped position in the alignment (if any)
797 SearchResultsI sr = getSsm()
798 .findAlignmentPositionsForStructurePositions(atoms);
801 * expect one matched alignment position, or none
802 * (if the structure position is not mapped)
804 for (SearchResultMatchI m : sr.getResults())
806 SequenceI seq = m.getSequence();
807 int start = m.getStart();
808 int end = m.getEnd();
809 SequenceFeature sf = new SequenceFeature(attName, description,
810 start, end, score, featureGroup);
811 // todo: should SequenceFeature have an explicit property for chain?
812 // note: repeating the action shouldn't duplicate features
813 featureAdded |= seq.addSequenceFeature(sf);
820 * Answers the feature group name to apply to features created in Jalview from
825 protected String getViewerFeatureGroup()
827 // todo pull up to interface
828 return CHIMERA_FEATURE_GROUP;
832 public String getModelIdForFile(String pdbFile)
834 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
835 if (foundModels != null && !foundModels.isEmpty())
837 return String.valueOf(foundModels.get(0).getModelNumber());
843 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
844 * any which were added from Jalview
848 public List<String> getChimeraAttributes()
850 List<String> atts = chimeraManager.getAttrList();
851 Iterator<String> it = atts.iterator();
854 if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
857 * attribute added from Jalview - exclude it
866 * Returns the file extension to use for a saved viewer session file (.py)
871 public String getSessionFileExtension()
876 public String getHelpURL()
878 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";