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.Cache;
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 atomspec
83 protected AtomSpec parseAtomSpec(String atomSpec)
85 return AtomSpec.fromChimeraAtomspec(atomSpec);
89 * Open a PDB structure file in Chimera and set up mappings from Jalview.
91 * We check if the PDB model id is already loaded in Chimera, if so don't reopen
92 * it. This is the case if Chimera has opened a saved session file.
97 public boolean openFile(PDBEntry pe)
99 String file = pe.getFile();
102 List<ChimeraModel> modelsToMap = new ArrayList<>();
103 List<ChimeraModel> oldList = chimeraManager.getModelList();
104 boolean alreadyOpen = false;
107 * If Chimera already has this model, don't reopen it, but do remap it.
109 for (ChimeraModel open : oldList)
111 if (open.getModelName().equals(pe.getId()))
114 modelsToMap.add(open);
119 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
120 * the model name(s) added by Chimera.
124 chimeraManager.openModel(file, pe.getId(), ModelType.PDB_MODEL);
125 addChimeraModel(pe, modelsToMap);
128 chimeraMaps.put(file, modelsToMap);
130 if (getSsm() != null)
132 getSsm().addStructureViewerListener(this);
135 } catch (Exception q)
137 log("Exception when trying to open model " + file + "\n"
145 * Adds the ChimeraModel corresponding to the given PDBEntry, based on model
146 * name matching PDB id
151 protected void addChimeraModel(PDBEntry pe,
152 List<ChimeraModel> modelsToMap)
155 * Chimera: query for actual models and find the one with
156 * matching model name - already set in viewer.openModel()
158 List<ChimeraModel> newList = chimeraManager.getModelList();
159 // JAL-1728 newList.removeAll(oldList) does not work
160 for (ChimeraModel cm : newList)
162 if (cm.getModelName().equals(pe.getId()))
177 public JalviewChimeraBinding(StructureSelectionManager ssm,
178 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
179 DataSourceType protocol)
181 super(ssm, pdbentry, sequenceIs, protocol);
182 boolean chimeraX = ViewerType.CHIMERAX.equals(getViewerType());
183 chimeraManager = chimeraX ? new ChimeraXManager(new StructureManager(true)) : new ChimeraManager(new StructureManager(true));
184 setStructureCommands(chimeraX ? new ChimeraXCommands() : new ChimeraCommands());
188 protected ViewerType getViewerType()
190 return ViewerType.CHIMERA;
194 * Start a dedicated HttpServer to listen for Chimera notifications, and tell it
197 public void startChimeraListener()
201 chimeraListener = new ChimeraListener(this);
202 startListening(chimeraListener.getUri());
203 } catch (BindException e)
206 "Failed to start Chimera listener: " + e.getMessage());
211 * Close down the Jalview viewer and listener, and (optionally) the associated
215 public void closeViewer(boolean closeChimera)
217 super.closeViewer(closeChimera);
218 if (this.chimeraListener != null)
220 chimeraListener.shutdown();
221 chimeraListener = null;
225 * the following call is added to avoid a stack trace error in Chimera
226 * after "stop really" is sent; Chimera > 1.14 will not need it; see also
227 * http://plato.cgl.ucsf.edu/trac/chimera/ticket/17597
229 if (closeChimera && (getViewerType() == ViewerType.CHIMERA))
231 chimeraManager.getChimeraProcess().destroy();
234 chimeraManager.clearOnChimeraExit();
235 chimeraManager = null;
239 * Helper method to construct model spec in Chimera format:
241 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
242 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
244 * Note for now we only ever choose the first of multiple models. This
245 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
246 * future if there is a need to select specific sub-models.
251 protected String getModelSpec(int pdbfnum)
253 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
255 return "#" + pdbfnum; // temp hack for ChimeraX
259 * For now, the test for having sub-models is whether multiple Chimera
260 * models are mapped for the PDB file; the models are returned as a response
261 * to the Chimera command 'list models type molecule', see
262 * ChimeraManager.getModelList().
264 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
265 boolean hasSubModels = maps != null && maps.size() > 1;
266 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
270 * Launch Chimera, unless an instance linked to this object is already
271 * running. Returns true if Chimera is successfully launched, or already
272 * running, else false.
276 public boolean launchChimera()
278 if (chimeraManager.isChimeraLaunched())
283 boolean launched = chimeraManager.launchChimera(getChimeraPaths());
286 startExternalViewerMonitor(chimeraManager.getChimeraProcess());
290 log("Failed to launch Chimera!");
296 * Returns a list of candidate paths to the Chimera program executable
300 protected List<String> getChimeraPaths()
302 return StructureManager.getChimeraPaths(false);
306 * Answers true if the Chimera process is still running, false if ended or not
312 public boolean isViewerRunning()
314 return chimeraManager.isChimeraLaunched();
318 * Send a command to Chimera, and optionally log and return any responses.
324 public List<String> executeCommand(final StructureCommandI command,
327 if (chimeraManager == null || command == null)
329 // ? thread running after viewer shut down
332 List<String> reply = null;
333 // trim command or it may never find a match in the replyLog!!
334 String cmd = command.getCommand().trim();
335 List<String> lastReply = chimeraManager
336 .sendChimeraCommand(cmd, getResponse);
340 if (Cache.log.isDebugEnabled()) {
342 "Response from command ('" + cmd + "') was:\n" + lastReply);
350 public synchronized String[] getStructureFiles()
352 if (chimeraManager == null)
354 return new String[0];
357 return chimeraMaps.keySet()
358 .toArray(modelFileNames = new String[chimeraMaps.size()]);
362 * Construct and send a command to highlight zero, one or more atoms. We do this
363 * by sending an "rlabel" command to show the residue label at that position.
366 public void highlightAtoms(List<AtomSpec> atoms)
368 if (atoms == null || atoms.size() == 0)
373 boolean forChimeraX = chimeraManager.isChimeraX();
374 StringBuilder cmd = new StringBuilder(128);
375 boolean first = true;
376 boolean found = false;
378 for (AtomSpec atom : atoms)
380 int pdbResNum = atom.getPdbResNum();
381 String chain = atom.getChain();
382 String pdbfile = atom.getPdbFile();
383 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
384 if (cms != null && !cms.isEmpty())
388 cmd.append(forChimeraX ? "label #" : "rlabel #");
397 cmd.append(cms.get(0).getModelNumber())
398 .append("/").append(chain).append(":").append(pdbResNum);
402 cmd.append(cms.get(0).getModelNumber())
403 .append(":").append(pdbResNum);
404 if (!chain.equals(" ") && !forChimeraX)
406 cmd.append(".").append(chain);
412 String command = cmd.toString();
415 * avoid repeated commands for the same residue
417 if (command.equals(lastHighlightCommand))
423 * unshow the label for the previous residue
425 if (lastHighlightCommand != null)
427 executeCommand(false, null, new StructureCommand("~" + lastHighlightCommand));
431 executeCommand(false, null, new StructureCommand(command));
433 this.lastHighlightCommand = command;
437 * Query Chimera for its current selection, and highlight it on the alignment
439 public void highlightChimeraSelection()
442 * Ask Chimera for its current selection
444 StructureCommandI command = getCommandGenerator().getSelectedResidues();
446 Runnable action = new Runnable()
451 List<String> chimeraReply = executeCommand(command, true);
453 List<String> selectedResidues = new ArrayList<>();
454 if (chimeraReply != null)
457 * expect 0, 1 or more lines of the format either
459 * residue id #0:43.A type GLY
461 * residue id /A:89 name THR index 88
462 * We are only interested in the atomspec (third token of the reply)
464 for (String inputLine : chimeraReply)
466 String[] inputLineParts = inputLine.split("\\s+");
467 if (inputLineParts.length >= 5)
469 selectedResidues.add(inputLineParts[2]);
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 new Thread(action).start();
493 * Converts a list of Chimera(X) atomspecs to a list of AtomSpec representing the
494 * corresponding residues (if any) in Jalview
496 * @param structureSelection
499 protected List<AtomSpec> convertStructureResiduesToAlignment(
500 List<String> structureSelection)
502 List<AtomSpec> atomSpecs = new ArrayList<>();
503 for (String atomSpec : structureSelection)
507 AtomSpec spec = parseAtomSpec(atomSpec);
508 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
509 spec.setPdbFile(pdbfilename);
511 } catch (IllegalArgumentException e)
513 Cache.log.error("Failed to parse atomspec: " + atomSpec);
523 protected String getPdbFileForModel(int modelId)
526 * Work out the pdbfilename from the model number
528 String pdbfilename = modelFileNames[0];
529 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
531 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
533 if (cm.getModelNumber() == modelId)
535 pdbfilename = pdbfile;
543 private void log(String message)
545 System.err.println("## Chimera log: " + message);
549 * Constructs and send commands to Chimera to set attributes on residues for
550 * features visible in Jalview.
552 * The syntax is: setattr r <attName> <attValue> <atomSpec>
554 * For example: setattr r jv_chain "Ferredoxin-1, Chloroplastic" #0:94.A
559 public int sendFeaturesToViewer(AlignmentViewPanel avp)
561 // TODO refactor as required to pull up to an interface
563 Map<String, Map<Object, AtomSpecModel>> featureValues = buildFeaturesMap(
565 List<StructureCommandI> commands = getCommandGenerator()
566 .setAttributes(featureValues);
567 if (commands.size() > 10)
569 sendCommandsByFile(commands);
573 executeCommands(commands, false, null);
575 return commands.size();
579 * Write commands to a temporary file, and send a command to Chimera to open the
580 * file as a commands script. For use when sending a large number of separate
581 * commands would overload the REST interface mechanism.
585 protected void sendCommandsByFile(List<StructureCommandI> commands)
589 File tmp = File.createTempFile("chim", getCommandFileExtension());
591 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
592 for (StructureCommandI command : commands)
594 out.println(command.getCommand());
598 String path = tmp.getAbsolutePath();
599 StructureCommandI command = getCommandGenerator()
600 .openCommandFile(path);
601 executeCommand(false, null, command);
602 } catch (IOException e)
604 System.err.println("Sending commands to Chimera via file failed with "
610 * Returns the file extension required for a file of commands to be read by
611 * the structure viewer
614 protected String getCommandFileExtension()
620 * Create features in Jalview for the given attribute name and structure
624 * The residue list should be 0, 1 or more reply lines of the format:
625 * residue id #0:5.A isHelix -155.000836316 index 5
627 * residue id #0:6.A isHelix None
632 * @return the number of features added
634 protected int createFeaturesForAttributes(String attName,
635 List<String> residues)
637 int featuresAdded = 0;
638 String featureGroup = getViewerFeatureGroup();
640 for (String residue : residues)
642 AtomSpec spec = null;
643 String[] tokens = residue.split(" ");
644 if (tokens.length < 5)
648 String atomSpec = tokens[2];
649 String attValue = tokens[4];
652 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
654 if ("None".equalsIgnoreCase(attValue)
655 || "False".equalsIgnoreCase(attValue))
662 spec = parseAtomSpec(atomSpec);
663 } catch (IllegalArgumentException e)
665 Cache.log.error("Problem parsing atomspec " + atomSpec);
669 String chainId = spec.getChain();
670 String description = attValue;
671 float score = Float.NaN;
674 score = Float.valueOf(attValue);
675 description = chainId;
676 } catch (NumberFormatException e)
678 // was not a float value
681 String pdbFile = getPdbFileForModel(spec.getModelNumber());
682 spec.setPdbFile(pdbFile);
684 List<AtomSpec> atoms = Collections.singletonList(spec);
687 * locate the mapped position in the alignment (if any)
689 SearchResultsI sr = getSsm()
690 .findAlignmentPositionsForStructurePositions(atoms);
693 * expect one matched alignment position, or none
694 * (if the structure position is not mapped)
696 for (SearchResultMatchI m : sr.getResults())
698 SequenceI seq = m.getSequence();
699 int start = m.getStart();
700 int end = m.getEnd();
701 SequenceFeature sf = new SequenceFeature(attName, description,
702 start, end, score, featureGroup);
703 // todo: should SequenceFeature have an explicit property for chain?
704 // note: repeating the action shouldn't duplicate features
705 if (seq.addSequenceFeature(sf))
711 return featuresAdded;
715 * Answers the feature group name to apply to features created in Jalview from
720 protected String getViewerFeatureGroup()
722 // todo pull up to interface
723 return CHIMERA_FEATURE_GROUP;
727 public String getModelIdForFile(String pdbFile)
729 List<ChimeraModel> foundModels = chimeraMaps.get(pdbFile);
730 if (foundModels != null && !foundModels.isEmpty())
732 return String.valueOf(foundModels.get(0).getModelNumber());
738 * Answers a (possibly empty) list of attribute names in Chimera[X], excluding
739 * any which were added from Jalview
743 public List<String> getChimeraAttributes()
745 List<String> attributes = new ArrayList<>();
746 StructureCommandI command = getCommandGenerator().listResidueAttributes();
747 final List<String> reply = executeCommand(command, true);
750 for (String inputLine : reply)
752 String[] lineParts = inputLine.split("\\s");
753 if (lineParts.length == 2 && lineParts[0].equals("resattr"))
755 String attName = lineParts[1];
757 * exclude attributes added from Jalview
759 if (!attName.startsWith(ChimeraCommands.NAMESPACE_PREFIX))
761 attributes.add(attName);
770 * Returns the file extension to use for a saved viewer session file (.py)
775 public String getSessionFileExtension()
777 return CHIMERA_SESSION_EXTENSION;
781 public String getHelpURL()
783 return "https://www.cgl.ucsf.edu/chimera/docs/UsersGuide";