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.structures.JalviewStructureDisplayI;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SearchResultMatchI;
31 import jalview.datamodel.SearchResultsI;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.httpserver.AbstractRequestHandler;
35 import jalview.io.DataSourceType;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ResidueProperties;
38 import jalview.structure.AtomSpec;
39 import jalview.structure.StructureMappingcommandSet;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.structures.models.AAStructureBindingModel;
42 import jalview.util.MessageManager;
44 import java.awt.Color;
46 import java.io.FileOutputStream;
47 import java.io.IOException;
48 import java.io.PrintWriter;
49 import java.net.BindException;
50 import java.util.ArrayList;
51 import java.util.BitSet;
52 import java.util.Collections;
53 import java.util.Hashtable;
54 import java.util.LinkedHashMap;
55 import java.util.List;
58 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
59 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
60 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
61 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
63 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
65 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
67 // Chimera clause to exclude alternate locations in atom selection
68 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
70 private static final String COLOURING_CHIMERA = MessageManager
71 .getString("status.colouring_chimera");
73 private static final boolean debug = false;
75 private static final String PHOSPHORUS = "P";
77 private static final String ALPHACARBON = "CA";
79 private List<String> chainNames = new ArrayList<>();
81 private Hashtable<String, String> chainFile = new Hashtable<>();
84 * Object through which we talk to Chimera
86 private ChimeraManager viewer;
89 * Object which listens to Chimera notifications
91 private AbstractRequestHandler chimeraListener;
94 * set if chimera state is being restored from some source - instructs binding
95 * not to apply default display style when structure set is updated for first
98 private boolean loadingFromArchive = false;
101 * flag to indicate if the Chimera viewer should ignore sequence colouring
102 * events from the structure manager because the GUI is still setting up
104 private boolean loadingFinished = true;
107 * Map of ChimeraModel objects keyed by PDB full local file name
109 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
111 String lastHighlightCommand;
114 * incremented every time a load notification is successfully handled -
115 * lightweight mechanism for other threads to detect when they can start
116 * referring to new structures.
118 private long loadNotifiesHandled = 0;
120 private Thread chimeraMonitor;
123 * Open a PDB structure file in Chimera and set up mappings from Jalview.
125 * We check if the PDB model id is already loaded in Chimera, if so don't
126 * reopen it. This is the case if Chimera has opened a saved session file.
131 public boolean openFile(PDBEntry pe)
133 String file = pe.getFile();
136 List<ChimeraModel> modelsToMap = new ArrayList<>();
137 List<ChimeraModel> oldList = viewer.getModelList();
138 boolean alreadyOpen = false;
141 * If Chimera already has this model, don't reopen it, but do remap it.
143 for (ChimeraModel open : oldList)
145 if (open.getModelName().equals(pe.getId()))
148 modelsToMap.add(open);
153 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
154 * the model name(s) added by Chimera.
158 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
159 List<ChimeraModel> newList = viewer.getModelList();
160 // JAL-1728 newList.removeAll(oldList) does not work
161 for (ChimeraModel cm : newList)
163 if (cm.getModelName().equals(pe.getId()))
170 chimeraMaps.put(file, modelsToMap);
172 if (getSsm() != null)
174 getSsm().addStructureViewerListener(this);
177 } catch (Exception q)
179 log("Exception when trying to open model " + file + "\n"
194 public JalviewChimeraBinding(StructureSelectionManager ssm,
195 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
196 DataSourceType protocol)
198 super(ssm, pdbentry, sequenceIs, protocol);
199 viewer = new ChimeraManager(new StructureManager(true));
203 * Starts a thread that waits for the Chimera process to finish, so that we
204 * can then close the associated resources. This avoids leaving orphaned
205 * Chimera viewer panels in Jalview if the user closes Chimera.
207 protected void startChimeraProcessMonitor()
209 final Process p = viewer.getChimeraProcess();
210 chimeraMonitor = new Thread(new Runnable()
219 JalviewStructureDisplayI display = getViewer();
222 display.closeViewer(false);
224 } catch (InterruptedException e)
226 // exit thread if Chimera Viewer is closed in Jalview
230 chimeraMonitor.start();
234 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
235 * it to start listening
237 public void startChimeraListener()
241 chimeraListener = new ChimeraListener(this);
242 viewer.startListening(chimeraListener.getUri());
243 } catch (BindException e)
246 "Failed to start Chimera listener: " + e.getMessage());
251 * Close down the Jalview viewer and listener, and (optionally) the associated
254 public void closeViewer(boolean closeChimera)
256 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
259 viewer.exitChimera();
261 if (this.chimeraListener != null)
263 chimeraListener.shutdown();
264 chimeraListener = null;
268 if (chimeraMonitor != null)
270 chimeraMonitor.interrupt();
272 releaseUIResources();
276 public void colourByChain()
278 colourBySequence = false;
279 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
283 * Constructs and sends a Chimera command to colour by charge
285 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
286 * <li>Lysine and Arginine (positive charge) blue</li>
287 * <li>Cysteine - yellow</li>
288 * <li>all others - white</li>
292 public void colourByCharge()
294 colourBySequence = false;
295 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
296 sendAsynchronousCommand(command, COLOURING_CHIMERA);
303 public String superposeStructures(AlignmentI[] _alignment,
304 int[] _refStructure, HiddenColumns[] _hiddenCols)
306 StringBuilder allComs = new StringBuilder(128);
307 String[] files = getStructureFiles();
309 if (!waitForFileLoad(files))
315 StringBuilder selectioncom = new StringBuilder(256);
316 for (int a = 0; a < _alignment.length; a++)
318 int refStructure = _refStructure[a];
319 AlignmentI alignment = _alignment[a];
320 HiddenColumns hiddenCols = _hiddenCols[a];
322 if (refStructure >= files.length)
324 System.err.println("Ignoring invalid reference structure value "
330 * 'matched' bit i will be set for visible alignment columns i where
331 * all sequences have a residue with a mapping to the PDB structure
333 BitSet matched = new BitSet();
334 for (int m = 0; m < alignment.getWidth(); m++)
336 if (hiddenCols == null || hiddenCols.isVisible(m))
342 SuperposeData[] structures = new SuperposeData[files.length];
343 for (int f = 0; f < files.length; f++)
345 structures[f] = new SuperposeData(alignment.getWidth());
349 * Calculate the superposable alignment columns ('matched'), and the
350 * corresponding structure residue positions (structures.pdbResNo)
352 int candidateRefStructure = findSuperposableResidues(alignment,
353 matched, structures);
354 if (refStructure < 0)
357 * If no reference structure was specified, pick the first one that has
358 * a mapping in the alignment
360 refStructure = candidateRefStructure;
363 int nmatched = matched.cardinality();
366 return MessageManager.formatMessage("label.insufficient_residues",
371 * Generate select statements to select regions to superimpose structures
373 String[] selcom = new String[files.length];
374 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
376 String chainCd = "." + structures[pdbfnum].chain;
379 StringBuilder molsel = new StringBuilder();
381 int nextColumnMatch = matched.nextSetBit(0);
382 while (nextColumnMatch != -1)
384 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
385 if (lpos != pdbResNum - 1)
388 * discontiguous - append last residue now
392 molsel.append(String.valueOf(lpos));
393 molsel.append(chainCd);
401 * extending a contiguous run
406 * start the range selection
408 molsel.append(String.valueOf(lpos));
414 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
418 * and terminate final selection
422 molsel.append(String.valueOf(lpos));
423 molsel.append(chainCd);
425 if (molsel.length() > 1)
427 selcom[pdbfnum] = molsel.toString();
428 selectioncom.append("#").append(String.valueOf(pdbfnum))
430 selectioncom.append(selcom[pdbfnum]);
431 selectioncom.append(" ");
432 if (pdbfnum < files.length - 1)
434 selectioncom.append("| ");
439 selcom[pdbfnum] = null;
443 StringBuilder command = new StringBuilder(256);
444 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
446 if (pdbfnum == refStructure || selcom[pdbfnum] == null
447 || selcom[refStructure] == null)
451 if (command.length() > 0)
457 * Form Chimera match command, from the 'new' structure to the
458 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
460 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
463 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
465 command.append("match ").append(getModelSpec(pdbfnum))
467 command.append(selcom[pdbfnum]);
468 command.append("@").append(
469 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
470 // JAL-1757 exclude alternate CA locations
471 command.append(NO_ALTLOCS);
472 command.append(" ").append(getModelSpec(refStructure)).append(":");
473 command.append(selcom[refStructure]);
474 command.append("@").append(
475 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
476 command.append(NO_ALTLOCS);
478 if (selectioncom.length() > 0)
482 System.out.println("Select regions:\n" + selectioncom.toString());
484 "Superimpose command(s):\n" + command.toString());
486 allComs/*.append("~display all; chain @CA|P; ribbon ")
487 .append(selectioncom.toString())*/
488 .append(";" + command.toString());
493 if (selectioncom.length() > 0)
495 // TODO: visually distinguish regions that were superposed
496 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
498 selectioncom.setLength(selectioncom.length() - 1);
502 System.out.println("Select regions:\n" + selectioncom.toString());
504 allComs.append("; ~display "); // all");
505 if (!isShowAlignmentOnly())
507 allComs.append("; ribbon; chain @CA|P");
511 allComs.append("; ~ribbon");
513 allComs.append("; ribbon ").append(selectioncom.toString())
515 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
517 for (String reply : chimeraReplies)
519 String lowerCase = reply.toLowerCase();
520 if (lowerCase.contains("unequal numbers of atoms")
521 || lowerCase.contains("at least"))
531 * Helper method to construct model spec in Chimera format:
533 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
534 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
536 * Note for now we only ever choose the first of multiple models. This
537 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
538 * future if there is a need to select specific sub-models.
544 public String getModelSpec(int pdbfnum)
546 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
552 * For now, the test for having sub-models is whether multiple Chimera
553 * models are mapped for the PDB file; the models are returned as a response
554 * to the Chimera command 'list models type molecule', see
555 * ChimeraManager.getModelList().
557 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
558 boolean hasSubModels = maps != null && maps.size() > 1;
559 String spec = "#" + String.valueOf(pdbfnum);
560 return hasSubModels ? spec + ".1" : spec;
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
656 protected void colourBySequence(String[] commands)
658 for (String command : commands)
660 sendAsynchronousCommand(command, COLOURING_CHIMERA);
665 * Computes and returns a set of commands to colour residues in Chimera the same
666 * as mapped residues in the alignment
673 protected String[] getColourBySequenceCommands(
674 String[] files, AlignmentViewPanel viewPanel)
676 Map<Object, AtomSpecModel> colourMap = buildColoursMap(viewPanel);
678 return ChimeraCommands.getColourBySequenceCommand(colourMap, this);
684 protected void executeWhenReady(String command)
687 sendChimeraCommand(command, false);
691 private void waitForChimera()
693 while (viewer != null && viewer.isBusy())
698 } catch (InterruptedException q)
704 // End StructureListener
705 // //////////////////////////
708 * instruct the Jalview binding to update the pdbentries vector if necessary
709 * prior to matching the viewer's contents to the list of structure files
710 * Jalview knows about.
712 public abstract void refreshPdbEntries();
715 * map between index of model filename returned from getPdbFile and the first
716 * index of models from this file in the viewer. Note - this is not trimmed -
717 * use getPdbFile to get number of unique models.
719 private int _modelFileNameMap[];
721 // ////////////////////////////////
722 // /StructureListener
724 public synchronized String[] getStructureFiles()
728 return new String[0];
731 return chimeraMaps.keySet()
732 .toArray(modelFileNames = new String[chimeraMaps.size()]);
736 * Construct and send a command to highlight zero, one or more atoms. We do
737 * this by sending an "rlabel" command to show the residue label at that
741 public void highlightAtoms(List<AtomSpec> atoms)
743 if (atoms == null || atoms.size() == 0)
748 StringBuilder cmd = new StringBuilder(128);
749 boolean first = true;
750 boolean found = false;
752 for (AtomSpec atom : atoms)
754 int pdbResNum = atom.getPdbResNum();
755 String chain = atom.getChain();
756 String pdbfile = atom.getPdbFile();
757 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
758 if (cms != null && !cms.isEmpty())
762 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
770 cmd.append(pdbResNum);
771 if (!chain.equals(" "))
773 cmd.append(".").append(chain);
778 String command = cmd.toString();
781 * avoid repeated commands for the same residue
783 if (command.equals(lastHighlightCommand))
789 * unshow the label for the previous residue
791 if (lastHighlightCommand != null)
793 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
797 viewer.sendChimeraCommand(command, false);
799 this.lastHighlightCommand = command;
803 * Query Chimera for its current selection, and highlight it on the alignment
805 public void highlightChimeraSelection()
808 * Ask Chimera for its current selection
810 List<String> selection = viewer.getSelectedResidueSpecs();
813 * Parse model number, residue and chain for each selected position,
814 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
816 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
820 * Broadcast the selection (which may be empty, if the user just cleared all
823 getSsm().mouseOverStructure(atomSpecs);
827 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
828 * corresponding residues (if any) in Jalview
830 * @param structureSelection
833 protected List<AtomSpec> convertStructureResiduesToAlignment(
834 List<String> structureSelection)
836 List<AtomSpec> atomSpecs = new ArrayList<>();
837 for (String atomSpec : structureSelection)
841 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
842 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
843 spec.setPdbFile(pdbfilename);
845 } catch (IllegalArgumentException e)
847 System.err.println("Failed to parse atomspec: " + atomSpec);
857 protected String getPdbFileForModel(int modelId)
860 * Work out the pdbfilename from the model number
862 String pdbfilename = modelFileNames[0];
863 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
865 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
867 if (cm.getModelNumber() == modelId)
869 pdbfilename = pdbfile;
877 private void log(String message)
879 System.err.println("## Chimera log: " + message);
882 private void viewerCommandHistory(boolean enable)
884 // log("(Not yet implemented) History "
885 // + ((debug || enable) ? "on" : "off"));
888 public long getLoadNotifiesHandled()
890 return loadNotifiesHandled;
894 public void setJalviewColourScheme(ColourSchemeI cs)
896 colourBySequence = false;
903 // Chimera expects RGB values in the range 0-1
904 final double normalise = 255D;
905 viewerCommandHistory(false);
906 StringBuilder command = new StringBuilder(128);
908 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
910 for (String resName : residueSet)
912 char res = resName.length() == 3
913 ? ResidueProperties.getSingleCharacterCode(resName)
915 Color col = cs.findColour(res, 0, null, null, 0f);
916 command.append("color ")
917 .append(String.valueOf(col.getRed() / normalise)).append(",")
918 .append(String.valueOf(col.getGreen() / normalise))
919 .append(",").append(String.valueOf(col.getBlue() / normalise))
920 .append(" ::").append(resName).append(";");
923 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
924 viewerCommandHistory(true);
928 * called when the binding thinks the UI needs to be refreshed after a Chimera
929 * state change. this could be because structures were loaded, or because an
930 * error has occurred.
932 public abstract void refreshGUI();
935 public void setLoadingFromArchive(boolean loadingFromArchive)
937 this.loadingFromArchive = loadingFromArchive;
942 * @return true if Chimeral is still restoring state or loading is still going
943 * on (see setFinsihedLoadingFromArchive)
946 public boolean isLoadingFromArchive()
948 return loadingFromArchive && !loadingFinished;
952 * modify flag which controls if sequence colouring events are honoured by the
953 * binding. Should be true for normal operation
955 * @param finishedLoading
958 public void setFinishedLoadingFromArchive(boolean finishedLoading)
960 loadingFinished = finishedLoading;
964 * Send the Chimera 'background solid <color>" command.
967 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
972 public void setBackgroundColour(Color col)
974 viewerCommandHistory(false);
975 double normalise = 255D;
976 final String command = "background solid " + col.getRed() / normalise
977 + "," + col.getGreen() / normalise + ","
978 + col.getBlue() / normalise + ";";
979 viewer.sendChimeraCommand(command, false);
980 viewerCommandHistory(true);
984 * Ask Chimera to save its session to the given file. Returns true if
985 * successful, else false.
990 public boolean saveSession(String filepath)
992 if (isChimeraRunning())
994 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
996 if (reply.contains("Session written"))
1003 .error("Error saving Chimera session: " + reply.toString());
1010 * Ask Chimera to open a session file. Returns true if successful, else false.
1011 * The filename must have a .py extension for this command to work.
1016 public boolean openSession(String filepath)
1018 sendChimeraCommand("open " + filepath, true);
1019 // todo: test for failure - how?
1024 * Returns a list of chains mapped in this viewer. Note this list is not
1025 * currently scoped per structure.
1030 public List<String> getChainNames()
1036 * Send a 'focus' command to Chimera to recentre the visible display
1038 public void focusView()
1040 sendChimeraCommand("focus", false);
1044 * Send a 'show' command for all atoms in the currently selected columns
1046 * TODO: pull up to abstract structure viewer interface
1050 public void highlightSelection(AlignmentViewPanel vp)
1052 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1054 AlignmentI alignment = vp.getAlignment();
1055 StructureSelectionManager sm = getSsm();
1056 for (SequenceI seq : alignment.getSequences())
1059 * convert selected columns into sequence positions
1061 int[] positions = new int[cols.size()];
1063 for (Integer col : cols)
1065 positions[i++] = seq.findPosition(col);
1067 sm.highlightStructure(this, seq, positions);
1072 * Constructs and send commands to Chimera to set attributes on residues for
1073 * features visible in Jalview
1078 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1080 // TODO refactor as required to pull up to an interface
1081 AlignmentI alignment = avp.getAlignment();
1083 String[] files = getStructureFiles();
1089 StructureMappingcommandSet commandSet = ChimeraCommands
1090 .getSetAttributeCommandsForFeatures(avp, this);
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;");
1295 AtomSpecModel model = getShownResidues(av);
1296 String atomSpec = ChimeraCommands.getAtomSpec(model, this);
1298 cmd.append("ribbon ").append(atomSpec);
1299 if (!isShowAlignmentOnly())
1301 cmd.append("chain @CA|P; ribbon");
1305 cmd.append("; focus");
1307 sendChimeraCommand(cmd.toString(), false);