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 java.awt.Color;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.LinkedHashMap;
28 import java.util.List;
31 import jalview.api.AlignViewportI;
32 import jalview.api.AlignmentViewPanel;
33 import jalview.api.FeatureRenderer;
34 import jalview.datamodel.AlignmentI;
35 import jalview.datamodel.MappedFeatures;
36 import jalview.datamodel.SequenceFeature;
37 import jalview.datamodel.SequenceI;
38 import jalview.gui.Desktop;
39 import jalview.structure.AtomSpecModel;
40 import jalview.structure.StructureCommand;
41 import jalview.structure.StructureCommandI;
42 import jalview.structure.StructureCommandsBase;
43 import jalview.structure.StructureMapping;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.util.ColorUtils;
48 * Routines for generating Chimera commands for Jalview/Chimera binding
53 public class ChimeraCommands extends StructureCommandsBase
55 private static final StructureCommand SHOW_BACKBONE = new StructureCommand(
56 "~display all;~ribbon;chain @CA|P");
58 public static final String NAMESPACE_PREFIX = "jv_";
60 private static final StructureCommandI COLOUR_BY_CHARGE = new StructureCommand(
61 "color white;color red ::ASP,GLU;color blue ::LYS,ARG;color yellow ::CYS");
63 private static final StructureCommandI COLOUR_BY_CHAIN = new StructureCommand(
66 // Chimera clause to exclude alternate locations in atom selection
67 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
70 public StructureCommandI getColourCommand(String atomSpec, Color colour)
72 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/color.html
73 String colourCode = getColourString(colour);
74 return new StructureCommand("color " + colourCode + " " + atomSpec);
78 * Returns a colour formatted suitable for use in viewer command syntax
83 protected String getColourString(Color colour)
85 return ColorUtils.toTkCode(colour);
89 * Constructs and returns Chimera commands to set attributes on residues
90 * corresponding to features in Jalview. Attribute names are the Jalview feature
91 * type, with a "jv_" prefix.
100 public List<StructureCommandI> setAttributesForFeatures(
101 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
102 AlignmentViewPanel viewPanel)
104 Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
105 ssm, files, seqs, viewPanel);
107 return setAttributes(featureMap);
112 * Helper method to build a map of
113 * { featureType, { feature value, AtomSpecModel } }
122 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
123 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
124 AlignmentViewPanel viewPanel)
126 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
128 FeatureRenderer fr = viewPanel.getFeatureRenderer();
134 AlignViewportI viewport = viewPanel.getAlignViewport();
135 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
138 * if alignment is showing features from complement, we also transfer
139 * these features to the corresponding mapped structure residues
141 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
142 List<String> complementFeatures = new ArrayList<>();
143 FeatureRenderer complementRenderer = null;
144 if (showLinkedFeatures)
146 AlignViewportI comp = fr.getViewport().getCodingComplement();
149 complementRenderer = Desktop.getAlignFrameFor(comp)
150 .getFeatureRenderer();
151 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
154 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
159 AlignmentI alignment = viewPanel.getAlignment();
160 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
162 final int modelNumber = pdbfnum + getModelStartNo();
163 String modelId = String.valueOf(modelNumber);
164 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
166 if (mapping == null || mapping.length < 1)
171 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
173 for (int m = 0; m < mapping.length; m++)
175 final SequenceI seq = seqs[pdbfnum][seqNo];
176 int sp = alignment.findIndex(seq);
177 StructureMapping structureMapping = mapping[m];
178 if (structureMapping.getSequence() == seq && sp > -1)
181 * found a sequence with a mapping to a structure;
182 * now scan its features
184 if (!visibleFeatures.isEmpty())
186 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
189 if (showLinkedFeatures)
191 scanComplementFeatures(complementRenderer, structureMapping,
192 seq, theMap, modelId);
202 * Scans visible features in mapped positions of the CDS/peptide complement, and
203 * adds any found to the map of attribute values/structure positions
205 * @param complementRenderer
206 * @param structureMapping
211 protected static void scanComplementFeatures(
212 FeatureRenderer complementRenderer,
213 StructureMapping structureMapping, SequenceI seq,
214 Map<String, Map<Object, AtomSpecModel>> theMap,
218 * for each sequence residue mapped to a structure position...
220 for (int seqPos : structureMapping.getMapping().keySet())
223 * find visible complementary features at mapped position(s)
225 MappedFeatures mf = complementRenderer
226 .findComplementFeaturesAtResidue(seq, seqPos);
229 for (SequenceFeature sf : mf.features)
231 String type = sf.getType();
234 * Don't copy features which originated from Chimera
236 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
237 .equals(sf.getFeatureGroup()))
243 * record feature 'value' (score/description/type) as at the
244 * corresponding structure position
246 List<int[]> mappedRanges = structureMapping
247 .getPDBResNumRanges(seqPos, seqPos);
249 if (!mappedRanges.isEmpty())
251 String value = sf.getDescription();
252 if (value == null || value.length() == 0)
256 float score = sf.getScore();
257 if (score != 0f && !Float.isNaN(score))
259 value = Float.toString(score);
261 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
262 if (featureValues == null)
264 featureValues = new HashMap<>();
265 theMap.put(type, featureValues);
267 for (int[] range : mappedRanges)
269 addAtomSpecRange(featureValues, value, modelNumber, range[0],
270 range[1], structureMapping.getChain());
279 * Inspect features on the sequence; for each feature that is visible,
280 * determine its mapped ranges in the structure (if any) according to the
281 * given mapping, and add them to the map.
283 * @param visibleFeatures
289 protected static void scanSequenceFeatures(List<String> visibleFeatures,
290 StructureMapping mapping, SequenceI seq,
291 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
293 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
294 visibleFeatures.toArray(new String[visibleFeatures.size()]));
295 for (SequenceFeature sf : sfs)
297 String type = sf.getType();
300 * Don't copy features which originated from Chimera
302 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
303 .equals(sf.getFeatureGroup()))
308 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
311 if (!mappedRanges.isEmpty())
313 String value = sf.getDescription();
314 if (value == null || value.length() == 0)
318 float score = sf.getScore();
319 if (score != 0f && !Float.isNaN(score))
321 value = Float.toString(score);
323 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
324 if (featureValues == null)
326 featureValues = new HashMap<>();
327 theMap.put(type, featureValues);
329 for (int[] range : mappedRanges)
331 addAtomSpecRange(featureValues, value, modelId, range[0],
332 range[1], mapping.getChain());
339 * Traverse the map of features/values/models/chains/positions to construct a
340 * list of 'setattr' commands (one per distinct feature type and value).
342 * The format of each command is
345 * <blockquote> setattr r <featureName> " " #modelnumber:range.chain
346 * e.g. setattr r jv_chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
353 protected List<StructureCommandI> setAttributes(
354 Map<String, Map<Object, AtomSpecModel>> featureMap)
356 List<StructureCommandI> commands = new ArrayList<>();
357 for (String featureType : featureMap.keySet())
359 String attributeName = makeAttributeName(featureType);
362 * clear down existing attributes for this feature
364 // 'problem' - sets attribute to None on all residues - overkill?
365 // commands.add("~setattr r " + attributeName + " :*");
367 Map<Object, AtomSpecModel> values = featureMap.get(featureType);
368 for (Object value : values.keySet())
371 * for each distinct value recorded for this feature type,
372 * add a command to set the attribute on the mapped residues
373 * Put values in single quotes, encoding any embedded single quotes
375 AtomSpecModel atomSpecModel = values.get(value);
376 String featureValue = value.toString();
377 featureValue = featureValue.replaceAll("\\'", "'");
378 StructureCommandI cmd = setAttribute(attributeName, featureValue,
388 * Returns a viewer command to set the given residue attribute value on
389 * residues specified by the AtomSpecModel, for example
392 * setatr res jv_chain 'primary' #1:12-34,48-55.B
395 * @param attributeName
396 * @param attributeValue
397 * @param atomSpecModel
400 protected StructureCommandI setAttribute(String attributeName,
401 String attributeValue,
402 AtomSpecModel atomSpecModel)
404 StringBuilder sb = new StringBuilder(128);
405 sb.append("setattr res ").append(attributeName).append(" '")
406 .append(attributeValue).append("' ");
407 sb.append(getAtomSpec(atomSpecModel, false));
408 return new StructureCommand(sb.toString());
412 * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
413 * for a 'Jalview' namespace, and any non-alphanumeric character is converted
418 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
420 protected static String makeAttributeName(String featureType)
422 StringBuilder sb = new StringBuilder();
423 if (featureType != null)
425 for (char c : featureType.toCharArray())
427 sb.append(Character.isLetterOrDigit(c) ? c : '_');
430 String attName = NAMESPACE_PREFIX + sb.toString();
433 * Chimera treats an attribute name ending in 'color' as colour-valued;
434 * Jalview doesn't, so prevent this by appending an underscore
436 if (attName.toUpperCase().endsWith("COLOR"))
445 public StructureCommandI colourByChain()
447 return COLOUR_BY_CHAIN;
451 public List<StructureCommandI> colourByCharge()
453 return Arrays.asList(COLOUR_BY_CHARGE);
457 public String getResidueSpec(String residue)
459 return "::" + residue;
463 public StructureCommandI setBackgroundColour(Color col)
465 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/set.html#bgcolor
466 return new StructureCommand("set bgColor " + ColorUtils.toTkCode(col));
470 public StructureCommandI focusView()
472 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/focus.html
473 return new StructureCommand("focus");
477 public List<StructureCommandI> showChains(List<String> toShow)
480 * Construct a chimera command like
482 * ~display #*;~ribbon #*;ribbon :.A,:.B
484 StringBuilder cmd = new StringBuilder(64);
485 boolean first = true;
486 for (String chain : toShow)
488 String[] tokens = chain.split(":");
489 if (tokens.length == 2)
491 String showChainCmd = tokens[0] + ":." + tokens[1];
496 cmd.append(showChainCmd);
502 * could append ";focus" to this command to resize the display to fill the
503 * window, but it looks more helpful not to (easier to relate chains to the
506 final String command = "~display #*; ~ribbon #*; ribbon :"
508 return Arrays.asList(new StructureCommand(command));
512 public List<StructureCommandI> superposeStructures(AtomSpecModel ref,
516 * Form Chimera match command to match spec to ref
517 * (the first set of atoms are moved on to the second)
519 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
521 * @see https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
523 StringBuilder cmd = new StringBuilder();
524 String atomSpecAlphaOnly = getAtomSpec(spec, true);
525 String refSpecAlphaOnly = getAtomSpec(ref, true);
526 cmd.append("match ").append(atomSpecAlphaOnly).append(" ").append(refSpecAlphaOnly);
529 * show superposed residues as ribbon
531 String atomSpec = getAtomSpec(spec, false);
532 String refSpec = getAtomSpec(ref, false);
533 cmd.append("; ribbon ");
534 cmd.append(atomSpec).append("|").append(refSpec).append("; focus");
536 return Arrays.asList(new StructureCommand(cmd.toString()));
540 public StructureCommandI openCommandFile(String path)
542 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/filetypes.html
543 return new StructureCommand("open cmd:" + path);
547 public StructureCommandI saveSession(String filepath)
549 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
550 return new StructureCommand("save " + filepath);
554 * Returns the range(s) modelled by {@code atomSpec} formatted as a Chimera
555 * atomspec string, e.g.
558 * #0:15.A,28.A,54.A,70-72.A|#1:2.A,6.A,11.A,13-14.A
563 * <li>#0 is a model number</li>
564 * <li>15 or 70-72 is a residue number, or range of residue numbers</li>
565 * <li>.A is a chain identifier</li>
566 * <li>residue ranges are separated by comma</li>
567 * <li>atomspecs for distinct models are separated by | (or)</li>
575 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/frameatom_spec.html
578 public String getAtomSpec(AtomSpecModel atomSpec, boolean alphaOnly)
580 StringBuilder sb = new StringBuilder(128);
581 boolean firstModel = true;
582 for (String model : atomSpec.getModels())
589 appendModel(sb, model, atomSpec, alphaOnly);
591 return sb.toString();
595 * A helper method to append an atomSpec string for atoms in the given model
602 protected void appendModel(StringBuilder sb, String model,
603 AtomSpecModel atomSpec, boolean alphaOnly)
605 sb.append("#").append(model).append(":");
607 boolean firstPositionForModel = true;
609 for (String chain : atomSpec.getChains(model))
611 chain = " ".equals(chain) ? chain : chain.trim();
613 List<int[]> rangeList = atomSpec.getRanges(model, chain);
614 for (int[] range : rangeList)
616 appendRange(sb, range[0], range[1], chain, firstPositionForModel,
618 firstPositionForModel = false;
624 * restrict to alpha carbon, no alternative locations
625 * (needed to ensuring matching atom counts for superposition)
627 // TODO @P instead if RNA - add nucleotide flag to AtomSpecModel?
628 sb.append("@CA").append(NO_ALTLOCS);
633 public List<StructureCommandI> showBackbone()
635 return Arrays.asList(SHOW_BACKBONE);
639 public StructureCommandI loadFile(String file)
641 return new StructureCommand("open " + file);
645 * Overrides the default method to concatenate colour commands into one
648 public List<StructureCommandI> colourBySequence(
649 Map<Object, AtomSpecModel> colourMap)
651 List<StructureCommandI> commands = new ArrayList<>();
652 StringBuilder sb = new StringBuilder(colourMap.size() * 20);
653 boolean first = true;
654 for (Object key : colourMap.keySet())
656 Color colour = (Color) key;
657 final AtomSpecModel colourData = colourMap.get(colour);
658 StructureCommandI command = getColourCommand(colourData, colour);
661 sb.append(getCommandSeparator());
664 sb.append(command.getCommand());
667 commands.add(new StructureCommand(sb.toString()));