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.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
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.ColumnSelection;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SearchResultMatchI;
32 import jalview.datamodel.SearchResults;
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.StructureMappingcommandSet;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.structures.models.AAStructureBindingModel;
43 import jalview.util.MessageManager;
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.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<String>();
81 private Hashtable<String, String> chainFile = new Hashtable<String, String>();
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;
106 public String fileLoadingError;
109 * Map of ChimeraModel objects keyed by PDB full local file name
111 private Map<String, List<ChimeraModel>> chimeraMaps = new LinkedHashMap<String, List<ChimeraModel>>();
113 String lastHighlightCommand;
116 * incremented every time a load notification is successfully handled -
117 * lightweight mechanism for other threads to detect when they can start
118 * referring to new structures.
120 private long loadNotifiesHandled = 0;
122 private Thread chimeraMonitor;
125 * Open a PDB structure file in Chimera and set up mappings from Jalview.
127 * We check if the PDB model id is already loaded in Chimera, if so don't
128 * reopen it. This is the case if Chimera has opened a saved session file.
133 public boolean openFile(PDBEntry pe)
135 String file = pe.getFile();
138 List<ChimeraModel> modelsToMap = new ArrayList<ChimeraModel>();
139 List<ChimeraModel> oldList = viewer.getModelList();
140 boolean alreadyOpen = false;
143 * If Chimera already has this model, don't reopen it, but do remap it.
145 for (ChimeraModel open : oldList)
147 if (open.getModelName().equals(pe.getId()))
150 modelsToMap.add(open);
155 * If Chimera doesn't yet have this model, ask it to open it, and retrieve
156 * the model name(s) added by Chimera.
160 viewer.openModel(file, pe.getId(), ModelType.PDB_MODEL);
161 List<ChimeraModel> newList = viewer.getModelList();
162 // JAL-1728 newList.removeAll(oldList) does not work
163 for (ChimeraModel cm : newList)
165 if (cm.getModelName().equals(pe.getId()))
172 chimeraMaps.put(file, modelsToMap);
174 if (getSsm() != null)
176 getSsm().addStructureViewerListener(this);
177 // ssm.addSelectionListener(this);
178 FeatureRenderer fr = getFeatureRenderer(null);
186 } catch (Exception q)
188 log("Exception when trying to open model " + file + "\n"
203 public JalviewChimeraBinding(StructureSelectionManager ssm,
204 PDBEntry[] pdbentry, SequenceI[][] sequenceIs, DataSourceType protocol)
206 super(ssm, pdbentry, sequenceIs, protocol);
207 viewer = new ChimeraManager(new StructureManager(true));
211 * Starts a thread that waits for the Chimera process to finish, so that we
212 * can then close the associated resources. This avoids leaving orphaned
213 * Chimera viewer panels in Jalview if the user closes Chimera.
215 protected void startChimeraProcessMonitor()
217 final Process p = viewer.getChimeraProcess();
218 chimeraMonitor = new Thread(new Runnable()
227 JalviewStructureDisplayI display = getViewer();
230 display.closeViewer(false);
232 } catch (InterruptedException e)
234 // exit thread if Chimera Viewer is closed in Jalview
238 chimeraMonitor.start();
242 * Start a dedicated HttpServer to listen for Chimera notifications, and tell
243 * it to start listening
245 public void startChimeraListener()
249 chimeraListener = new ChimeraListener(this);
250 viewer.startListening(chimeraListener.getUri());
251 } catch (BindException e)
253 System.err.println("Failed to start Chimera listener: "
259 * Construct a title string for the viewer window based on the data Jalview
265 public String getViewerTitle(boolean verbose)
267 return getViewerTitle("Chimera", verbose);
271 * Tells Chimera to display only the specified chains
275 public void showChains(List<String> toshow)
278 * Construct a chimera command like
280 * ~display #*;~ribbon #*;ribbon :.A,:.B
282 StringBuilder cmd = new StringBuilder(64);
283 boolean first = true;
284 for (String chain : toshow)
286 int modelNumber = getModelNoForChain(chain);
287 String showChainCmd = modelNumber == -1 ? "" : modelNumber + ":."
288 + chain.split(":")[1];
293 cmd.append(showChainCmd);
298 * could append ";focus" to this command to resize the display to fill the
299 * window, but it looks more helpful not to (easier to relate chains to the
302 final String command = "~display #*; ~ribbon #*; ribbon :"
304 sendChimeraCommand(command, false);
308 * Close down the Jalview viewer and listener, and (optionally) the associated
311 public void closeViewer(boolean closeChimera)
313 getSsm().removeStructureViewerListener(this, this.getPdbFile());
316 viewer.exitChimera();
318 if (this.chimeraListener != null)
320 chimeraListener.shutdown();
321 chimeraListener = null;
325 if (chimeraMonitor != null)
327 chimeraMonitor.interrupt();
329 releaseUIResources();
332 public void colourByChain()
334 colourBySequence = false;
335 sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
339 * Constructs and sends a Chimera command to colour by charge
341 * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
342 * <li>Lysine and Arginine (positive charge) blue</li>
343 * <li>Cysteine - yellow</li>
344 * <li>all others - white</li>
347 public void colourByCharge()
349 colourBySequence = false;
350 String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
351 sendAsynchronousCommand(command, COLOURING_CHIMERA);
355 * Construct and send a command to align structures against a reference
356 * structure, based on one or more sequence alignments
359 * an array of alignments to process
360 * @param _refStructure
361 * an array of corresponding reference structures (index into pdb
362 * file array); if a negative value is passed, the first PDB file
363 * mapped to an alignment sequence is used as the reference for
366 * an array of corresponding hidden columns for each alignment
368 public void superposeStructures(AlignmentI[] _alignment,
369 int[] _refStructure, ColumnSelection[] _hiddenCols)
371 StringBuilder allComs = new StringBuilder(128);
372 String[] files = getPdbFile();
374 if (!waitForFileLoad(files))
380 StringBuilder selectioncom = new StringBuilder(256);
381 for (int a = 0; a < _alignment.length; a++)
383 int refStructure = _refStructure[a];
384 AlignmentI alignment = _alignment[a];
385 ColumnSelection hiddenCols = _hiddenCols[a];
387 if (refStructure >= files.length)
389 System.err.println("Ignoring invalid reference structure value "
395 * 'matched' array will hold 'true' for visible alignment columns where
396 * all sequences have a residue with a mapping to the PDB structure
398 boolean matched[] = new boolean[alignment.getWidth()];
399 for (int m = 0; m < matched.length; m++)
401 matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
404 SuperposeData[] structures = new SuperposeData[files.length];
405 for (int f = 0; f < files.length; f++)
407 structures[f] = new SuperposeData(alignment.getWidth());
411 * Calculate the superposable alignment columns ('matched'), and the
412 * corresponding structure residue positions (structures.pdbResNo)
414 int candidateRefStructure = findSuperposableResidues(alignment,
415 matched, structures);
416 if (refStructure < 0)
419 * If no reference structure was specified, pick the first one that has
420 * a mapping in the alignment
422 refStructure = candidateRefStructure;
426 for (boolean b : matched)
435 // TODO: bail out here because superposition illdefined?
439 * Generate select statements to select regions to superimpose structures
441 String[] selcom = new String[files.length];
442 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
444 String chainCd = "." + structures[pdbfnum].chain;
447 StringBuilder molsel = new StringBuilder();
448 for (int r = 0; r < matched.length; r++)
452 int pdbResNum = structures[pdbfnum].pdbResNo[r];
453 if (lpos != pdbResNum - 1)
456 * discontiguous - append last residue now
460 molsel.append(String.valueOf(lpos));
461 molsel.append(chainCd);
469 * extending a contiguous run
474 * start the range selection
476 molsel.append(String.valueOf(lpos));
486 * and terminate final selection
490 molsel.append(String.valueOf(lpos));
491 molsel.append(chainCd);
493 if (molsel.length() > 1)
495 selcom[pdbfnum] = molsel.toString();
496 selectioncom.append("#").append(String.valueOf(pdbfnum))
498 selectioncom.append(selcom[pdbfnum]);
499 selectioncom.append(" ");
500 if (pdbfnum < files.length - 1)
502 selectioncom.append("| ");
507 selcom[pdbfnum] = null;
511 StringBuilder command = new StringBuilder(256);
512 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
514 if (pdbfnum == refStructure || selcom[pdbfnum] == null
515 || selcom[refStructure] == null)
519 if (command.length() > 0)
525 * Form Chimera match command, from the 'new' structure to the
526 * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
528 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
531 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
533 command.append("match ").append(getModelSpec(pdbfnum)).append(":");
534 command.append(selcom[pdbfnum]);
535 command.append("@").append(
536 structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
537 // JAL-1757 exclude alternate CA locations
538 command.append(NO_ALTLOCS);
539 command.append(" ").append(getModelSpec(refStructure)).append(":");
540 command.append(selcom[refStructure]);
541 command.append("@").append(
542 structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
543 command.append(NO_ALTLOCS);
545 if (selectioncom.length() > 0)
549 System.out.println("Select regions:\n" + selectioncom.toString());
550 System.out.println("Superimpose command(s):\n"
551 + command.toString());
553 allComs.append("~display all; chain @CA|P; ribbon ")
554 .append(selectioncom.toString())
555 .append(";" + command.toString());
558 if (selectioncom.length() > 0)
560 // TODO: visually distinguish regions that were superposed
561 if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
563 selectioncom.setLength(selectioncom.length() - 1);
567 System.out.println("Select regions:\n" + selectioncom.toString());
569 allComs.append("; ~display all; chain @CA|P; ribbon ")
570 .append(selectioncom.toString()).append("; focus");
571 sendChimeraCommand(allComs.toString(), false);
577 * Helper method to construct model spec in Chimera format:
579 * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
580 * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
582 * Note for now we only ever choose the first of multiple models. This
583 * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
584 * future if there is a need to select specific sub-models.
589 protected String getModelSpec(int pdbfnum)
591 if (pdbfnum < 0 || pdbfnum >= getPdbCount())
597 * For now, the test for having sub-models is whether multiple Chimera
598 * models are mapped for the PDB file; the models are returned as a response
599 * to the Chimera command 'list models type molecule', see
600 * ChimeraManager.getModelList().
602 List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
603 boolean hasSubModels = maps != null && maps.size() > 1;
604 return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
608 * Launch Chimera, unless an instance linked to this object is already
609 * running. Returns true if Chimera is successfully launched, or already
610 * running, else false.
614 public boolean launchChimera()
616 if (viewer.isChimeraLaunched())
621 boolean launched = viewer.launchChimera(StructureManager
625 startChimeraProcessMonitor();
629 log("Failed to launch Chimera!");
635 * Answers true if the Chimera process is still running, false if ended or not
640 public boolean isChimeraRunning()
642 return viewer.isChimeraLaunched();
646 * Send a command to Chimera, and optionally log and return any responses.
648 * Does nothing, and returns null, if the command is the same as the last one
654 public List<String> sendChimeraCommand(final String command,
659 // ? thread running after viewer shut down
662 List<String> reply = null;
663 viewerCommandHistory(false);
664 if (true /*lastCommand == null || !lastCommand.equals(command)*/)
666 // trim command or it may never find a match in the replyLog!!
667 List<String> lastReply = viewer.sendChimeraCommand(command.trim(),
674 log("Response from command ('" + command + "') was:\n"
679 viewerCommandHistory(true);
685 * Send a Chimera command asynchronously in a new thread. If the progress
686 * message is not null, display this message while the command is executing.
691 protected abstract void sendAsynchronousCommand(String command,
695 * colour any structures associated with sequences in the given alignment
696 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
697 * if colourBySequence is enabled.
699 public void colourBySequence(boolean showFeatures,
700 jalview.api.AlignmentViewPanel alignmentv)
702 if (!colourBySequence || !loadingFinished)
706 if (getSsm() == null)
710 String[] files = getPdbFile();
712 SequenceRenderer sr = getSequenceRenderer(alignmentv);
714 FeatureRenderer fr = null;
717 fr = getFeatureRenderer(alignmentv);
719 AlignmentI alignment = alignmentv.getAlignment();
721 StructureMappingcommandSet colourBySequenceCommands = ChimeraCommands
722 .getColourBySequenceCommand(getSsm(), files, getSequence(), sr,
724 for (String command : colourBySequenceCommands.commands)
726 sendAsynchronousCommand(command, COLOURING_CHIMERA);
733 protected void executeWhenReady(String command)
736 sendChimeraCommand(command, false);
740 private void waitForChimera()
742 while (viewer != null && viewer.isBusy())
747 } catch (InterruptedException q)
753 // End StructureListener
754 // //////////////////////////
757 * returns the current featureRenderer that should be used to colour the
764 public abstract FeatureRenderer getFeatureRenderer(
765 AlignmentViewPanel alignment);
768 * instruct the Jalview binding to update the pdbentries vector if necessary
769 * prior to matching the viewer's contents to the list of structure files
770 * Jalview knows about.
772 public abstract void refreshPdbEntries();
774 // ////////////////////////////////
775 // /StructureListener
777 public synchronized String[] getPdbFile()
781 return new String[0];
784 return chimeraMaps.keySet().toArray(
785 modelFileNames = new String[chimeraMaps.size()]);
789 * returns the current sequenceRenderer that should be used to colour the
796 public abstract SequenceRenderer getSequenceRenderer(
797 AlignmentViewPanel alignment);
800 * Construct and send a command to highlight zero, one or more atoms. We do
801 * this by sending an "rlabel" command to show the residue label at that
805 public void highlightAtoms(List<AtomSpec> atoms)
807 if (atoms == null || atoms.size() == 0)
812 StringBuilder cmd = new StringBuilder(128);
813 boolean first = true;
814 boolean found = false;
816 for (AtomSpec atom : atoms)
818 int pdbResNum = atom.getPdbResNum();
819 String chain = atom.getChain();
820 String pdbfile = atom.getPdbFile();
821 List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
822 if (cms != null && !cms.isEmpty())
826 cmd.append("rlabel #").append(cms.get(0).getModelNumber())
834 cmd.append(pdbResNum);
835 if (!chain.equals(" "))
837 cmd.append(".").append(chain);
842 String command = cmd.toString();
845 * avoid repeated commands for the same residue
847 if (command.equals(lastHighlightCommand))
853 * unshow the label for the previous residue
855 if (lastHighlightCommand != null)
857 viewer.sendChimeraCommand("~" + lastHighlightCommand, false);
861 viewer.sendChimeraCommand(command, false);
863 this.lastHighlightCommand = command;
867 * Query Chimera for its current selection, and highlight it on the alignment
869 public void highlightChimeraSelection()
872 * Ask Chimera for its current selection
874 List<String> selection = viewer.getSelectedResidueSpecs();
877 * Parse model number, residue and chain for each selected position,
878 * formatted as #0:123.A or #1.2:87.B (#model.submodel:residue.chain)
880 List<AtomSpec> atomSpecs = convertStructureResiduesToAlignment(selection);
883 * Broadcast the selection (which may be empty, if the user just cleared all
886 getSsm().mouseOverStructure(atomSpecs);
890 * Converts a list of Chimera atomspecs to a list of AtomSpec representing the
891 * corresponding residues (if any) in Jalview
893 * @param structureSelection
896 protected List<AtomSpec> convertStructureResiduesToAlignment(
897 List<String> structureSelection)
899 List<AtomSpec> atomSpecs = new ArrayList<AtomSpec>();
900 for (String atomSpec : structureSelection)
904 AtomSpec spec = AtomSpec.fromChimeraAtomspec(atomSpec);
905 String pdbfilename = getPdbFileForModel(spec.getModelNumber());
906 spec.setPdbFile(pdbfilename);
908 } catch (IllegalArgumentException e)
910 System.err.println("Failed to parse atomspec: " + atomSpec);
920 protected String getPdbFileForModel(int modelId)
923 * Work out the pdbfilename from the model number
925 String pdbfilename = modelFileNames[0];
926 findfileloop: for (String pdbfile : this.chimeraMaps.keySet())
928 for (ChimeraModel cm : chimeraMaps.get(pdbfile))
930 if (cm.getModelNumber() == modelId)
932 pdbfilename = pdbfile;
940 private void log(String message)
942 System.err.println("## Chimera log: " + message);
945 private void viewerCommandHistory(boolean enable)
947 // log("(Not yet implemented) History "
948 // + ((debug || enable) ? "on" : "off"));
951 public long getLoadNotifiesHandled()
953 return loadNotifiesHandled;
956 public void setJalviewColourScheme(ColourSchemeI cs)
958 colourBySequence = false;
965 // Chimera expects RBG values in the range 0-1
966 final double normalise = 255D;
967 viewerCommandHistory(false);
968 StringBuilder command = new StringBuilder(128);
970 List<String> residueSet = ResidueProperties.getResidues(isNucleotide(),
972 for (String res : residueSet)
974 Color col = cs.findColour(res.charAt(0));
975 command.append("color " + col.getRed() / normalise + ","
976 + col.getGreen() / normalise + "," + col.getBlue()
977 / normalise + " ::" + res + ";");
980 sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
981 viewerCommandHistory(true);
985 * called when the binding thinks the UI needs to be refreshed after a Chimera
986 * state change. this could be because structures were loaded, or because an
987 * error has occurred.
989 public abstract void refreshGUI();
992 public void setLoadingFromArchive(boolean loadingFromArchive)
994 this.loadingFromArchive = loadingFromArchive;
999 * @return true if Chimeral is still restoring state or loading is still going
1000 * on (see setFinsihedLoadingFromArchive)
1003 public boolean isLoadingFromArchive()
1005 return loadingFromArchive && !loadingFinished;
1009 * modify flag which controls if sequence colouring events are honoured by the
1010 * binding. Should be true for normal operation
1012 * @param finishedLoading
1015 public void setFinishedLoadingFromArchive(boolean finishedLoading)
1017 loadingFinished = finishedLoading;
1021 * Send the Chimera 'background solid <color>" command.
1024 * ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
1028 public void setBackgroundColour(Color col)
1030 viewerCommandHistory(false);
1031 double normalise = 255D;
1032 final String command = "background solid " + col.getRed() / normalise
1033 + "," + col.getGreen() / normalise + "," + col.getBlue()
1035 viewer.sendChimeraCommand(command, false);
1036 viewerCommandHistory(true);
1040 * Ask Chimera to save its session to the given file. Returns true if
1041 * successful, else false.
1046 public boolean saveSession(String filepath)
1048 if (isChimeraRunning())
1050 List<String> reply = viewer.sendChimeraCommand("save " + filepath,
1052 if (reply.contains("Session written"))
1059 .error("Error saving Chimera session: " + reply.toString());
1066 * Ask Chimera to open a session file. Returns true if successful, else false.
1067 * The filename must have a .py extension for this command to work.
1072 public boolean openSession(String filepath)
1074 sendChimeraCommand("open " + filepath, true);
1075 // todo: test for failure - how?
1080 * Returns a list of chains mapped in this viewer. Note this list is not
1081 * currently scoped per structure.
1086 public List<String> getChainNames()
1092 * Send a 'focus' command to Chimera to recentre the visible display
1094 public void focusView()
1096 sendChimeraCommand("focus", false);
1100 * Send a 'show' command for all atoms in the currently selected columns
1102 * TODO: pull up to abstract structure viewer interface
1106 public void highlightSelection(AlignmentViewPanel vp)
1108 List<Integer> cols = vp.getAlignViewport().getColumnSelection()
1110 AlignmentI alignment = vp.getAlignment();
1111 StructureSelectionManager sm = getSsm();
1112 for (SequenceI seq : alignment.getSequences())
1115 * convert selected columns into sequence positions
1117 int[] positions = new int[cols.size()];
1119 for (Integer col : cols)
1121 positions[i++] = seq.findPosition(col);
1123 sm.highlightStructure(this, seq, positions);
1128 * Constructs and send commands to Chimera to set attributes on residues for
1129 * features visible in Jalview
1133 public void sendFeaturesToViewer(AlignmentViewPanel avp)
1135 // TODO refactor as required to pull up to an interface
1136 AlignmentI alignment = avp.getAlignment();
1137 FeatureRenderer fr = getFeatureRenderer(avp);
1140 * fr is null if feature display is turned off
1147 String[] files = getPdbFile();
1153 StructureMappingcommandSet commandSet = ChimeraCommands
1154 .getSetAttributeCommandsForFeatures(getSsm(), files,
1155 getSequence(), fr, alignment);
1156 String[] commands = commandSet.commands;
1157 if (commands.length > 10)
1159 sendCommandsByFile(commands);
1163 for (String command : commands)
1165 sendAsynchronousCommand(command, null);
1171 * Write commands to a temporary file, and send a command to Chimera to open
1172 * the file as a commands script. For use when sending a large number of
1173 * separate commands would overload the REST interface mechanism.
1177 protected void sendCommandsByFile(String[] commands)
1181 File tmp = File.createTempFile("chim", ".com");
1183 PrintWriter out = new PrintWriter(new FileOutputStream(tmp));
1184 for (String command : commands)
1186 out.println(command);
1190 String path = tmp.getAbsolutePath();
1191 sendAsynchronousCommand("open cmd:" + path, null);
1192 } catch (IOException e)
1195 .println("Sending commands to Chimera via file failed with "
1201 * Get Chimera residues which have the named attribute, find the mapped
1202 * positions in the Jalview sequence(s), and set as sequence features
1205 * @param alignmentPanel
1207 public void copyStructureAttributesToFeatures(String attName,
1208 AlignmentViewPanel alignmentPanel)
1210 // todo pull up to AAStructureBindingModel (and interface?)
1213 * ask Chimera to list residues with the attribute, reporting its value
1215 // this alternative command
1216 // list residues spec ':*/attName' attr attName
1217 // doesn't report 'None' values (which is good), but
1218 // fails for 'average.bfactor' (which is bad):
1220 String cmd = "list residues attr '" + attName + "'";
1221 List<String> residues = sendChimeraCommand(cmd, true);
1223 boolean featureAdded = createFeaturesForAttributes(attName, residues);
1226 alignmentPanel.getFeatureRenderer().featuresAdded();
1231 * Create features in Jalview for the given attribute name and structure
1235 * The residue list should be 0, 1 or more reply lines of the format:
1236 * residue id #0:5.A isHelix -155.000836316 index 5
1238 * residue id #0:6.A isHelix None
1245 protected boolean createFeaturesForAttributes(String attName,
1246 List<String> residues)
1248 boolean featureAdded = false;
1249 String featureGroup = getViewerFeatureGroup();
1251 for (String residue : residues)
1253 AtomSpec spec = null;
1254 String[] tokens = residue.split(" ");
1255 if (tokens.length < 5)
1259 String atomSpec = tokens[2];
1260 String attValue = tokens[4];
1263 * ignore 'None' (e.g. for phi) or 'False' (e.g. for isHelix)
1265 if ("None".equalsIgnoreCase(attValue)
1266 || "False".equalsIgnoreCase(attValue))
1273 spec = AtomSpec.fromChimeraAtomspec(atomSpec);
1274 } catch (IllegalArgumentException e)
1276 System.err.println("Problem parsing atomspec " + atomSpec);
1280 String chainId = spec.getChain();
1281 String description = attValue;
1282 float score = Float.NaN;
1285 score = Float.valueOf(attValue);
1286 description = chainId;
1287 } catch (NumberFormatException e)
1289 // was not a float value
1292 String pdbFile = getPdbFileForModel(spec.getModelNumber());
1293 spec.setPdbFile(pdbFile);
1295 List<AtomSpec> atoms = Collections.singletonList(spec);
1298 * locate the mapped position in the alignment (if any)
1300 SearchResults sr = getSsm()
1301 .findAlignmentPositionsForStructurePositions(atoms);
1304 * expect one matched alignment position, or none
1305 * (if the structure position is not mapped)
1307 for (SearchResultMatchI m : sr.getResults())
1309 SequenceI seq = m.getSequence();
1310 int start = m.getStart();
1311 int end = m.getEnd();
1312 SequenceFeature sf = new SequenceFeature(attName, description,
1313 start, end, score, featureGroup);
1314 // todo: should SequenceFeature have an explicit property for chain?
1315 // note: repeating the action shouldn't duplicate features
1316 featureAdded |= seq.addSequenceFeature(sf);
1319 return featureAdded;
1323 * Answers the feature group name to apply to features created in Jalview from
1324 * Chimera attributes
1328 protected String getViewerFeatureGroup()
1330 // todo pull up to interface
1331 return CHIMERA_FEATURE_GROUP;
1335 public Hashtable<String, String> getChainFile()
1340 public List<ChimeraModel> getChimeraModelByChain(String chain)
1342 return chimeraMaps.get(chainFile.get(chain));
1345 public int getModelNoForChain(String chain)
1347 List<ChimeraModel> foundModels = getChimeraModelByChain(chain);
1348 if (foundModels != null && !foundModels.isEmpty())
1350 return foundModels.get(0).getModelNumber();