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.FeatureRenderer;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.MappedFeatures;
28 import jalview.datamodel.SequenceFeature;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.Desktop;
31 import jalview.structure.AtomSpecModel;
32 import jalview.structure.StructureCommandsBase;
33 import jalview.structure.StructureMapping;
34 import jalview.structure.StructureSelectionManager;
35 import jalview.util.ColorUtils;
36 import jalview.util.IntRangeComparator;
38 import java.awt.Color;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.LinkedHashMap;
44 import java.util.List;
48 * Routines for generating Chimera commands for Jalview/Chimera binding
53 public class ChimeraCommands extends StructureCommandsBase
55 public static final String NAMESPACE_PREFIX = "jv_";
57 private static final String CMD_COLOUR_BY_CHARGE = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
59 private static final String CMD_COLOUR_BY_CHAIN = "rainbow chain";
61 // Chimera clause to exclude alternate locations in atom selection
62 private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
65 public String getColourCommand(String atomSpec, Color colour)
67 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/color.html
68 String colourCode = getColourString(colour);
69 return "color " + colourCode + " " + atomSpec;
73 * Returns a colour formatted suitable for use in viewer command syntax
78 protected String getColourString(Color colour)
80 return ColorUtils.toTkCode(colour);
84 * Constructs and returns Chimera commands to set attributes on residues
85 * corresponding to features in Jalview. Attribute names are the Jalview feature
86 * type, with a "jv_" prefix.
95 public String[] setAttributesForFeatures(
96 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
97 AlignmentViewPanel viewPanel)
99 Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
100 ssm, files, seqs, viewPanel);
102 return setAttributes(featureMap);
107 * Helper method to build a map of
108 * { featureType, { feature value, AtomSpecModel } }
117 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
118 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
119 AlignmentViewPanel viewPanel)
121 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
123 FeatureRenderer fr = viewPanel.getFeatureRenderer();
129 AlignViewportI viewport = viewPanel.getAlignViewport();
130 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
133 * if alignment is showing features from complement, we also transfer
134 * these features to the corresponding mapped structure residues
136 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
137 List<String> complementFeatures = new ArrayList<>();
138 FeatureRenderer complementRenderer = null;
139 if (showLinkedFeatures)
141 AlignViewportI comp = fr.getViewport().getCodingComplement();
144 complementRenderer = Desktop.getAlignFrameFor(comp)
145 .getFeatureRenderer();
146 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
149 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
154 AlignmentI alignment = viewPanel.getAlignment();
155 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
157 final int modelNumber = pdbfnum + getModelStartNo();
158 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
160 if (mapping == null || mapping.length < 1)
165 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
167 for (int m = 0; m < mapping.length; m++)
169 final SequenceI seq = seqs[pdbfnum][seqNo];
170 int sp = alignment.findIndex(seq);
171 StructureMapping structureMapping = mapping[m];
172 if (structureMapping.getSequence() == seq && sp > -1)
175 * found a sequence with a mapping to a structure;
176 * now scan its features
178 if (!visibleFeatures.isEmpty())
180 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
181 theMap, modelNumber);
183 if (showLinkedFeatures)
185 scanComplementFeatures(complementRenderer, structureMapping,
186 seq, theMap, modelNumber);
196 * Scans visible features in mapped positions of the CDS/peptide complement, and
197 * adds any found to the map of attribute values/structure positions
199 * @param complementRenderer
200 * @param structureMapping
205 protected static void scanComplementFeatures(
206 FeatureRenderer complementRenderer,
207 StructureMapping structureMapping, SequenceI seq,
208 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
211 * for each sequence residue mapped to a structure position...
213 for (int seqPos : structureMapping.getMapping().keySet())
216 * find visible complementary features at mapped position(s)
218 MappedFeatures mf = complementRenderer
219 .findComplementFeaturesAtResidue(seq, seqPos);
222 for (SequenceFeature sf : mf.features)
224 String type = sf.getType();
227 * Don't copy features which originated from Chimera
229 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
230 .equals(sf.getFeatureGroup()))
236 * record feature 'value' (score/description/type) as at the
237 * corresponding structure position
239 List<int[]> mappedRanges = structureMapping
240 .getPDBResNumRanges(seqPos, seqPos);
242 if (!mappedRanges.isEmpty())
244 String value = sf.getDescription();
245 if (value == null || value.length() == 0)
249 float score = sf.getScore();
250 if (score != 0f && !Float.isNaN(score))
252 value = Float.toString(score);
254 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
255 if (featureValues == null)
257 featureValues = new HashMap<>();
258 theMap.put(type, featureValues);
260 for (int[] range : mappedRanges)
262 addAtomSpecRange(featureValues, value, modelNumber, range[0],
263 range[1], structureMapping.getChain());
272 * Inspect features on the sequence; for each feature that is visible, determine
273 * its mapped ranges in the structure (if any) according to the given mapping,
274 * and add them to the map.
276 * @param visibleFeatures
282 protected static void scanSequenceFeatures(List<String> visibleFeatures,
283 StructureMapping mapping, SequenceI seq,
284 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
286 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
287 visibleFeatures.toArray(new String[visibleFeatures.size()]));
288 for (SequenceFeature sf : sfs)
290 String type = sf.getType();
293 * Don't copy features which originated from Chimera
295 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
296 .equals(sf.getFeatureGroup()))
301 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
304 if (!mappedRanges.isEmpty())
306 String value = sf.getDescription();
307 if (value == null || value.length() == 0)
311 float score = sf.getScore();
312 if (score != 0f && !Float.isNaN(score))
314 value = Float.toString(score);
316 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
317 if (featureValues == null)
319 featureValues = new HashMap<>();
320 theMap.put(type, featureValues);
322 for (int[] range : mappedRanges)
324 addAtomSpecRange(featureValues, value, modelNumber, range[0],
325 range[1], mapping.getChain());
332 * Traverse the map of features/values/models/chains/positions to construct a
333 * list of 'setattr' commands (one per distinct feature type and value).
335 * The format of each command is
338 * <blockquote> setattr r <featureName> " " #modelnumber:range.chain
339 * e.g. setattr r jv_chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
346 protected String[] setAttributes(
347 Map<String, Map<Object, AtomSpecModel>> featureMap)
349 List<String> commands = new ArrayList<>();
350 for (String featureType : featureMap.keySet())
352 String attributeName = makeAttributeName(featureType);
355 * clear down existing attributes for this feature
357 // 'problem' - sets attribute to None on all residues - overkill?
358 // commands.add("~setattr r " + attributeName + " :*");
360 Map<Object, AtomSpecModel> values = featureMap.get(featureType);
361 for (Object value : values.keySet())
364 * for each distinct value recorded for this feature type,
365 * add a command to set the attribute on the mapped residues
366 * Put values in single quotes, encoding any embedded single quotes
368 AtomSpecModel atomSpecModel = values.get(value);
369 String featureValue = value.toString();
370 featureValue = featureValue.replaceAll("\\'", "'");
371 String cmd = setAttribute(attributeName, featureValue,
377 return commands.toArray(new String[commands.size()]);
381 * Returns a viewer command to set the given residue attribute value on
382 * residues specified by the AtomSpecModel, for example
385 * setatr res jv_chain 'primary' #1:12-34,48-55.B
388 * @param attributeName
389 * @param attributeValue
390 * @param atomSpecModel
393 protected String setAttribute(String attributeName,
394 String attributeValue,
395 AtomSpecModel atomSpecModel)
397 StringBuilder sb = new StringBuilder(128);
398 sb.append("setattr res ").append(attributeName).append(" '")
399 .append(attributeValue).append("' ");
400 sb.append(getAtomSpec(atomSpecModel, false));
401 return sb.toString();
405 * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
406 * for a 'Jalview' namespace, and any non-alphanumeric character is converted
411 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
413 protected static String makeAttributeName(String featureType)
415 StringBuilder sb = new StringBuilder();
416 if (featureType != null)
418 for (char c : featureType.toCharArray())
420 sb.append(Character.isLetterOrDigit(c) ? c : '_');
423 String attName = NAMESPACE_PREFIX + sb.toString();
426 * Chimera treats an attribute name ending in 'color' as colour-valued;
427 * Jalview doesn't, so prevent this by appending an underscore
429 if (attName.toUpperCase().endsWith("COLOR"))
438 public String colourByChain()
440 return CMD_COLOUR_BY_CHAIN;
444 public String colourByCharge()
446 return CMD_COLOUR_BY_CHARGE;
450 public String getResidueSpec(String residue)
452 return "::" + residue;
456 public String setBackgroundColour(Color col)
458 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/set.html#bgcolor
459 return "set bgColor " + ColorUtils.toTkCode(col);
463 public String focusView()
465 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/focus.html
470 public String showChains(List<String> toShow)
473 * Construct a chimera command like
475 * ~display #*;~ribbon #*;ribbon :.A,:.B
477 StringBuilder cmd = new StringBuilder(64);
478 boolean first = true;
479 for (String chain : toShow)
481 String[] tokens = chain.split(":");
482 if (tokens.length == 2)
484 String showChainCmd = tokens[0] + ":." + tokens[1];
489 cmd.append(showChainCmd);
495 * could append ";focus" to this command to resize the display to fill the
496 * window, but it looks more helpful not to (easier to relate chains to the
499 final String command = "~display #*; ~ribbon #*; ribbon :"
505 public String superposeStructures(AtomSpecModel spec, AtomSpecModel ref)
508 * Form Chimera match command to match spec to ref
510 * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
513 * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
515 StringBuilder cmd = new StringBuilder();
516 String atomSpec = getAtomSpec(spec, true);
517 String refSpec = getAtomSpec(ref, true);
518 cmd.append("match ").append(atomSpec).append(" ").append(refSpec);
521 * show superposed residues as ribbon, others as chain
523 // fixme this should precede the loop over all alignments/structures
524 cmd.append(";~display all; chain @CA|P");
525 cmd.append("; ribbon ");
526 cmd.append(atomSpec).append("|").append(refSpec).append("; focus");
528 return cmd.toString();
532 public String openCommandFile(String path)
534 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/filetypes.html
535 return "open cmd:" + path;
539 public String saveSession(String filepath)
541 // https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/save.html
542 return "save " + filepath;
546 * Returns the range(s) modelled by {@code atomSpec} formatted as a Chimera
547 * atomspec string, e.g.
550 * #0:15.A,28.A,54.A,70-72.A|#1:2.A,6.A,11.A,13-14.A
555 * <li>#0 is a model number</li>
556 * <li>15 or 70-72 is a residue number, or range of residue numbers</li>
557 * <li>.A is a chain identifier</li>
558 * <li>residue ranges are separated by comma</li>
559 * <li>atomspecs for distinct models are separated by | (or)</li>
567 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/frameatom_spec.html
570 public String getAtomSpec(AtomSpecModel atomSpec, boolean alphaOnly)
572 StringBuilder sb = new StringBuilder(128);
573 boolean firstModel = true;
574 for (Integer model : atomSpec.getModels())
581 appendModel(sb, model, atomSpec, alphaOnly);
583 return sb.toString();
587 * A helper method to append an atomSpec string for atoms in the given model
594 protected void appendModel(StringBuilder sb, Integer model,
595 AtomSpecModel atomSpec, boolean alphaOnly)
597 sb.append("#").append(model).append(":");
599 boolean firstPositionForModel = true;
601 for (String chain : atomSpec.getChains(model))
603 chain = " ".equals(chain) ? chain : chain.trim();
605 List<int[]> rangeList = atomSpec.getRanges(model, chain);
608 * sort ranges into ascending start position order
610 Collections.sort(rangeList, IntRangeComparator.ASCENDING);
612 int start = rangeList.isEmpty() ? 0 : rangeList.get(0)[0];
613 int end = rangeList.isEmpty() ? 0 : rangeList.get(0)[1];
615 Iterator<int[]> iterator = rangeList.iterator();
616 while (iterator.hasNext())
618 int[] range = iterator.next();
619 if (range[0] <= end + 1)
622 * range overlaps or is contiguous with the last one
623 * - so just extend the end position, and carry on
624 * (unless this is the last in the list)
626 end = Math.max(end, range[1]);
631 * we have a break so append the last range
633 appendRange(sb, start, end, chain, firstPositionForModel, false);
634 firstPositionForModel = false;
641 * and append the last range
643 if (!rangeList.isEmpty())
645 appendRange(sb, start, end, chain, firstPositionForModel, false);
646 firstPositionForModel = false;
652 * restrict to alpha carbon, no alternative locations
653 * (needed to ensuring matching atom counts for superposition)
655 sb.append("@CA|P").append(NO_ALTLOCS);
660 public String showBackbone()
662 return "~display all;chain @CA|P";