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.LinkedHashMap;
31 import java.util.List;
34 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
35 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
36 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
37 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
38 import jalview.api.AlignmentViewPanel;
39 import jalview.bin.Console;
40 import jalview.datamodel.PDBEntry;
41 import jalview.datamodel.SearchResultMatchI;
42 import jalview.datamodel.SearchResultsI;
43 import jalview.datamodel.SequenceFeature;
44 import jalview.datamodel.SequenceI;
45 import jalview.gui.StructureViewer.ViewerType;
46 import jalview.httpserver.AbstractRequestHandler;
47 import jalview.io.DataSourceType;
48 import jalview.structure.AtomSpec;
49 import jalview.structure.AtomSpecModel;
50 import jalview.structure.StructureCommand;
51 import jalview.structure.StructureCommandI;
52 import jalview.structure.StructureSelectionManager;
53 import jalview.structures.models.AAStructureBindingModel;
55 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
57 public static final String CHIMERA_SESSION_EXTENSION = ".py";
59 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
62 * Object through which we talk to Chimera
64 private ChimeraManager chimeraManager;
67 * Object which listens to Chimera notifications
69 private AbstractRequestHandler chimeraListener;
72 * Map of ChimeraModel objects keyed by PDB full local file name
74 protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
76 String lastHighlightCommand;
79 * Returns a model of the structure positions described by the Chimera format
85 protected AtomSpec parseAtomSpec(String atomSpec)
87 return AtomSpec.fromChimeraAtomspec(atomSpec);
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
94 * reopen 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 boolean chimeraX = ViewerType.CHIMERAX.equals(getViewerType());
185 chimeraManager = chimeraX
186 ? new ChimeraXManager(new StructureManager(true))
187 : new ChimeraManager(new StructureManager(true));
188 setStructureCommands(
189 chimeraX ? new ChimeraXCommands() : new ChimeraCommands());
193 protected ViewerType getViewerType()
195 return ViewerType.CHIMERA;
199 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
200 * it to start listening
202 public void startChimeraListener()
206 chimeraListener = new ChimeraListener(this);
207 startListening(chimeraListener.getUri());
208 } catch (BindException e)
211 "Failed to start Chimera listener: " + e.getMessage());
216 * Close down the Jalview viewer and listener, and (optionally) the associated
220 public void closeViewer(boolean closeChimera)
222 super.closeViewer(closeChimera);
223 if (this.chimeraListener != null)
225 chimeraListener.shutdown();
226 chimeraListener = null;
230 * the following call is added to avoid a stack trace error in Chimera
231 * after "stop really" is sent; Chimera > 1.14 will not need it; see also
232 * http://plato.cgl.ucsf.edu/trac/chimera/ticket/17597
234 if (closeChimera && (getViewerType() == ViewerType.CHIMERA))
236 chimeraManager.getChimeraProcess().destroy();
239 chimeraManager.clearOnChimeraExit();
240 chimeraManager = null;
244 * Helper method to construct model spec in Chimera format:
246 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
247 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
249 * Note for now we only ever choose the first of multiple models. This
250 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
251 * future if there is a need to select specific sub-models.
256 protected String getModelSpec(int pdbfnum)
258 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
260 return "#" + pdbfnum; // temp hack for ChimeraX
264 * For now, the test for having sub-models is whether multiple Chimera
265 * models are mapped for the PDB file; the models are returned as a response
266 * to the Chimera command 'list models type molecule', see
267 * ChimeraManager.getModelList().
269 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
270 boolean hasSubModels = maps != null && maps.size() > 1;
271 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
275 * Launch Chimera, unless an instance linked to this object is already
276 * running. Returns true if Chimera is successfully launched, or already
277 * running, else false.
281 public boolean launchChimera()
283 if (chimeraManager.isChimeraLaunched())
288 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
291 startExternalViewerMonitor(chimeraManager.getChimeraProcess());
295 log("Failed to launch Chimera!");
301 * Returns a list of candidate paths to the Chimera program executable
305 protected List<String> getChimeraPaths()
307 return StructureManager.getChimeraPaths(false);
311 * Answers true if the Chimera process is still running, false if ended or not
317 public boolean isViewerRunning()
319 return chimeraManager != null && chimeraManager.isChimeraLaunched();
323 * Send a command to Chimera, and optionally log and return any responses.
329 public List<String> executeCommand(final StructureCommandI command,
332 if (chimeraManager == null || command == null)
334 // ? thread running after viewer shut down
337 List<String> reply = null;
338 // trim command or it may never find a match in the replyLog!!
339 String cmd = command.getCommand().trim();
340 List<String> lastReply = chimeraManager.sendChimeraCommand(cmd,
345 if (Console.isDebugEnabled())
348 "Response from command ('" + cmd + "') was:\n" + lastReply);
353 if (Console.isDebugEnabled())
355 Console.debug("Command executed: " + cmd);
363 public synchronized String[] getStructureFiles()
365 if (chimeraManager == null)
367 return new String[0];
370 return chimeraMaps.keySet()
371 .toArray(modelFileNames = new String[chimeraMaps.size()]);
375 * Construct and send a command to highlight zero, one or more atoms. We do
376 * this by sending an "rlabel" command to show the residue label at that
380 public void highlightAtoms(List<AtomSpec> atoms)
382 if (atoms == null || atoms.size() == 0)
387 boolean forChimeraX = chimeraManager.isChimeraX();
388 StringBuilder cmd = new StringBuilder(128);
389 boolean first = true;
390 boolean found = false;
392 for (AtomSpec atom : atoms)
394 int pdbResNum = atom.getPdbResNum();
395 String chain = atom.getChain();
396 String pdbfile = atom.getPdbFile();
397 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
398 if (cms != null && !cms.isEmpty())
402 cmd.append(forChimeraX ? "label #" : "rlabel #");
411 cmd.append(cms.get(0).getModelNumber()).append("/").append(chain)
412 .append(":").append(pdbResNum);
416 cmd.append(cms.get(0).getModelNumber()).append(":")
418 if (!chain.equals(" ") && !forChimeraX)
420 cmd.append(".").append(chain);
426 String command = cmd.toString();
429 * avoid repeated commands for the same residue
431 if (command.equals(lastHighlightCommand))
437 // not a valid residue label command, so clear
441 * prepend with command
442 * to unshow the label for the previous residue
444 if (lastHighlightCommand != null)
447 cmd.insert(0, lastHighlightCommand);
451 if (cmd.length() > 0)
453 executeCommand(true, null, new StructureCommand(cmd.toString()));
458 this.lastHighlightCommand = command;
463 * Query Chimera for its current selection, and highlight it on the alignment
465 public void highlightChimeraSelection()
468 * Ask Chimera for its current selection
470 StructureCommandI command = getCommandGenerator().getSelectedResidues();
472 Runnable action = new Runnable()
477 List<String> chimeraReply = executeCommand(command, true);
479 List<String> selectedResidues = new ArrayList<>();
480 if (chimeraReply != null)
483 * expect 0, 1 or more lines of the format either
485 * residue id #0:43.A type GLY
487 * residue id /A:89 name THR index 88
488 * We are only interested in the atomspec (third token of the reply)
490 for (String inputLine : chimeraReply)
492 String[] inputLineParts = inputLine.split("\\s+");
493 if (inputLineParts.length >= 5)
495 selectedResidues.add(inputLineParts[2]);
501 * Parse model number, residue and chain for each selected position,
502 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
504 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
508 * Broadcast the selection (which may be empty, if the user just cleared all
511 getSsm().mouseOverStructure(atomSpecs);
515 new Thread(action).start();
519 * Converts a list of Chimera(X) atomspecs to a list of AtomSpec representing
520 * the corresponding residues (if any) in Jalview
522 * @param structureSelection
525 protected List<AtomSpec> convertStructureResiduesToAlignment(
526 List<String> structureSelection)
528 List<AtomSpec> atomSpecs = new ArrayList<>();
529 for (String atomSpec : structureSelection)
533 AtomSpec spec = parseAtomSpec(atomSpec);
534 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
535 spec.setPdbFile(pdbfilename);
537 } catch (IllegalArgumentException e)
539 Console.error("Failed to parse atomspec: " + atomSpec);
549 protected String getPdbFileForModel(int modelId)
552 * Work out the pdbfilename from the model number
554 String pdbfilename = modelFileNames[0];
555 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
557 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
559 if (cm.getModelNumber() == modelId)
561 pdbfilename = pdbfile;
569 private void log(String message)
571 System.err.println("## Chimera log: " + message);
575 * Constructs and send commands to Chimera to set attributes on residues for
576 * features visible in Jalview.
578 * The syntax is: setattr r <attName> <attValue> <atomSpec>
580 * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
585 public int sendFeaturesToViewer(AlignmentViewPanel avp)
587 // TODO refactor as required to pull up to an interface
589 Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
591 List<StructureCommandI> commands = getCommandGenerator()
592 .setAttributes(featureValues);
593 if (commands.size() > 10)
595 sendCommandsByFile(commands);
599 executeCommands(commands, false, null);
601 return commands.size();
605 * Write commands to a temporary file, and send a command to Chimera to open
606 * the file as a commands script. For use when sending a large number of
607 * separate commands would overload the REST interface mechanism.
611 protected void sendCommandsByFile(List<StructureCommandI> commands)
615 File tmp = File.createTempFile("chim", getCommandFileExtension());
617 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
618 for (StructureCommandI command : commands)
620 out.println(command.getCommand());
624 String path = tmp.getAbsolutePath();
625 StructureCommandI command = getCommandGenerator()
626 .openCommandFile(path);
627 executeCommand(false, null, command);
628 } catch (IOException e)
630 System.err.println("Sending commands to Chimera via file failed with "
636 * Returns the file extension required for a file of commands to be read by
637 * the structure viewer
641 protected String getCommandFileExtension()
647 * Create features in Jalview for the given attribute name and structure
651 * The residue list should be 0, 1 or more reply lines of the format:
652 * residue id #0:5.A isHelix -155.000836316 index 5
654 * residue id #0:6.A isHelix None
659 * @return the number of features added
661 protected int createFeaturesForAttributes(String attName,
662 List<String> residues)
664 int featuresAdded = 0;
665 String featureGroup = getViewerFeatureGroup();
667 for (String residue : residues)
669 AtomSpec spec = null;
670 String[] tokens = residue.split(" ");
671 if (tokens.length < 5)
675 String atomSpec = tokens[2];
676 String attValue = tokens[4];
679 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
681 if ("None".equalsIgnoreCase(attValue)
682 || "False".equalsIgnoreCase(attValue))
689 spec = parseAtomSpec(atomSpec);
690 } catch (IllegalArgumentException e)
692 Console.error("Problem parsing atomspec " + atomSpec);
696 String chainId = spec.getChain();
697 String description = attValue;
698 float score = Float.NaN;
701 score = Float.valueOf(attValue);
702 description = chainId;
703 } catch (NumberFormatException e)
705 // was not a float value
708 String pdbFile = getPdbFileForModel(spec.getModelNumber());
709 spec.setPdbFile(pdbFile);
711 List<AtomSpec> atoms = Collections.singletonList(spec);
714 * locate the mapped position in the alignment (if any)
716 SearchResultsI sr = getSsm()
717 .findAlignmentPositionsForStructurePositions(atoms);
720 * expect one matched alignment position, or none
721 * (if the structure position is not mapped)
723 for (SearchResultMatchI m : sr.getResults())
725 SequenceI seq = m.getSequence();
726 int start = m.getStart();
727 int end = m.getEnd();
728 SequenceFeature sf = new SequenceFeature(attName, description,
729 start, end, score, featureGroup);
730 // todo: should SequenceFeature have an explicit property for chain?
731 // note: repeating the action shouldn't duplicate features
732 if (seq.addSequenceFeature(sf))
738 return featuresAdded;
742 * Answers the feature group name to apply to features created in Jalview from
747 protected String getViewerFeatureGroup()
749 // todo pull up to interface
750 return CHIMERA_FEATURE_GROUP;
754 public String getModelIdForFile(String pdbFile)
756 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
757 if (foundModels != null && !foundModels.isEmpty())
759 return String.valueOf(foundModels.get(0).getModelNumber());
765 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
766 * any which were added from Jalview
770 public List<String> getChimeraAttributes()
772 List<String> attributes = new ArrayList<>();
773 StructureCommandI command = getCommandGenerator()
774 .listResidueAttributes();
775 final List<String> reply = executeCommand(command, true);
778 for (String inputLine : reply)
780 String[] lineParts = inputLine.split("\\s");
781 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
783 String attName = lineParts[1];
785 * exclude attributes added from Jalview
787 if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
789 attributes.add(attName);
798 * Returns the file extension to use for a saved viewer session file (.py)
803 public String getSessionFileExtension()
805 return CHIMERA_SESSION_EXTENSION;
809 public String getHelpURL()
811 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";