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 * Sends a set of colour commands to the structure viewer
655 protected void colourBySequence(String[] commands)
657 for (String command : commands)
659 sendAsynchronousCommand(command, COLOURING_CHIMERA);
664 * Computes and returns a set of commands to colour residues in Chimera the same
665 * as mapped residues in the alignment
672 protected String[] getColourBySequenceCommands(
673 String[] files, AlignmentViewPanel viewPanel)
675 Map<Object, AtomSpecModel> colourMap = StructureCommands.buildColoursMap(this, viewPanel);
677 return ChimeraCommands.getColourBySequenceCommand(colourMap, this);
683 protected void executeWhenReady(String command)
686 sendChimeraCommand(command, false);
690 private void waitForChimera()
692 while (viewer != null && viewer.isBusy())
697 } catch (InterruptedException q)
703 // End StructureListener
704 // //////////////////////////
707 * instruct the Jalview binding to update the pdbentries vector if necessary
708 * prior to matching the viewer's contents to the list of structure files
709 * Jalview knows about.
711 public abstract void refreshPdbEntries();
714 * map between index of model filename returned from getPdbFile and the first
715 * index of models from this file in the viewer. Note - this is not trimmed -
716 * use getPdbFile to get number of unique models.
718 private int _modelFileNameMap[];
720 // ////////////////////////////////
721 // /StructureListener
723 public synchronized String[] getStructureFiles()
727 return new String[0];
730 return chimeraMaps.keySet()
731 .toArray(modelFileNames = new String[chimeraMaps.size()]);
735 * Construct and send a command to highlight zero, one or more atoms. We do
736 * this by sending an "rlabel" command to show the residue label at that
740 public void highlightAtoms(List<AtomSpec> atoms)
742 if (atoms == null || atoms.size() == 0)
747 StringBuilder cmd = new StringBuilder(128);
748 boolean first = true;
749 boolean found = false;
751 for (AtomSpec atom : atoms)
753 int pdbResNum = atom.getPdbResNum();
754 String chain = atom.getChain();
755 String pdbfile = atom.getPdbFile();
756 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
757 if (cms != null && !cms.isEmpty())
761 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
769 cmd.append(pdbResNum);
770 if (!chain.equals(" "))
772 cmd.append(".").append(chain);
777 String command = cmd.toString();
780 * avoid repeated commands for the same residue
782 if (command.equals(lastHighlightCommand))
788 * unshow the label for the previous residue
790 if (lastHighlightCommand != null)
792 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
796 viewer.sendChimeraCommand(command, false);
798 this.lastHighlightCommand = command;
802 * Query Chimera for its current selection, and highlight it on the alignment
804 public void highlightChimeraSelection()
807 * Ask Chimera for its current selection
809 List<String> selection = viewer.getSelectedResidueSpecs();
812 * Parse model number, residue and chain for each selected position,
813 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
815 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(
819 * Broadcast the selection (which may be empty, if the user just cleared all
822 getSsm().mouseOverStructure(atomSpecs);
826 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
827 * corresponding residues (if any) in Jalview
829 * @param structureSelection
832 protected List<AtomSpec> convertStructureResiduesToAlignment(
833 List<String> structureSelection)
835 List<AtomSpec> atomSpecs = new ArrayList<>();
836 for (String atomSpec : structureSelection)
840 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
841 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
842 spec.setPdbFile(pdbfilename);
844 } catch (IllegalArgumentException e)
846 System.err.println("Failed to parse atomspec: " + atomSpec);
856 protected String getPdbFileForModel(int modelId)
859 * Work out the pdbfilename from the model number
861 String pdbfilename = modelFileNames[0];
862 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
864 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
866 if (cm.getModelNumber() == modelId)
868 pdbfilename = pdbfile;
876 private void log(String message)
878 System.err.println("## Chimera log: " + message);
881 private void viewerCommandHistory(boolean enable)
883 // log("(Not yet implemented) History "
884 // + ((debug || enable) ? "on" : "off"));
887 public long getLoadNotifiesHandled()
889 return loadNotifiesHandled;
893 public void setJalviewColourScheme(ColourSchemeI cs)
895 colourBySequence = false;
902 // Chimera expects RGB values in the range 0-1
903 final double normalise = 255D;
904 viewerCommandHistory(false);
905 StringBuilder command = new StringBuilder(128);
907 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
909 for (String resName : residueSet)
911 char res = resName.length() == 3
912 ? ResidueProperties.getSingleCharacterCode(resName)
914 Color col = cs.findColour(res, 0, null, null, 0f);
915 command.append("color ")
916 .append(String.valueOf(col.getRed() / normalise)).append(",")
917 .append(String.valueOf(col.getGreen() / normalise))
918 .append(",").append(String.valueOf(col.getBlue() / normalise))
919 .append(" ::").append(resName).append(";");
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 * Send a 'focus' command to Chimera to recentre the visible display
1025 public void focusView()
1027 sendChimeraCommand("focus", false);
1031 * Send a 'show' command for all atoms in the currently selected columns
1033 * TODO: pull up to abstract structure viewer interface
1037 public void highlightSelection(AlignmentViewPanel vp)
1039 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1041 AlignmentI alignment = vp.getAlignment();
1042 StructureSelectionManager sm = getSsm();
1043 for (SequenceI seq : alignment.getSequences())
1046 * convert selected columns into sequence positions
1048 int[] positions = new int[cols.size()];
1050 for (Integer col : cols)
1052 positions[i++] = seq.findPosition(col);
1054 sm.highlightStructure(this, seq, positions);
1059 * Constructs and send commands to Chimera to set attributes on residues for
1060 * features visible in Jalview
1065 public int sendFeaturesToViewer(AlignmentViewPanel avp)
1067 // TODO refactor as required to pull up to an interface
1068 AlignmentI alignment = avp.getAlignment();
1070 String[] files = getStructureFiles();
1076 StructureMappingcommandSet commandSet = ChimeraCommands
1077 .getSetAttributeCommandsForFeatures(avp, this);
1078 String[] commands = commandSet.commands;
1079 if (commands.length > 10)
1081 sendCommandsByFile(commands);
1085 for (String command : commands)
1087 sendAsynchronousCommand(command, null);
1090 return commands.length;
1094 * Write commands to a temporary file, and send a command to Chimera to open
1095 * the file as a commands script. For use when sending a large number of
1096 * separate commands would overload the REST interface mechanism.
1100 protected void sendCommandsByFile(String[] commands)
1104 File tmp = File.createTempFile("chim", ".com");
1106 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1107 for (String command : commands)
1109 out.println(command);
1113 String path = tmp.getAbsolutePath();
1114 sendAsynchronousCommand("open cmd:" + path, null);
1115 } catch (IOException e)
1117 System.err.println("Sending commands to Chimera via file failed with "
1123 * Get Chimera residues which have the named attribute, find the mapped
1124 * positions in the Jalview sequence(s), and set as sequence features
1127 * @param alignmentPanel
1129 public void copyStructureAttributesToFeatures(String attName,
1130 AlignmentViewPanel alignmentPanel)
1132 // todo pull up to AAStructureBindingModel (and interface?)
1135 * ask Chimera to list residues with the attribute, reporting its value
1137 // this alternative command
1138 // list residues spec ':*/attName' attr attName
1139 // doesn't report 'None' values (which is good), but
1140 // fails for 'average.bfactor' (which is bad):
1142 String cmd = "list residues attr '" + attName + "'";
1143 List<String> residues = sendChimeraCommand(cmd, true);
1145 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1148 alignmentPanel.getFeatureRenderer().featuresAdded();
1153 * Create features in Jalview for the given attribute name and structure
1157 * The residue list should be 0, 1 or more reply lines of the format:
1158 * residue id #0:5.A isHelix -155.000836316 index 5
1160 * residue id #0:6.A isHelix None
1167 protected boolean createFeaturesForAttributes(String attName,
1168 List<String> residues)
1170 boolean featureAdded = false;
1171 String featureGroup = getViewerFeatureGroup();
1173 for (String residue : residues)
1175 AtomSpec spec = null;
1176 String[] tokens = residue.split(" ");
1177 if (tokens.length < 5)
1181 String atomSpec = tokens[2];
1182 String attValue = tokens[4];
1185 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1187 if ("None".equalsIgnoreCase(attValue)
1188 || "False".equalsIgnoreCase(attValue))
1195 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1196 } catch (IllegalArgumentException e)
1198 System.err.println("Problem parsing atomspec " + atomSpec);
1202 String chainId = spec.getChain();
1203 String description = attValue;
1204 float score = Float.NaN;
1207 score = Float.valueOf(attValue);
1208 description = chainId;
1209 } catch (NumberFormatException e)
1211 // was not a float value
1214 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1215 spec.setPdbFile(pdbFile);
1217 List<AtomSpec> atoms = Collections.singletonList(spec);
1220 * locate the mapped position in the alignment (if any)
1222 SearchResultsI sr = getSsm()
1223 .findAlignmentPositionsForStructurePositions(atoms);
1226 * expect one matched alignment position, or none
1227 * (if the structure position is not mapped)
1229 for (SearchResultMatchI m : sr.getResults())
1231 SequenceI seq = m.getSequence();
1232 int start = m.getStart();
1233 int end = m.getEnd();
1234 SequenceFeature sf = new SequenceFeature(attName, description,
1235 start, end, score, featureGroup);
1236 // todo: should SequenceFeature have an explicit property for chain?
1237 // note: repeating the action shouldn't duplicate features
1238 featureAdded |= seq.addSequenceFeature(sf);
1241 return featureAdded;
1245 * Answers the feature group name to apply to features created in Jalview from
1246 * Chimera attributes
1250 protected String getViewerFeatureGroup()
1252 // todo pull up to interface
1253 return CHIMERA_FEATURE_GROUP;
1256 public Hashtable<String, String> getChainFile()
1261 public List<ChimeraModel> getChimeraModelByChain(String chain)
1263 return chimeraMaps.get(chainFile.get(chain));
1266 public int getModelNoForChain(String chain)
1268 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1269 if (foundModels != null && !foundModels.isEmpty())
1271 return foundModels.get(0).getModelNumber();
1277 public void showStructures(AlignViewportI av, boolean refocus)
1279 StringBuilder cmd = new StringBuilder(128);
1280 cmd.append("~display; ~ribbon;");
1282 AtomSpecModel model = getShownResidues(av);
1283 String atomSpec = ChimeraCommands.getAtomSpec(model, this);
1285 cmd.append("ribbon ").append(atomSpec);
1286 if (!isShowAlignmentOnly())
1288 cmd.append("chain @CA|P; ribbon");
1292 cmd.append("; focus");
1294 sendChimeraCommand(cmd.toString(), false);