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;
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.structures.JalviewStructureDisplayI;
27 import jalview.bin.Cache;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SearchResultMatchI;
32 import jalview.datamodel.SearchResultsI;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceI;
35 import jalview.httpserver.AbstractRequestHandler;
36 import jalview.io.DataSourceType;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.AtomSpec;
40 import jalview.structure.StructureMapping;
41 import jalview.structure.StructureMappingcommandSet;
42 import jalview.structure.StructureSelectionManager;
43 import jalview.structures.models.AAStructureBindingModel;
44 import jalview.util.MessageManager;
46 import java.awt.Color;
48 import java.io.FileOutputStream;
49 import java.io.IOException;
50 import java.io.PrintWriter;
51 import java.net.BindException;
52 import java.util.ArrayList;
53 import java.util.BitSet;
54 import java.util.Collections;
55 import java.util.Hashtable;
56 import java.util.Iterator;
57 import java.util.LinkedHashMap;
58 import java.util.List;
61 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
62 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
63 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
64 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
66 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
68 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
70 // Chimera clause to exclude alternate locations in atom selection
71 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
73 private static final String COLOURING_CHIMERA = MessageManager
74 .getString("status.colouring_chimera");
76 private static final boolean debug = false;
78 private static final String PHOSPHORUS = "P";
80 private static final String ALPHACARBON = "CA";
82 private List<String> chainNames = new ArrayList<>();
84 private Hashtable<String, String> chainFile = new Hashtable<>();
87 * Object through which we talk to Chimera
89 private ChimeraManager viewer;
92 * Object which listens to Chimera notifications
94 private AbstractRequestHandler chimeraListener;
97 * set if chimera state is being restored from some source - instructs binding
98 * not to apply default display style when structure set is updated for first
101 private boolean loadingFromArchive = false;
104 * flag to indicate if the Chimera viewer should ignore sequence colouring
105 * events from the structure manager because the GUI is still setting up
107 private boolean loadingFinished = true;
110 * Map of ChimeraModel objects keyed by PDB full local file name
112 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
114 String lastHighlightCommand;
117 * incremented every time a load notification is successfully handled -
118 * lightweight mechanism for other threads to detect when they can start
119 * referring to new structures.
121 private long loadNotifiesHandled = 0;
123 private Thread chimeraMonitor;
126 * Open a PDB structure file in Chimera and set up mappings from Jalview.
128 * We check if the PDB model id is already loaded in Chimera, if so don't
129 * reopen it. This is the case if Chimera has opened a saved session file.
134 public boolean openFile(PDBEntry pe)
136 String file = pe.getFile();
139 List<ChimeraModel> modelsToMap = new ArrayList<>();
140 List<ChimeraModel> oldList = viewer.getModelList();
141 boolean alreadyOpen = false;
144 * If Chimera already has this model, don't reopen it, but do remap it.
146 for (ChimeraModel open : oldList)
148 if (open.getModelName().equals(pe.getId()))
151 modelsToMap.add(open);
156 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
157 * the model name(s) added by Chimera.
161 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
162 List<ChimeraModel> newList = viewer.getModelList();
163 // JAL-1728 newList.removeAll(oldList) does not work
164 for (ChimeraModel cm : newList)
166 if (cm.getModelName().equals(pe.getId()))
173 chimeraMaps.put(file, modelsToMap);
175 if (getSsm() != null)
177 getSsm().addStructureViewerListener(this);
180 } catch (Exception q)
182 log("Exception when trying to open model " + file + "\n"
197 public JalviewChimeraBinding(StructureSelectionManager ssm,
198 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
199 DataSourceType protocol)
201 super(ssm, pdbentry, sequenceIs, protocol);
202 viewer = new ChimeraManager(new StructureManager(true));
206 * Starts a thread that waits for the Chimera process to finish, so that we
207 * can then close the associated resources. This avoids leaving orphaned
208 * Chimera viewer panels in Jalview if the user closes Chimera.
210 protected void startChimeraProcessMonitor()
212 final Process p = viewer.getChimeraProcess();
213 chimeraMonitor = new Thread(new Runnable()
222 JalviewStructureDisplayI display = getViewer();
225 display.closeViewer(false);
227 } catch (InterruptedException e)
229 // exit thread if Chimera Viewer is closed in Jalview
233 chimeraMonitor.start();
237 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
238 * it to start listening
240 public void startChimeraListener()
244 chimeraListener = new ChimeraListener(this);
245 viewer.startListening(chimeraListener.getUri());
246 } catch (BindException e)
249 "Failed to start Chimera listener: " + e.getMessage());
254 * Close down the Jalview viewer and listener, and (optionally) the associated
257 public void closeViewer(boolean closeChimera)
259 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
262 viewer.exitChimera();
264 if (this.chimeraListener != null)
266 chimeraListener.shutdown();
267 chimeraListener = null;
271 if (chimeraMonitor != null)
273 chimeraMonitor.interrupt();
275 releaseUIResources();
279 public void colourByChain()
281 colourBySequence = false;
282 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
286 * Constructs and sends a Chimera command to colour by charge
288 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
289 * <li>Lysine and Arginine (positive charge) blue</li>
290 * <li>Cysteine - yellow</li>
291 * <li>all others - white</li>
295 public void colourByCharge()
297 colourBySequence = false;
298 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
299 sendAsynchronousCommand(command, COLOURING_CHIMERA);
306 public String superposeStructures(AlignmentI[] _alignment,
307 int[] _refStructure, HiddenColumns[] _hiddenCols)
309 StringBuilder allComs = new StringBuilder(128);
310 String[] files = getStructureFiles();
312 if (!waitForFileLoad(files))
318 StringBuilder selectioncom = new StringBuilder(256);
319 for (int a = 0; a < _alignment.length; a++)
321 int refStructure = _refStructure[a];
322 AlignmentI alignment = _alignment[a];
323 HiddenColumns hiddenCols = _hiddenCols[a];
325 if (refStructure >= files.length)
327 System.err.println("Ignoring invalid reference structure value "
333 * 'matched' bit i will be set for visible alignment columns i where
334 * all sequences have a residue with a mapping to the PDB structure
336 BitSet matched = new BitSet();
337 for (int m = 0; m < alignment.getWidth(); m++)
339 if (hiddenCols == null || hiddenCols.isVisible(m))
345 SuperposeData[] structures = new SuperposeData[files.length];
346 for (int f = 0; f < files.length; f++)
348 structures[f] = new SuperposeData(alignment.getWidth());
352 * Calculate the superposable alignment columns ('matched'), and the
353 * corresponding structure residue positions (structures.pdbResNo)
355 int candidateRefStructure = findSuperposableResidues(alignment,
356 matched, structures);
357 if (refStructure < 0)
360 * If no reference structure was specified, pick the first one that has
361 * a mapping in the alignment
363 refStructure = candidateRefStructure;
366 int nmatched = matched.cardinality();
369 return MessageManager.formatMessage("label.insufficient_residues",
374 * Generate select statements to select regions to superimpose structures
376 String[] selcom = new String[files.length];
377 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
379 String chainCd = "." + structures[pdbfnum].chain;
382 StringBuilder molsel = new StringBuilder();
384 int nextColumnMatch = matched.nextSetBit(0);
385 while (nextColumnMatch != -1)
387 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
388 if (lpos != pdbResNum - 1)
391 * discontiguous - append last residue now
395 molsel.append(String.valueOf(lpos));
396 molsel.append(chainCd);
404 * extending a contiguous run
409 * start the range selection
411 molsel.append(String.valueOf(lpos));
417 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
421 * and terminate final selection
425 molsel.append(String.valueOf(lpos));
426 molsel.append(chainCd);
428 if (molsel.length() > 1)
430 selcom[pdbfnum] = molsel.toString();
431 selectioncom.append("#").append(String.valueOf(pdbfnum))
433 selectioncom.append(selcom[pdbfnum]);
434 selectioncom.append(" ");
435 if (pdbfnum < files.length - 1)
437 selectioncom.append("| ");
442 selcom[pdbfnum] = null;
446 StringBuilder command = new StringBuilder(256);
447 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
449 if (pdbfnum == refStructure || selcom[pdbfnum] == null
450 || selcom[refStructure] == null)
454 if (command.length() > 0)
460 * Form Chimera match command, from the 'new' structure to the
461 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
463 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
466 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
468 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
469 command.append(selcom[pdbfnum]);
470 command.append("@").append(
471 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
472 // JAL-1757 exclude alternate CA locations
473 command.append(NO_ALTLOCS);
474 command.append(" ").append(getModelSpec(refStructure)).append(":");
475 command.append(selcom[refStructure]);
476 command.append("@").append(
477 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
478 command.append(NO_ALTLOCS);
480 if (selectioncom.length() > 0)
484 System.out.println("Select regions:\n" + selectioncom.toString());
486 "Superimpose command(s):\n" + command.toString());
488 allComs/*.append("~display all; chain @CA|P; ribbon ")
489 .append(selectioncom.toString())*/
490 .append(";" + command.toString());
495 if (selectioncom.length() > 0)
497 // TODO: visually distinguish regions that were superposed
498 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
500 selectioncom.setLength(selectioncom.length() - 1);
504 System.out.println("Select regions:\n" + selectioncom.toString());
506 allComs.append("; ~display "); // all");
507 if (!isShowAlignmentOnly())
509 allComs.append("; ribbon; chain @CA|P");
513 allComs.append("; ~ribbon");
515 allComs.append("; ribbon ").append(selectioncom.toString())
517 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
519 for (String reply : chimeraReplies)
521 String lowerCase = reply.toLowerCase();
522 if (lowerCase.contains("unequal numbers of atoms")
523 || lowerCase.contains("at least"))
533 * Helper method to construct model spec in Chimera format:
535 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
536 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
538 * Note for now we only ever choose the first of multiple models. This
539 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
540 * future if there is a need to select specific sub-models.
545 protected String getModelSpec(int pdbfnum)
547 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
553 * For now, the test for having sub-models is whether multiple Chimera
554 * models are mapped for the PDB file; the models are returned as a response
555 * to the Chimera command 'list models type molecule', see
556 * ChimeraManager.getModelList().
558 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
559 boolean hasSubModels = maps != null && maps.size() > 1;
560 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
564 * Launch Chimera, unless an instance linked to this object is already
565 * running. Returns true if Chimera is successfully launched, or already
566 * running, else false.
570 public boolean launchChimera()
572 if (viewer.isChimeraLaunched())
577 boolean launched = viewer
578 .launchChimera(StructureManager.getChimeraPaths());
581 startChimeraProcessMonitor();
585 log("Failed to launch Chimera!");
591 * Answers true if the Chimera process is still running, false if ended or not
596 public boolean isChimeraRunning()
598 return viewer.isChimeraLaunched();
602 * Send a command to Chimera, and optionally log and return any responses.
604 * Does nothing, and returns null, if the command is the same as the last one
610 public List<String> sendChimeraCommand(final String command,
615 // ? thread running after viewer shut down
618 List<String> reply = null;
619 viewerCommandHistory(false);
620 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
622 // trim command or it may never find a match in the replyLog!!
623 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
630 log("Response from command ('" + command + "') was:\n"
635 viewerCommandHistory(true);
641 * Send a Chimera command asynchronously in a new thread. If the progress
642 * message is not null, display this message while the command is executing.
647 protected abstract void sendAsynchronousCommand(String command,
651 * Sends a set of colour commands to the structure viewer
653 * @param colourBySequenceCommands
656 protected void colourBySequence(
657 StructureMappingcommandSet[] colourBySequenceCommands)
659 for (StructureMappingcommandSet cpdbbyseq : colourBySequenceCommands)
661 for (String command : cpdbbyseq.commands)
663 sendAsynchronousCommand(command, COLOURING_CHIMERA);
675 protected StructureMappingcommandSet[] getColourBySequenceCommands(
676 String[] files, SequenceRenderer sr, AlignmentViewPanel viewPanel)
678 return ChimeraCommands.getColourBySequenceCommand(getSsm(), files,
679 getSequence(), sr, viewPanel);
685 protected void executeWhenReady(String command)
688 sendChimeraCommand(command, false);
692 private void waitForChimera()
694 while (viewer != null && viewer.isBusy())
699 } catch (InterruptedException q)
705 // End StructureListener
706 // //////////////////////////
709 * instruct the Jalview binding to update the pdbentries vector if necessary
710 * prior to matching the viewer's contents to the list of structure files
711 * Jalview knows about.
713 public abstract void refreshPdbEntries();
716 * map between index of model filename returned from getPdbFile and the first
717 * index of models from this file in the viewer. Note - this is not trimmed -
718 * use getPdbFile to get number of unique models.
720 private int _modelFileNameMap[];
722 // ////////////////////////////////
723 // /StructureListener
725 public synchronized String[] getStructureFiles()
729 return new String[0];
732 return chimeraMaps.keySet()
733 .toArray(modelFileNames = new String[chimeraMaps.size()]);
737 * Construct and send a command to highlight zero, one or more atoms. We do
738 * this by sending an "rlabel" command to show the residue label at that
742 public void highlightAtoms(List<AtomSpec> atoms)
744 if (atoms == null || atoms.size() == 0)
749 StringBuilder cmd = new StringBuilder(128);
750 boolean first = true;
751 boolean found = false;
753 for (AtomSpec atom : atoms)
755 int pdbResNum = atom.getPdbResNum();
756 String chain = atom.getChain();
757 String pdbfile = atom.getPdbFile();
758 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
759 if (cms != null && !cms.isEmpty())
763 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
771 cmd.append(pdbResNum);
772 if (!chain.equals(" "))
774 cmd.append(".").append(chain);
779 String command = cmd.toString();
782 * avoid repeated commands for the same residue
784 if (command.equals(lastHighlightCommand))
790 * unshow the label for the previous residue
792 if (lastHighlightCommand != null)
794 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
798 viewer.sendChimeraCommand(command, false);
800 this.lastHighlightCommand = command;
804 * Query Chimera for its current selection, and highlight it on the alignment
806 public void highlightChimeraSelection()
809 * Ask Chimera for its current selection
811 List<String> selection = viewer.getSelectedResidueSpecs();
814 * Parse model number, residue and chain for each selected position,
815 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
817 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
821 * Broadcast the selection (which may be empty, if the user just cleared all
824 getSsm().mouseOverStructure(atomSpecs);
828 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
829 * corresponding residues (if any) in Jalview
831 * @param structureSelection
834 protected List<AtomSpec> convertStructureResiduesToAlignment(
835 List<String> structureSelection)
837 List<AtomSpec> atomSpecs = new ArrayList<>();
838 for (String atomSpec : structureSelection)
842 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
843 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
844 spec.setPdbFile(pdbfilename);
846 } catch (IllegalArgumentException e)
848 System.err.println("Failed to parse atomspec: " + atomSpec);
858 protected String getPdbFileForModel(int modelId)
861 * Work out the pdbfilename from the model number
863 String pdbfilename = modelFileNames[0];
864 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
866 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
868 if (cm.getModelNumber() == modelId)
870 pdbfilename = pdbfile;
878 private void log(String message)
880 System.err.println("## Chimera log: " + message);
883 private void viewerCommandHistory(boolean enable)
885 // log("(Not yet implemented) History "
886 // + ((debug || enable) ? "on" : "off"));
889 public long getLoadNotifiesHandled()
891 return loadNotifiesHandled;
895 public void setJalviewColourScheme(ColourSchemeI cs)
897 colourBySequence = false;
904 // Chimera expects RBG values in the range 0-1
905 final double normalise = 255D;
906 viewerCommandHistory(false);
907 StringBuilder command = new StringBuilder(128);
909 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
911 for (String resName : residueSet)
913 char res = resName.length() == 3
914 ? ResidueProperties.getSingleCharacterCode(resName)
916 Color col = cs.findColour(res, 0, null, null, 0f);
917 command.append("color " + col.getRed() / normalise + ","
918 + col.getGreen() / normalise + "," + col.getBlue() / normalise
919 + " ::" + resName + ";");
922 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
923 viewerCommandHistory(true);
927 * called when the binding thinks the UI needs to be refreshed after a Chimera
928 * state change. this could be because structures were loaded, or because an
929 * error has occurred.
931 public abstract void refreshGUI();
934 public void setLoadingFromArchive(boolean loadingFromArchive)
936 this.loadingFromArchive = loadingFromArchive;
941 * @return true if Chimeral is still restoring state or loading is still going
942 * on (see setFinsihedLoadingFromArchive)
945 public boolean isLoadingFromArchive()
947 return loadingFromArchive && !loadingFinished;
951 * modify flag which controls if sequence colouring events are honoured by the
952 * binding. Should be true for normal operation
954 * @param finishedLoading
957 public void setFinishedLoadingFromArchive(boolean finishedLoading)
959 loadingFinished = finishedLoading;
963 * Send the Chimera 'background solid <color>" command.
966 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
971 public void setBackgroundColour(Color col)
973 viewerCommandHistory(false);
974 double normalise = 255D;
975 final String command = "background solid " + col.getRed() / normalise
976 + "," + col.getGreen() / normalise + ","
977 + col.getBlue() / normalise + ";";
978 viewer.sendChimeraCommand(command, false);
979 viewerCommandHistory(true);
983 * Ask Chimera to save its session to the given file. Returns true if
984 * successful, else false.
989 public boolean saveSession(String filepath)
991 if (isChimeraRunning())
993 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
995 if (reply.contains("Session written"))
1002 .error("Error saving Chimera session: " + reply.toString());
1009 * Ask Chimera to open a session file. Returns true if successful, else false.
1010 * The filename must have a .py extension for this command to work.
1015 public boolean openSession(String filepath)
1017 sendChimeraCommand("open " + filepath, true);
1018 // todo: test for failure - how?
1023 * Returns a list of chains mapped in this viewer. Note this list is not
1024 * currently scoped per structure.
1029 public List<String> getChainNames()
1035 * Send a 'focus' command to Chimera to recentre the visible display
1037 public void focusView()
1039 sendChimeraCommand("focus", false);
1043 * Send a 'show' command for all atoms in the currently selected columns
1045 * TODO: pull up to abstract structure viewer interface
1049 public void highlightSelection(AlignmentViewPanel vp)
1051 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1053 AlignmentI alignment = vp.getAlignment();
1054 StructureSelectionManager sm = getSsm();
1055 for (SequenceI seq : alignment.getSequences())
1058 * convert selected columns into sequence positions
1060 int[] positions = new int[cols.size()];
1062 for (Integer col : cols)
1064 positions[i++] = seq.findPosition(col);
1066 sm.highlightStructure(this, seq, positions);
1071 * Constructs and send commands to Chimera to set attributes on residues for
1072 * features visible in Jalview
1077 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1079 // TODO refactor as required to pull up to an interface
1080 AlignmentI alignment = avp.getAlignment();
1082 String[] files = getStructureFiles();
1088 StructureMappingcommandSet commandSet = ChimeraCommands
1089 .getSetAttributeCommandsForFeatures(getSsm(), files,
1090 getSequence(), avp);
1091 String[] commands = commandSet.commands;
1092 if (commands.length > 10)
1094 sendCommandsByFile(commands);
1098 for (String command : commands)
1100 sendAsynchronousCommand(command, null);
1103 return commands.length;
1107 * Write commands to a temporary file, and send a command to Chimera to open
1108 * the file as a commands script. For use when sending a large number of
1109 * separate commands would overload the REST interface mechanism.
1113 protected void sendCommandsByFile(String[] commands)
1117 File tmp = File.createTempFile("chim", ".com");
1119 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1120 for (String command : commands)
1122 out.println(command);
1126 String path = tmp.getAbsolutePath();
1127 sendAsynchronousCommand("open cmd:" + path, null);
1128 } catch (IOException e)
1130 System.err.println("Sending commands to Chimera via file failed with "
1136 * Get Chimera residues which have the named attribute, find the mapped
1137 * positions in the Jalview sequence(s), and set as sequence features
1140 * @param alignmentPanel
1142 public void copyStructureAttributesToFeatures(String attName,
1143 AlignmentViewPanel alignmentPanel)
1145 // todo pull up to AAStructureBindingModel (and interface?)
1148 * ask Chimera to list residues with the attribute, reporting its value
1150 // this alternative command
1151 // list residues spec ':*/attName' attr attName
1152 // doesn't report 'None' values (which is good), but
1153 // fails for 'average.bfactor' (which is bad):
1155 String cmd = "list residues attr '" + attName + "'";
1156 List<String> residues = sendChimeraCommand(cmd, true);
1158 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1161 alignmentPanel.getFeatureRenderer().featuresAdded();
1166 * Create features in Jalview for the given attribute name and structure
1170 * The residue list should be 0, 1 or more reply lines of the format:
1171 * residue id #0:5.A isHelix -155.000836316 index 5
1173 * residue id #0:6.A isHelix None
1180 protected boolean createFeaturesForAttributes(String attName,
1181 List<String> residues)
1183 boolean featureAdded = false;
1184 String featureGroup = getViewerFeatureGroup();
1186 for (String residue : residues)
1188 AtomSpec spec = null;
1189 String[] tokens = residue.split(" ");
1190 if (tokens.length < 5)
1194 String atomSpec = tokens[2];
1195 String attValue = tokens[4];
1198 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1200 if ("None".equalsIgnoreCase(attValue)
1201 || "False".equalsIgnoreCase(attValue))
1208 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1209 } catch (IllegalArgumentException e)
1211 System.err.println("Problem parsing atomspec " + atomSpec);
1215 String chainId = spec.getChain();
1216 String description = attValue;
1217 float score = Float.NaN;
1220 score = Float.valueOf(attValue);
1221 description = chainId;
1222 } catch (NumberFormatException e)
1224 // was not a float value
1227 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1228 spec.setPdbFile(pdbFile);
1230 List<AtomSpec> atoms = Collections.singletonList(spec);
1233 * locate the mapped position in the alignment (if any)
1235 SearchResultsI sr = getSsm()
1236 .findAlignmentPositionsForStructurePositions(atoms);
1239 * expect one matched alignment position, or none
1240 * (if the structure position is not mapped)
1242 for (SearchResultMatchI m : sr.getResults())
1244 SequenceI seq = m.getSequence();
1245 int start = m.getStart();
1246 int end = m.getEnd();
1247 SequenceFeature sf = new SequenceFeature(attName, description,
1248 start, end, score, featureGroup);
1249 // todo: should SequenceFeature have an explicit property for chain?
1250 // note: repeating the action shouldn't duplicate features
1251 featureAdded |= seq.addSequenceFeature(sf);
1254 return featureAdded;
1258 * Answers the feature group name to apply to features created in Jalview from
1259 * Chimera attributes
1263 protected String getViewerFeatureGroup()
1265 // todo pull up to interface
1266 return CHIMERA_FEATURE_GROUP;
1269 public Hashtable<String, String> getChainFile()
1274 public List<ChimeraModel> getChimeraModelByChain(String chain)
1276 return chimeraMaps.get(chainFile.get(chain));
1279 public int getModelNoForChain(String chain)
1281 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1282 if (foundModels != null && !foundModels.isEmpty())
1284 return foundModels.get(0).getModelNumber();
1290 public void showStructures(AlignViewportI av, boolean refocus)
1292 StringBuilder cmd = new StringBuilder(128);
1293 cmd.append("~display; ~ribbon;");
1294 String atomSpec = getMappedResidues(av);
1295 cmd.append("ribbon ").append(atomSpec);
1296 if (!isShowAlignmentOnly())
1298 cmd.append("chain @CA|P; ribbon");
1302 cmd.append("; focus");
1304 sendChimeraCommand(cmd.toString(), false);
1308 * Builds a Chimera atomSpec of residues mapped from sequences, of the format
1309 * (#model:residues.chain)
1312 * #0:2-94.A | #1:1-93.C | #2:1-93.A
1315 * Only residues visible in the alignment are included, that is, hidden columns
1316 * and sequences are excluded.
1321 private String getMappedResidues(AlignViewportI av)
1323 AlignmentI alignment = av.getAlignment();
1324 final int width = alignment.getWidth();
1326 String[] files = getStructureFiles();
1328 StringBuilder atomSpec = new StringBuilder(256);
1330 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1332 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
1335 * Find the first mapped sequence (if any) for this PDB entry which is in
1338 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
1339 for (int s = 0; s < seqCountForPdbFile; s++)
1341 for (StructureMapping mapping : mappings)
1343 final SequenceI theSequence = getSequence()[pdbfnum][s];
1344 if (mapping.getSequence() == theSequence
1345 && alignment.findIndex(theSequence) > -1)
1347 String chainCd = mapping.getChain();
1348 if (!isShowChain(mapping.getPdbId(), chainCd))
1352 Iterator<int[]> visible;
1353 if (isShowAlignmentOnly())
1355 visible = alignment.getHiddenColumns()
1356 .getVisContigsIterator(0, width, true);
1360 visible = Collections.singletonList(new int[] { 0, width })
1363 while (visible.hasNext())
1365 int[] visibleRegion = visible.next();
1366 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1367 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1368 List<int[]> residueRanges = mapping
1369 .getPDBResNumRanges(seqStartPos, seqEndPos);
1370 if (!residueRanges.isEmpty())
1372 if (atomSpec.length() > 0)
1374 atomSpec.append("| ");
1376 atomSpec.append(getModelSpec(pdbfnum)).append(":");
1377 boolean first = true;
1378 for (int[] range : residueRanges)
1382 atomSpec.append(",");
1385 atomSpec.append(range[0]).append("-").append(range[1]);
1386 atomSpec.append(".").append(chainCd);
1395 return atomSpec.toString();