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;
43 import jalview.util.StructureCommands;
45 import java.awt.Color;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49 import java.io.PrintWriter;
50 import java.net.BindException;
51 import java.util.ArrayList;
52 import java.util.BitSet;
53 import java.util.Collections;
54 import java.util.Hashtable;
55 import java.util.LinkedHashMap;
56 import java.util.List;
59 import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
60 import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
61 import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
62 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
64 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
66 public static final String CHIMERA_FEATURE_GROUP = "Chimera";
68 // Chimera clause to exclude alternate locations in atom selection
69 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
71 private static final String COLOURING_CHIMERA = MessageManager
72 .getString("status.colouring_chimera");
74 private static final boolean debug = false;
76 private static final String PHOSPHORUS = "P";
78 private static final String ALPHACARBON = "CA";
80 private Hashtable<String, String> chainFile = new Hashtable<>();
83 * Object through which we talk to Chimera
85 private ChimeraManager viewer;
88 * Object which listens to Chimera notifications
90 private AbstractRequestHandler chimeraListener;
93 * set if chimera state is being restored from some source - instructs binding
94 * not to apply default display style when structure set is updated for first
97 private boolean loadingFromArchive = false;
100 * flag to indicate if the Chimera viewer should ignore sequence colouring
101 * events from the structure manager because the GUI is still setting up
103 private boolean loadingFinished = true;
106 * Map of ChimeraModel objects keyed by PDB full local file name
108 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<>();
110 String lastHighlightCommand;
113 * incremented every time a load notification is successfully handled -
114 * lightweight mechanism for other threads to detect when they can start
115 * referring to new structures.
117 private long loadNotifiesHandled = 0;
119 private Thread chimeraMonitor;
122 * Open a PDB structure file in Chimera and set up mappings from Jalview.
124 * We check if the PDB model id is already loaded in Chimera, if so don't
125 * reopen it. This is the case if Chimera has opened a saved session file.
130 public boolean openFile(PDBEntry pe)
132 String file = pe.getFile();
135 List<ChimeraModel> modelsToMap = new ArrayList<>();
136 List<ChimeraModel> oldList = viewer.getModelList();
137 boolean alreadyOpen = false;
140 * If Chimera already has this model, don't reopen it, but do remap it.
142 for (ChimeraModel open : oldList)
144 if (open.getModelName().equals(pe.getId()))
147 modelsToMap.add(open);
152 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
153 * the model name(s) added by Chimera.
157 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
158 List<ChimeraModel> newList = viewer.getModelList();
159 // JAL-1728 newList.removeAll(oldList) does not work
160 for (ChimeraModel cm : newList)
162 if (cm.getModelName().equals(pe.getId()))
169 chimeraMaps.put(file, modelsToMap);
171 if (getSsm() != null)
173 getSsm().addStructureViewerListener(this);
176 } catch (Exception q)
178 log("Exception when trying to open model " + file + "\n"
193 public JalviewChimeraBinding(StructureSelectionManager ssm,
194 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
195 DataSourceType protocol)
197 super(ssm, pdbentry, sequenceIs, protocol);
198 viewer = new ChimeraManager(new StructureManager(true));
202 * Starts a thread that waits for the Chimera process to finish, so that we
203 * can then close the associated resources. This avoids leaving orphaned
204 * Chimera viewer panels in Jalview if the user closes Chimera.
206 protected void startChimeraProcessMonitor()
208 final Process p = viewer.getChimeraProcess();
209 chimeraMonitor = new Thread(new Runnable()
218 JalviewStructureDisplayI display = getViewer();
221 display.closeViewer(false);
223 } catch (InterruptedException e)
225 // exit thread if Chimera Viewer is closed in Jalview
229 chimeraMonitor.start();
233 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
234 * it to start listening
236 public void startChimeraListener()
240 chimeraListener = new ChimeraListener(this);
241 viewer.startListening(chimeraListener.getUri());
242 } catch (BindException e)
245 "Failed to start Chimera listener: " + e.getMessage());
250 * Close down the Jalview viewer and listener, and (optionally) the associated
253 public void closeViewer(boolean closeChimera)
255 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
258 viewer.exitChimera();
260 if (this.chimeraListener != null)
262 chimeraListener.shutdown();
263 chimeraListener = null;
267 if (chimeraMonitor != null)
269 chimeraMonitor.interrupt();
271 releaseUIResources();
275 public void colourByChain()
277 colourBySequence = false;
278 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
282 * Constructs and sends a Chimera command to colour by charge
284 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
285 * <li>Lysine and Arginine (positive charge) blue</li>
286 * <li>Cysteine - yellow</li>
287 * <li>all others - white</li>
291 public void colourByCharge()
293 colourBySequence = false;
294 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
295 sendAsynchronousCommand(command, COLOURING_CHIMERA);
302 public String superposeStructures(AlignmentI[] _alignment,
303 int[] _refStructure, HiddenColumns[] _hiddenCols)
305 StringBuilder allComs = new StringBuilder(128);
306 String[] files = getStructureFiles();
308 if (!waitForFileLoad(files))
314 StringBuilder selectioncom = new StringBuilder(256);
315 for (int a = 0; a < _alignment.length; a++)
317 int refStructure = _refStructure[a];
318 AlignmentI alignment = _alignment[a];
319 HiddenColumns hiddenCols = _hiddenCols[a];
321 if (refStructure >= files.length)
323 System.err.println("Ignoring invalid reference structure value "
329 * 'matched' bit i will be set for visible alignment columns i where
330 * all sequences have a residue with a mapping to the PDB structure
332 BitSet matched = new BitSet();
333 for (int m = 0; m < alignment.getWidth(); m++)
335 if (hiddenCols == null || hiddenCols.isVisible(m))
341 SuperposeData[] structures = new SuperposeData[files.length];
342 for (int f = 0; f < files.length; f++)
344 structures[f] = new SuperposeData(alignment.getWidth());
348 * Calculate the superposable alignment columns ('matched'), and the
349 * corresponding structure residue positions (structures.pdbResNo)
351 int candidateRefStructure = findSuperposableResidues(alignment,
352 matched, structures);
353 if (refStructure < 0)
356 * If no reference structure was specified, pick the first one that has
357 * a mapping in the alignment
359 refStructure = candidateRefStructure;
362 int nmatched = matched.cardinality();
365 return MessageManager.formatMessage("label.insufficient_residues",
370 * Generate select statements to select regions to superimpose structures
372 String[] selcom = new String[files.length];
373 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
375 String chainCd = "." + structures[pdbfnum].chain;
378 StringBuilder molsel = new StringBuilder();
380 int nextColumnMatch = matched.nextSetBit(0);
381 while (nextColumnMatch != -1)
383 int pdbResNum = structures[pdbfnum].pdbResNo[nextColumnMatch];
384 if (lpos != pdbResNum - 1)
387 * discontiguous - append last residue now
391 molsel.append(String.valueOf(lpos));
392 molsel.append(chainCd);
400 * extending a contiguous run
405 * start the range selection
407 molsel.append(String.valueOf(lpos));
413 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
417 * and terminate final selection
421 molsel.append(String.valueOf(lpos));
422 molsel.append(chainCd);
424 if (molsel.length() > 1)
426 selcom[pdbfnum] = molsel.toString();
427 selectioncom.append("#").append(String.valueOf(pdbfnum))
429 selectioncom.append(selcom[pdbfnum]);
430 selectioncom.append(" ");
431 if (pdbfnum < files.length - 1)
433 selectioncom.append("| ");
438 selcom[pdbfnum] = null;
442 StringBuilder command = new StringBuilder(256);
443 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
445 if (pdbfnum == refStructure || selcom[pdbfnum] == null
446 || selcom[refStructure] == null)
450 if (command.length() > 0)
456 * Form Chimera match command, from the 'new' structure to the
457 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
459 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
462 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
464 command.append("match ").append(getModelSpec(pdbfnum))
466 command.append(selcom[pdbfnum]);
467 command.append("@").append(
468 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
469 // JAL-1757 exclude alternate CA locations
470 command.append(NO_ALTLOCS);
471 command.append(" ").append(getModelSpec(refStructure)).append(":");
472 command.append(selcom[refStructure]);
473 command.append("@").append(
474 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
475 command.append(NO_ALTLOCS);
477 if (selectioncom.length() > 0)
481 System.out.println("Select regions:\n" + selectioncom.toString());
483 "Superimpose command(s):\n" + command.toString());
485 allComs/*.append("~display all; chain @CA|P; ribbon ")
486 .append(selectioncom.toString())*/
487 .append(";" + command.toString());
492 if (selectioncom.length() > 0)
494 // TODO: visually distinguish regions that were superposed
495 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
497 selectioncom.setLength(selectioncom.length() - 1);
501 System.out.println("Select regions:\n" + selectioncom.toString());
503 allComs.append("; ~display "); // all");
504 if (!isShowAlignmentOnly())
506 allComs.append("; ribbon; chain @CA|P");
510 allComs.append("; ~ribbon");
512 allComs.append("; ribbon ").append(selectioncom.toString())
514 List<String> chimeraReplies = sendChimeraCommand(allComs.toString(),
516 for (String reply : chimeraReplies)
518 String lowerCase = reply.toLowerCase();
519 if (lowerCase.contains("unequal numbers of atoms")
520 || lowerCase.contains("at least"))
530 * Helper method to construct model spec in Chimera format:
532 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
533 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
535 * Note for now we only ever choose the first of multiple models. This
536 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
537 * future if there is a need to select specific sub-models.
543 public String getModelSpec(int pdbfnum)
545 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
551 * For now, the test for having sub-models is whether multiple Chimera
552 * models are mapped for the PDB file; the models are returned as a response
553 * to the Chimera command 'list models type molecule', see
554 * ChimeraManager.getModelList().
556 List<ChimeraModel> maps = chimeraMaps.get(getStructureFiles()[pdbfnum]);
557 boolean hasSubModels = maps != null && maps.size() > 1;
558 String spec = "#" + String.valueOf(pdbfnum);
559 return hasSubModels ? spec + ".1" : spec;
563 * Launch Chimera, unless an instance linked to this object is already
564 * running. Returns true if Chimera is successfully launched, or already
565 * running, else false.
569 public boolean launchChimera()
571 if (viewer.isChimeraLaunched())
576 boolean launched = viewer
577 .launchChimera(StructureManager.getChimeraPaths());
580 startChimeraProcessMonitor();
584 log("Failed to launch Chimera!");
590 * Answers true if the Chimera process is still running, false if ended or not
595 public boolean isChimeraRunning()
597 return viewer.isChimeraLaunched();
601 * Send a command to Chimera, and optionally log and return any responses.
603 * Does nothing, and returns null, if the command is the same as the last one
609 public List<String> sendChimeraCommand(final String command,
614 // ? thread running after viewer shut down
617 List<String> reply = null;
618 viewerCommandHistory(false);
619 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
621 // trim command or it may never find a match in the replyLog!!
622 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
629 log("Response from command ('" + command + "') was:\n"
634 viewerCommandHistory(true);
640 * Send a Chimera command asynchronously in a new thread. If the progress
641 * message is not null, display this message while the command is executing.
646 protected abstract void sendAsynchronousCommand(String command,
650 * Constructs a set of colour commands and sends them to the structure viewer
655 protected void colourBySequence(AlignmentViewPanel viewPanel)
657 Map<Object, AtomSpecModel> colourMap = StructureCommands
658 .buildColoursMap(this, viewPanel);
660 String[] commands = ChimeraCommands
661 .getColourBySequenceCommand(colourMap, this);
663 for (String command : commands)
665 sendAsynchronousCommand(command, COLOURING_CHIMERA);
672 protected void executeWhenReady(String command)
675 sendChimeraCommand(command, false);
679 private void waitForChimera()
681 while (viewer != null && viewer.isBusy())
686 } catch (InterruptedException q)
692 // End StructureListener
693 // //////////////////////////
696 * instruct the Jalview binding to update the pdbentries vector if necessary
697 * prior to matching the viewer's contents to the list of structure files
698 * Jalview knows about.
700 public abstract void refreshPdbEntries();
703 * map between index of model filename returned from getPdbFile and the first
704 * index of models from this file in the viewer. Note - this is not trimmed -
705 * use getPdbFile to get number of unique models.
707 private int _modelFileNameMap[];
709 // ////////////////////////////////
710 // /StructureListener
712 public synchronized String[] getStructureFiles()
716 return new String[0];
719 return chimeraMaps.keySet()
720 .toArray(modelFileNames = new String[chimeraMaps.size()]);
724 * Construct and send a command to highlight zero, one or more atoms. We do
725 * this by sending an "rlabel" command to show the residue label at that
729 public void highlightAtoms(List<AtomSpec> atoms)
731 if (atoms == null || atoms.size() == 0)
736 StringBuilder cmd = new StringBuilder(128);
737 boolean first = true;
738 boolean found = false;
740 for (AtomSpec atom : atoms)
742 int pdbResNum = atom.getPdbResNum();
743 String chain = atom.getChain();
744 String pdbfile = atom.getPdbFile();
745 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
746 if (cms != null && !cms.isEmpty())
750 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
758 cmd.append(pdbResNum);
759 if (!chain.equals(" "))
761 cmd.append(".").append(chain);
766 String command = cmd.toString();
769 * avoid repeated commands for the same residue
771 if (command.equals(lastHighlightCommand))
777 * unshow the label for the previous residue
779 if (lastHighlightCommand != null)
781 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
785 viewer.sendChimeraCommand(command, false);
787 this.lastHighlightCommand = command;
791 * Query Chimera for its current selection, and highlight it on the alignment
793 public void highlightChimeraSelection()
796 * Ask Chimera for its current selection
798 List<String> selection = viewer.getSelectedResidueSpecs();
801 * Parse model number, residue and chain for each selected position,
802 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
804 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
808 * Broadcast the selection (which may be empty, if the user just cleared all
811 getSsm().mouseOverStructure(atomSpecs);
815 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
816 * corresponding residues (if any) in Jalview
818 * @param structureSelection
821 protected List<AtomSpec> convertStructureResiduesToAlignment(
822 List<String> structureSelection)
824 List<AtomSpec> atomSpecs = new ArrayList<>();
825 for (String atomSpec : structureSelection)
829 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
830 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
831 spec.setPdbFile(pdbfilename);
833 } catch (IllegalArgumentException e)
835 System.err.println("Failed to parse atomspec: " + atomSpec);
845 protected String getPdbFileForModel(int modelId)
848 * Work out the pdbfilename from the model number
850 String pdbfilename = modelFileNames[0];
851 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
853 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
855 if (cm.getModelNumber() == modelId)
857 pdbfilename = pdbfile;
865 private void log(String message)
867 System.err.println("## Chimera log: " + message);
870 private void viewerCommandHistory(boolean enable)
872 // log("(Not yet implemented) History "
873 // + ((debug || enable) ? "on" : "off"));
876 public long getLoadNotifiesHandled()
878 return loadNotifiesHandled;
882 public void setJalviewColourScheme(ColourSchemeI cs)
884 colourBySequence = false;
891 // Chimera expects RGB values in the range 0-1
892 final double normalise = 255D;
893 viewerCommandHistory(false);
894 StringBuilder command = new StringBuilder(128);
896 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
898 for (String resName : residueSet)
900 char res = resName.length() == 3
901 ? ResidueProperties.getSingleCharacterCode(resName)
903 Color col = cs.findColour(res, 0, null, null, 0f);
904 command.append("color ")
905 .append(String.valueOf(col.getRed() / normalise)).append(",")
906 .append(String.valueOf(col.getGreen() / normalise))
907 .append(",").append(String.valueOf(col.getBlue() / normalise))
908 .append(" ::").append(resName).append(";");
911 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
912 viewerCommandHistory(true);
916 * called when the binding thinks the UI needs to be refreshed after a Chimera
917 * state change. this could be because structures were loaded, or because an
918 * error has occurred.
920 public abstract void refreshGUI();
923 public void setLoadingFromArchive(boolean loadingFromArchive)
925 this.loadingFromArchive = loadingFromArchive;
930 * @return true if Chimeral is still restoring state or loading is still going
931 * on (see setFinsihedLoadingFromArchive)
934 public boolean isLoadingFromArchive()
936 return loadingFromArchive && !loadingFinished;
940 * modify flag which controls if sequence colouring events are honoured by the
941 * binding. Should be true for normal operation
943 * @param finishedLoading
946 public void setFinishedLoadingFromArchive(boolean finishedLoading)
948 loadingFinished = finishedLoading;
952 * Send the Chimera 'background solid <color>" command.
955 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
960 public void setBackgroundColour(Color col)
962 viewerCommandHistory(false);
963 double normalise = 255D;
964 final String command = "background solid " + col.getRed() / normalise
965 + "," + col.getGreen() / normalise + ","
966 + col.getBlue() / normalise + ";";
967 viewer.sendChimeraCommand(command, false);
968 viewerCommandHistory(true);
972 * Ask Chimera to save its session to the given file. Returns true if
973 * successful, else false.
978 public boolean saveSession(String filepath)
980 if (isChimeraRunning())
982 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
984 if (reply.contains("Session written"))
991 .error("Error saving Chimera session: " + reply.toString());
998 * Ask Chimera to open a session file. Returns true if successful, else false.
999 * The filename must have a .py extension for this command to work.
1004 public boolean openSession(String filepath)
1006 sendChimeraCommand("open " + filepath, true);
1007 // todo: test for failure - how?
1012 * Send a 'focus' command to Chimera to recentre the visible display
1015 public void focusView()
1017 sendChimeraCommand("focus", false);
1021 * Send a 'show' command for all atoms in the currently selected columns
1023 * TODO: pull up to abstract structure viewer interface
1027 public void highlightSelection(AlignmentViewPanel vp)
1029 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1031 AlignmentI alignment = vp.getAlignment();
1032 StructureSelectionManager sm = getSsm();
1033 for (SequenceI seq : alignment.getSequences())
1036 * convert selected columns into sequence positions
1038 int[] positions = new int[cols.size()];
1040 for (Integer col : cols)
1042 positions[i++] = seq.findPosition(col);
1044 sm.highlightStructure(this, seq, positions);
1049 * Constructs and send commands to Chimera to set attributes on residues for
1050 * features visible in Jalview
1055 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1057 // TODO refactor as required to pull up to an interface
1058 AlignmentI alignment = avp.getAlignment();
1060 String[] files = getStructureFiles();
1066 StructureMappingcommandSet commandSet = ChimeraCommands
1067 .getSetAttributeCommandsForFeatures(avp, this);
1068 String[] commands = commandSet.commands;
1069 if (commands.length > 10)
1071 sendCommandsByFile(commands);
1075 for (String command : commands)
1077 sendAsynchronousCommand(command, null);
1080 return commands.length;
1084 * Write commands to a temporary file, and send a command to Chimera to open
1085 * the file as a commands script. For use when sending a large number of
1086 * separate commands would overload the REST interface mechanism.
1090 protected void sendCommandsByFile(String[] commands)
1094 File tmp = File.createTempFile("chim", ".com");
1096 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1097 for (String command : commands)
1099 out.println(command);
1103 String path = tmp.getAbsolutePath();
1104 sendAsynchronousCommand("open cmd:" + path, null);
1105 } catch (IOException e)
1107 System.err.println("Sending commands to Chimera via file failed with "
1113 * Get Chimera residues which have the named attribute, find the mapped
1114 * positions in the Jalview sequence(s), and set as sequence features
1117 * @param alignmentPanel
1119 public void copyStructureAttributesToFeatures(String attName,
1120 AlignmentViewPanel alignmentPanel)
1122 // todo pull up to AAStructureBindingModel (and interface?)
1125 * ask Chimera to list residues with the attribute, reporting its value
1127 // this alternative command
1128 // list residues spec ':*/attName' attr attName
1129 // doesn't report 'None' values (which is good), but
1130 // fails for 'average.bfactor' (which is bad):
1132 String cmd = "list residues attr '" + attName + "'";
1133 List<String> residues = sendChimeraCommand(cmd, true);
1135 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1138 alignmentPanel.getFeatureRenderer().featuresAdded();
1143 * Create features in Jalview for the given attribute name and structure
1147 * The residue list should be 0, 1 or more reply lines of the format:
1148 * residue id #0:5.A isHelix -155.000836316 index 5
1150 * residue id #0:6.A isHelix None
1157 protected boolean createFeaturesForAttributes(String attName,
1158 List<String> residues)
1160 boolean featureAdded = false;
1161 String featureGroup = getViewerFeatureGroup();
1163 for (String residue : residues)
1165 AtomSpec spec = null;
1166 String[] tokens = residue.split(" ");
1167 if (tokens.length < 5)
1171 String atomSpec = tokens[2];
1172 String attValue = tokens[4];
1175 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1177 if ("None".equalsIgnoreCase(attValue)
1178 || "False".equalsIgnoreCase(attValue))
1185 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1186 } catch (IllegalArgumentException e)
1188 System.err.println("Problem parsing atomspec " + atomSpec);
1192 String chainId = spec.getChain();
1193 String description = attValue;
1194 float score = Float.NaN;
1197 score = Float.valueOf(attValue);
1198 description = chainId;
1199 } catch (NumberFormatException e)
1201 // was not a float value
1204 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1205 spec.setPdbFile(pdbFile);
1207 List<AtomSpec> atoms = Collections.singletonList(spec);
1210 * locate the mapped position in the alignment (if any)
1212 SearchResultsI sr = getSsm()
1213 .findAlignmentPositionsForStructurePositions(atoms);
1216 * expect one matched alignment position, or none
1217 * (if the structure position is not mapped)
1219 for (SearchResultMatchI m : sr.getResults())
1221 SequenceI seq = m.getSequence();
1222 int start = m.getStart();
1223 int end = m.getEnd();
1224 SequenceFeature sf = new SequenceFeature(attName, description,
1225 start, end, score, featureGroup);
1226 // todo: should SequenceFeature have an explicit property for chain?
1227 // note: repeating the action shouldn't duplicate features
1228 featureAdded |= seq.addSequenceFeature(sf);
1231 return featureAdded;
1235 * Answers the feature group name to apply to features created in Jalview from
1236 * Chimera attributes
1240 protected String getViewerFeatureGroup()
1242 // todo pull up to interface
1243 return CHIMERA_FEATURE_GROUP;
1246 public Hashtable<String, String> getChainFile()
1251 public List<ChimeraModel> getChimeraModelByChain(String chain)
1253 return chimeraMaps.get(chainFile.get(chain));
1256 public int getModelNoForChain(String chain)
1258 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1259 if (foundModels != null && !foundModels.isEmpty())
1261 return foundModels.get(0).getModelNumber();
1267 public void showStructures(AlignViewportI av, boolean refocus)
1269 StringBuilder cmd = new StringBuilder(128);
1270 cmd.append("~display; ~ribbon;");
1272 AtomSpecModel model = getShownResidues(av);
1273 String atomSpec = ChimeraCommands.getAtomSpec(model, this);
1275 cmd.append("ribbon ").append(atomSpec);
1276 if (!isShowAlignmentOnly())
1278 cmd.append("; chain @CA|P");
1282 cmd.append("; focus");
1284 sendChimeraCommand(cmd.toString(), false);
1288 public int getModelForPdbFile(String fileName, int fileIndex)
1290 if (chimeraMaps.containsKey(fileName))
1292 List<ChimeraModel> models = chimeraMaps.get(fileName);
1293 if (!models.isEmpty())
1295 return models.get(0).getModelNumber();