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.AtomSpecModel;
53 import jalview.structure.StructureCommand;
54 import jalview.structure.StructureCommandI;
55 import jalview.structure.StructureSelectionManager;
56 import jalview.structures.models.AAStructureBindingModel;
58 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
60 public static final String CHIMERA_SESSION_EXTENSION = ".py";
62 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
65 * Object through which we talk to Chimera
67 private ChimeraManager chimeraManager;
70 * Object which listens to Chimera notifications
72 private AbstractRequestHandler chimeraListener;
75 * Map of ChimeraModel objects keyed by PDB full local file name
77 protected Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
79 String lastHighlightCommand;
81 private Thread chimeraMonitor;
84 * Open a PDB structure file in Chimera and set up mappings from Jalview.
86 * We check if the PDB model id is already loaded in Chimera, if so don't reopen
87 * it. This is the case if Chimera has opened a saved session file.
92 public boolean openFile(PDBEntry pe)
94 String file = pe.getFile();
97 List<ChimeraModel> modelsToMap = new ArrayList<>();
98 List<ChimeraModel> oldList = chimeraManager.getModelList();
99 boolean alreadyOpen = false;
102 * If Chimera already has this model, don't reopen it, but do remap it.
104 for (ChimeraModel open : oldList)
106 if (open.getModelName().equals(pe.getId()))
109 modelsToMap.add(open);
114 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
115 * the model name(s) added by Chimera.
119 chimeraManager.openModel(file, pe.getId(), ModelType.PDB_MODEL);
120 addChimeraModel(pe, modelsToMap);
123 chimeraMaps.put(file, modelsToMap);
125 if (getSsm() != null)
127 getSsm().addStructureViewerListener(this);
130 } catch (Exception q)
132 log("Exception when trying to open model " + file + "\n"
140 * Adds the ChimeraModel corresponding to the given PDBEntry, based on model
141 * name matching PDB id
146 protected void addChimeraModel(PDBEntry pe,
147 List<ChimeraModel> modelsToMap)
150 * Chimera: query for actual models and find the one with
151 * matching model name - already set in viewer.openModel()
153 List<ChimeraModel> newList = chimeraManager.getModelList();
154 // JAL-1728 newList.removeAll(oldList) does not work
155 for (ChimeraModel cm : newList)
157 if (cm.getModelName().equals(pe.getId()))
172 public JalviewChimeraBinding(StructureSelectionManager ssm,
173 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
174 DataSourceType protocol)
176 super(ssm, pdbentry, sequenceIs, protocol);
177 chimeraManager = new ChimeraManager(new StructureManager(true));
178 chimeraManager.setChimeraX(ViewerType.CHIMERAX.equals(getViewerType()));
179 setStructureCommands(new ChimeraCommands());
183 protected ViewerType getViewerType()
185 return ViewerType.CHIMERA;
189 * Starts a thread that waits for the Chimera process to finish, so that we can
190 * then close the associated resources. This avoids leaving orphaned Chimera
191 * viewer panels in Jalview if the user closes Chimera.
193 protected void startChimeraProcessMonitor()
195 final Process p = chimeraManager.getChimeraProcess();
196 chimeraMonitor = new Thread(new Runnable()
205 JalviewStructureDisplayI display = getViewer();
208 display.closeViewer(false);
210 } catch (InterruptedException e)
212 // exit thread if Chimera Viewer is closed in Jalview
216 chimeraMonitor.start();
220 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
223 public void startChimeraListener()
227 chimeraListener = new ChimeraListener(this);
228 chimeraManager.startListening(chimeraListener.getUri());
229 } catch (BindException e)
232 "Failed to start Chimera listener: " + e.getMessage());
237 * Close down the Jalview viewer and listener, and (optionally) the associated
241 public void closeViewer(boolean closeChimera)
243 super.closeViewer(closeChimera);
246 chimeraManager.exitChimera();
248 if (this.chimeraListener != null)
250 chimeraListener.shutdown();
251 chimeraListener = null;
253 chimeraManager = null;
255 if (chimeraMonitor != null)
257 chimeraMonitor.interrupt();
262 * Helper method to construct model spec in Chimera format:
264 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
265 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
267 * Note for now we only ever choose the first of multiple models. This
268 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
269 * future if there is a need to select specific sub-models.
274 protected String getModelSpec(int pdbfnum)
276 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
278 return "#" + pdbfnum; // temp hack for ChimeraX
282 * For now, the test for having sub-models is whether multiple Chimera
283 * models are mapped for the PDB file; the models are returned as a response
284 * to the Chimera command 'list models type molecule', see
285 * ChimeraManager.getModelList().
287 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
288 boolean hasSubModels = maps != null && maps.size() > 1;
289 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
293 * Launch Chimera, unless an instance linked to this object is already
294 * running. Returns true if Chimera is successfully launched, or already
295 * running, else false.
299 public boolean launchChimera()
301 if (chimeraManager.isChimeraLaunched())
306 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
309 startChimeraProcessMonitor();
313 log("Failed to launch Chimera!");
319 * Returns a list of candidate paths to the Chimera program executable
323 protected List<String> getChimeraPaths()
325 return StructureManager.getChimeraPaths(false);
329 * Answers true if the Chimera process is still running, false if ended or not
335 public boolean isViewerRunning()
337 return chimeraManager.isChimeraLaunched();
341 * Send a command to Chimera, and optionally log and return any responses.
347 public List<String> executeCommand(final StructureCommandI command,
350 if (chimeraManager == null || command == null)
352 // ? thread running after viewer shut down
355 List<String> reply = null;
356 // trim command or it may never find a match in the replyLog!!
357 String cmd = command.getCommand().trim();
358 List<String> lastReply = chimeraManager
359 .sendChimeraCommand(cmd, getResponse);
364 "Response from command ('" + cmd + "') was:\n" + lastReply);
371 public synchronized String[] getStructureFiles()
373 if (chimeraManager == null)
375 return new String[0];
378 return chimeraMaps.keySet()
379 .toArray(modelFileNames = new String[chimeraMaps.size()]);
383 * Construct and send a command to highlight zero, one or more atoms. We do this
384 * by sending an "rlabel" command to show the residue label at that position.
387 public void highlightAtoms(List<AtomSpec> atoms)
389 if (atoms == null || atoms.size() == 0)
394 boolean forChimeraX = chimeraManager.isChimeraX();
395 StringBuilder cmd = new StringBuilder(128);
396 boolean first = true;
397 boolean found = false;
399 for (AtomSpec atom : atoms)
401 int pdbResNum = atom.getPdbResNum();
402 String chain = atom.getChain();
403 String pdbfile = atom.getPdbFile();
404 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
405 if (cms != null && !cms.isEmpty())
409 cmd.append(forChimeraX ? "label #" : "rlabel #");
418 cmd.append(cms.get(0).getModelNumber())
419 .append("/").append(chain).append(":").append(pdbResNum);
423 cmd.append(cms.get(0).getModelNumber())
424 .append(":").append(pdbResNum);
425 if (!chain.equals(" ") && !forChimeraX)
427 cmd.append(".").append(chain);
433 String command = cmd.toString();
436 * avoid repeated commands for the same residue
438 if (command.equals(lastHighlightCommand))
444 * unshow the label for the previous residue
446 if (lastHighlightCommand != null)
448 chimeraManager.sendChimeraCommand("~" + lastHighlightCommand, false);
452 chimeraManager.sendChimeraCommand(command, false);
454 this.lastHighlightCommand = command;
458 * Query Chimera for its current selection, and highlight it on the alignment
460 public void highlightChimeraSelection()
463 * Ask Chimera for its current selection
465 List<String> selection = chimeraManager.getSelectedResidueSpecs();
468 * Parse model number, residue and chain for each selected position,
469 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
471 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
475 * Broadcast the selection (which may be empty, if the user just cleared all
478 getSsm().mouseOverStructure(atomSpecs);
482 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
483 * corresponding residues (if any) in Jalview
485 * @param structureSelection
488 protected List<AtomSpec> convertStructureResiduesToAlignment(
489 List<String> structureSelection)
491 boolean chimeraX = chimeraManager.isChimeraX();
492 List<AtomSpec> atomSpecs = new ArrayList<>();
493 for (String atomSpec : structureSelection)
497 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
498 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
499 spec.setPdbFile(pdbfilename);
501 } catch (IllegalArgumentException e)
503 System.err.println("Failed to parse atomspec: " + atomSpec);
513 protected String getPdbFileForModel(int modelId)
516 * Work out the pdbfilename from the model number
518 String pdbfilename = modelFileNames[0];
519 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
521 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
523 if (cm.getModelNumber() == modelId)
525 pdbfilename = pdbfile;
533 private void log(String message)
535 System.err.println("## Chimera log: " + message);
539 * Send a 'show' command for all atoms in the currently selected columns
541 * TODO: pull up to abstract structure viewer interface
545 public void highlightSelection(AlignmentViewPanel vp)
547 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
549 AlignmentI alignment = vp.getAlignment();
550 StructureSelectionManager sm = getSsm();
551 for (SequenceI seq : alignment.getSequences())
554 * convert selected columns into sequence positions
556 int[] positions = new int[cols.size()];
558 for (Integer col : cols)
560 positions[i++] = seq.findPosition(col);
562 sm.highlightStructure(this, seq, positions);
567 * Constructs and send commands to Chimera to set attributes on residues for
568 * features visible in Jalview.
570 * The syntax is: setattr r <attName> <attValue> <atomSpec>
572 * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
577 public int sendFeaturesToViewer(AlignmentViewPanel avp)
579 // TODO refactor as required to pull up to an interface
581 Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
583 List<StructureCommandI> commands = getCommandGenerator()
584 .setAttributes(featureValues);
585 if (commands.size() > 10)
587 sendCommandsByFile(commands);
591 for (StructureCommandI command : commands)
593 sendAsynchronousCommand(command, null);
596 return commands.size();
600 * Write commands to a temporary file, and send a command to Chimera to open the
601 * file as a commands script. For use when sending a large number of separate
602 * commands would overload the REST interface mechanism.
606 protected void sendCommandsByFile(List<StructureCommandI> commands)
610 File tmp = File.createTempFile("chim", getCommandFileExtension());
612 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
613 for (StructureCommandI command : commands)
615 out.println(command.getCommand());
619 String path = tmp.getAbsolutePath();
620 StructureCommandI command = getCommandGenerator()
621 .openCommandFile(path);
622 sendAsynchronousCommand(command, null);
623 } catch (IOException e)
625 System.err.println("Sending commands to Chimera via file failed with "
631 * Returns the file extension required for a file of commands to be read by
632 * the structure viewer
635 protected String getCommandFileExtension()
641 * Get Chimera residues which have the named attribute, find the mapped
642 * positions in the Jalview sequence(s), and set as sequence features
645 * @param alignmentPanel
647 public void copyStructureAttributesToFeatures(String attName,
648 AlignmentViewPanel alignmentPanel)
650 // todo pull up to AAStructureBindingModel (and interface?)
653 * ask Chimera to list residues with the attribute, reporting its value
655 // this alternative command
656 // list residues spec ':*/attName' attr attName
657 // doesn't report 'None' values (which is good), but
658 // fails for 'average.bfactor' (which is bad):
660 String cmd = "list residues attr '" + attName + "'";
661 List<String> residues = executeCommand(new StructureCommand(cmd), true);
663 boolean featureAdded = createFeaturesForAttributes(attName, residues);
666 alignmentPanel.getFeatureRenderer().featuresAdded();
671 * Create features in Jalview for the given attribute name and structure
675 * The residue list should be 0, 1 or more reply lines of the format:
676 * residue id #0:5.A isHelix -155.000836316 index 5
678 * residue id #0:6.A isHelix None
685 protected boolean createFeaturesForAttributes(String attName,
686 List<String> residues)
688 boolean featureAdded = false;
689 String featureGroup = getViewerFeatureGroup();
690 boolean chimeraX = chimeraManager.isChimeraX();
692 for (String residue : residues)
694 AtomSpec spec = null;
695 String[] tokens = residue.split(" ");
696 if (tokens.length < 5)
700 String atomSpec = tokens[2];
701 String attValue = tokens[4];
704 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
706 if ("None".equalsIgnoreCase(attValue)
707 || "False".equalsIgnoreCase(attValue))
714 spec = AtomSpec.fromChimeraAtomspec(atomSpec, chimeraX);
715 } catch (IllegalArgumentException e)
717 System.err.println("Problem parsing atomspec " + atomSpec);
721 String chainId = spec.getChain();
722 String description = attValue;
723 float score = Float.NaN;
726 score = Float.valueOf(attValue);
727 description = chainId;
728 } catch (NumberFormatException e)
730 // was not a float value
733 String pdbFile = getPdbFileForModel(spec.getModelNumber());
734 spec.setPdbFile(pdbFile);
736 List<AtomSpec> atoms = Collections.singletonList(spec);
739 * locate the mapped position in the alignment (if any)
741 SearchResultsI sr = getSsm()
742 .findAlignmentPositionsForStructurePositions(atoms);
745 * expect one matched alignment position, or none
746 * (if the structure position is not mapped)
748 for (SearchResultMatchI m : sr.getResults())
750 SequenceI seq = m.getSequence();
751 int start = m.getStart();
752 int end = m.getEnd();
753 SequenceFeature sf = new SequenceFeature(attName, description,
754 start, end, score, featureGroup);
755 // todo: should SequenceFeature have an explicit property for chain?
756 // note: repeating the action shouldn't duplicate features
757 featureAdded |= seq.addSequenceFeature(sf);
764 * Answers the feature group name to apply to features created in Jalview from
769 protected String getViewerFeatureGroup()
771 // todo pull up to interface
772 return CHIMERA_FEATURE_GROUP;
776 public String getModelIdForFile(String pdbFile)
778 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
779 if (foundModels != null && !foundModels.isEmpty())
781 return String.valueOf(foundModels.get(0).getModelNumber());
787 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
788 * any which were added from Jalview
792 public List<String> getChimeraAttributes()
794 List<String> atts = chimeraManager.getAttrList();
795 Iterator<String> it = atts.iterator();
798 if (it.next().startsWith(ChimeraCommands.NAMESPACE_PREFIX))
801 * attribute added from Jalview - exclude it
810 * Returns the file extension to use for a saved viewer session file (.py)
815 public String getSessionFileExtension()
817 return CHIMERA_SESSION_EXTENSION;
821 public String getHelpURL()
823 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";