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.bin.Cache;
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.AtomSpecModel;
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";
64 * Object through which we talk to Chimera
66 private ChimeraManager chimeraManager;
69 * Object which listens to Chimera notifications
71 private AbstractRequestHandler chimeraListener;
74 * Map of ChimeraModel objects keyed by PDB full local file name
76 protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
78 String lastHighlightCommand;
81 * Returns a model of the structure positions described by the Chimera format atomspec
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 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 boolean chimeraX = ViewerType.CHIMERAX.equals(getViewerType());
185 chimeraManager = chimeraX ? new ChimeraXManager(new StructureManager(true)) : new ChimeraManager(new StructureManager(true));
186 setStructureCommands(chimeraX ? new ChimeraXCommands() : new ChimeraCommands());
190 protected ViewerType getViewerType()
192 return ViewerType.CHIMERA;
196 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
199 public void startChimeraListener()
203 chimeraListener = new ChimeraListener(this);
204 startListening(chimeraListener.getUri());
205 } catch (BindException e)
208 "Failed to start Chimera listener: " + e.getMessage());
213 * Close down the Jalview viewer and listener, and (optionally) the associated
217 public void closeViewer(boolean closeChimera)
219 super.closeViewer(closeChimera);
220 if (this.chimeraListener != null)
222 chimeraListener.shutdown();
223 chimeraListener = null;
227 * the following call is added to avoid a stack trace error in Chimera
228 * after "stop really" is sent; Chimera > 1.14 will not need it; see also
229 * http://plato.cgl.ucsf.edu/trac/chimera/ticket/17597
231 if (closeChimera && (getViewerType() == ViewerType.CHIMERA))
233 chimeraManager.getChimeraProcess().destroy();
236 chimeraManager.clearOnChimeraExit();
237 chimeraManager = null;
241 * Helper method to construct model spec in Chimera format:
243 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
244 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
246 * Note for now we only ever choose the first of multiple models. This
247 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
248 * future if there is a need to select specific sub-models.
253 protected String getModelSpec(int pdbfnum)
255 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
257 return "#" + pdbfnum; // temp hack for ChimeraX
261 * For now, the test for having sub-models is whether multiple Chimera
262 * models are mapped for the PDB file; the models are returned as a response
263 * to the Chimera command 'list models type molecule', see
264 * ChimeraManager.getModelList().
266 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
267 boolean hasSubModels = maps != null && maps.size() > 1;
268 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
272 * Launch Chimera, unless an instance linked to this object is already
273 * running. Returns true if Chimera is successfully launched, or already
274 * running, else false.
278 public boolean launchChimera()
280 if (chimeraManager.isChimeraLaunched())
285 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
288 startExternalViewerMonitor(chimeraManager.getChimeraProcess());
292 log("Failed to launch Chimera!");
298 * Returns a list of candidate paths to the Chimera program executable
302 protected List<String> getChimeraPaths()
304 return StructureManager.getChimeraPaths(false);
308 * Answers true if the Chimera process is still running, false if ended or not
314 public boolean isViewerRunning()
316 return chimeraManager.isChimeraLaunched();
320 * Send a command to Chimera, and optionally log and return any responses.
326 public List<String> executeCommand(final StructureCommandI command,
329 if (chimeraManager == null || command == null)
331 // ? thread running after viewer shut down
334 List<String> reply = null;
335 // trim command or it may never find a match in the replyLog!!
336 String cmd = command.getCommand().trim();
337 List<String> lastReply = chimeraManager
338 .sendChimeraCommand(cmd, getResponse);
342 if (Cache.log.isDebugEnabled()) {
344 "Response from command ('" + cmd + "') was:\n" + lastReply);
352 public synchronized String[] getStructureFiles()
354 if (chimeraManager == null)
356 return new String[0];
359 return chimeraMaps.keySet()
360 .toArray(modelFileNames = new String[chimeraMaps.size()]);
364 * Construct and send a command to highlight zero, one or more atoms. We do this
365 * by sending an "rlabel" command to show the residue label at that position.
368 public void highlightAtoms(List<AtomSpec> atoms)
370 if (atoms == null || atoms.size() == 0)
375 boolean forChimeraX = chimeraManager.isChimeraX();
376 StringBuilder cmd = new StringBuilder(128);
377 boolean first = true;
378 boolean found = false;
380 for (AtomSpec atom : atoms)
382 int pdbResNum = atom.getPdbResNum();
383 String chain = atom.getChain();
384 String pdbfile = atom.getPdbFile();
385 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
386 if (cms != null && !cms.isEmpty())
390 cmd.append(forChimeraX ? "label #" : "rlabel #");
399 cmd.append(cms.get(0).getModelNumber())
400 .append("/").append(chain).append(":").append(pdbResNum);
404 cmd.append(cms.get(0).getModelNumber())
405 .append(":").append(pdbResNum);
406 if (!chain.equals(" ") && !forChimeraX)
408 cmd.append(".").append(chain);
414 String command = cmd.toString();
417 * avoid repeated commands for the same residue
419 if (command.equals(lastHighlightCommand))
425 * unshow the label for the previous residue
427 if (lastHighlightCommand != null)
429 chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
433 chimeraManager.sendChimeraCommand(command, false);
435 this.lastHighlightCommand = command;
439 * Query Chimera for its current selection, and highlight it on the alignment
441 public void highlightChimeraSelection()
444 * Ask Chimera for its current selection
446 StructureCommandI command = getCommandGenerator().getSelectedResidues();
448 Runnable action = new Runnable()
453 List<String> chimeraReply = executeCommand(command, true);
455 List<String> selectedResidues = new ArrayList<>();
456 if (chimeraReply != null)
459 * expect 0, 1 or more lines of the format either
461 * residue id #0:43.A type GLY
463 * residue id /A:89 name THR index 88
464 * We are only interested in the atomspec (third token of the reply)
466 for (String inputLine : chimeraReply)
468 String[] inputLineParts = inputLine.split("\\s+");
469 if (inputLineParts.length >= 5)
471 selectedResidues.add(inputLineParts[2]);
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 new Thread(action).start();
495 * Converts a list of Chimera(X) atomspecs to a list of AtomSpec representing the
496 * corresponding residues (if any) in Jalview
498 * @param structureSelection
501 protected List<AtomSpec> convertStructureResiduesToAlignment(
502 List<String> structureSelection)
504 List<AtomSpec> atomSpecs = new ArrayList<>();
505 for (String atomSpec : structureSelection)
509 AtomSpec spec = parseAtomSpec(atomSpec);
510 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
511 spec.setPdbFile(pdbfilename);
513 } catch (IllegalArgumentException e)
515 Cache.log.error("Failed to parse atomspec: " + atomSpec);
525 protected String getPdbFileForModel(int modelId)
528 * Work out the pdbfilename from the model number
530 String pdbfilename = modelFileNames[0];
531 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
533 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
535 if (cm.getModelNumber() == modelId)
537 pdbfilename = pdbfile;
545 private void log(String message)
547 System.err.println("## Chimera log: " + message);
551 * Constructs and send commands to Chimera to set attributes on residues for
552 * features visible in Jalview.
554 * The syntax is: setattr r <attName> <attValue> <atomSpec>
556 * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
561 public int sendFeaturesToViewer(AlignmentViewPanel avp)
563 // TODO refactor as required to pull up to an interface
565 Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
567 List<StructureCommandI> commands = getCommandGenerator()
568 .setAttributes(featureValues);
569 if (commands.size() > 10)
571 sendCommandsByFile(commands);
575 for (StructureCommandI command : commands)
577 sendAsynchronousCommand(command, null);
580 return commands.size();
584 * Write commands to a temporary file, and send a command to Chimera to open the
585 * file as a commands script. For use when sending a large number of separate
586 * commands would overload the REST interface mechanism.
590 protected void sendCommandsByFile(List<StructureCommandI> commands)
594 File tmp = File.createTempFile("chim", getCommandFileExtension());
596 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
597 for (StructureCommandI command : commands)
599 out.println(command.getCommand());
603 String path = tmp.getAbsolutePath();
604 StructureCommandI command = getCommandGenerator()
605 .openCommandFile(path);
606 sendAsynchronousCommand(command, null);
607 } catch (IOException e)
609 System.err.println("Sending commands to Chimera via file failed with "
615 * Returns the file extension required for a file of commands to be read by
616 * the structure viewer
619 protected String getCommandFileExtension()
625 * Create features in Jalview for the given attribute name and structure
629 * The residue list should be 0, 1 or more reply lines of the format:
630 * residue id #0:5.A isHelix -155.000836316 index 5
632 * residue id #0:6.A isHelix None
637 * @return the number of features added
639 protected int createFeaturesForAttributes(String attName,
640 List<String> residues)
642 int featuresAdded = 0;
643 String featureGroup = getViewerFeatureGroup();
645 for (String residue : residues)
647 AtomSpec spec = null;
648 String[] tokens = residue.split(" ");
649 if (tokens.length < 5)
653 String atomSpec = tokens[2];
654 String attValue = tokens[4];
657 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
659 if ("None".equalsIgnoreCase(attValue)
660 || "False".equalsIgnoreCase(attValue))
667 spec = parseAtomSpec(atomSpec);
668 } catch (IllegalArgumentException e)
670 Cache.log.error("Problem parsing atomspec " + atomSpec);
674 String chainId = spec.getChain();
675 String description = attValue;
676 float score = Float.NaN;
679 score = Float.valueOf(attValue);
680 description = chainId;
681 } catch (NumberFormatException e)
683 // was not a float value
686 String pdbFile = getPdbFileForModel(spec.getModelNumber());
687 spec.setPdbFile(pdbFile);
689 List<AtomSpec> atoms = Collections.singletonList(spec);
692 * locate the mapped position in the alignment (if any)
694 SearchResultsI sr = getSsm()
695 .findAlignmentPositionsForStructurePositions(atoms);
698 * expect one matched alignment position, or none
699 * (if the structure position is not mapped)
701 for (SearchResultMatchI m : sr.getResults())
703 SequenceI seq = m.getSequence();
704 int start = m.getStart();
705 int end = m.getEnd();
706 SequenceFeature sf = new SequenceFeature(attName, description,
707 start, end, score, featureGroup);
708 // todo: should SequenceFeature have an explicit property for chain?
709 // note: repeating the action shouldn't duplicate features
710 if (seq.addSequenceFeature(sf))
716 return featuresAdded;
720 * Answers the feature group name to apply to features created in Jalview from
725 protected String getViewerFeatureGroup()
727 // todo pull up to interface
728 return CHIMERA_FEATURE_GROUP;
732 public String getModelIdForFile(String pdbFile)
734 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
735 if (foundModels != null && !foundModels.isEmpty())
737 return String.valueOf(foundModels.get(0).getModelNumber());
743 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
744 * any which were added from Jalview
748 public List<String> getChimeraAttributes()
750 List<String> attributes = new ArrayList<>();
751 StructureCommandI command = getCommandGenerator().listResidueAttributes();
752 final List<String> reply = executeCommand(command, true);
755 for (String inputLine : reply)
757 String[] lineParts = inputLine.split("\\s");
758 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
760 String attName = lineParts[1];
762 * exclude attributes added from Jalview
764 if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
766 attributes.add(attName);
775 * Returns the file extension to use for a saved viewer session file (.py)
780 public String getSessionFileExtension()
782 return CHIMERA_SESSION_EXTENSION;
786 public String getHelpURL()
788 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";