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.StructureMapping;
32 import jalview.structure.StructureMappingcommandSet;
33 import jalview.structure.StructureSelectionManager;
34 import jalview.structures.models.AAStructureBindingModel;
35 import jalview.util.ColorUtils;
37 import java.awt.Color;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.LinkedHashMap;
41 import java.util.List;
45 * Routines for generating Chimera commands for Jalview/Chimera binding
50 public class ChimeraCommands extends StructureCommands
52 public static final String NAMESPACE_PREFIX = "jv_";
55 * colour for residues shown in structure but hidden in alignment
57 private static final String COLOR_GRAY_HEX = "color "
58 + ColorUtils.toTkCode(Color.GRAY);
61 * Constructs Chimera commands to colour residues as per the Jalview alignment
67 public static String[] getColourBySequenceCommand(
68 Map<Object, AtomSpecModel> colourMap,
69 AAStructureBindingModel binding)
71 List<String> colourCommands = buildColourCommands(colourMap, binding);
73 return colourCommands.toArray(new String[colourCommands.size()]);
77 * Traverse the map of colours/models/chains/positions to construct a list of
78 * 'color' commands (one per distinct colour used). The format of each command
83 * color colorname #modelnumber:range.chain
84 * e.g. color #00ff00 #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
92 protected static List<String> buildColourCommands(
93 Map<Object, AtomSpecModel> colourMap,
94 AAStructureBindingModel binding)
97 * This version concatenates all commands into a single String (semi-colon
98 * delimited). If length limit issues arise, refactor to return one color
101 List<String> commands = new ArrayList<>();
102 StringBuilder sb = new StringBuilder(256);
103 sb.append(COLOR_GRAY_HEX);
105 for (Object key : colourMap.keySet())
107 Color colour = (Color) key;
108 String colourCode = ColorUtils.toTkCode(colour);
110 sb.append("color ").append(colourCode).append(" ");
111 final AtomSpecModel colourData = colourMap.get(colour);
112 sb.append(getAtomSpec(colourData, binding));
114 commands.add(sb.toString());
119 * Constructs and returns Chimera commands to set attributes on residues
120 * corresponding to features in Jalview. Attribute names are the Jalview feature
121 * type, with a "jv_" prefix.
130 public static StructureMappingcommandSet getSetAttributeCommandsForFeatures(
131 AlignmentViewPanel viewPanel, AAStructureBindingModel binding)
133 StructureSelectionManager ssm = binding.getSsm();
134 String[] files = binding.getStructureFiles();
135 SequenceI[][] seqs = binding.getSequence();
137 Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
138 ssm, files, seqs, viewPanel);
140 List<String> commands = buildSetAttributeCommands(featureMap, binding);
142 StructureMappingcommandSet cs = new StructureMappingcommandSet(
143 ChimeraCommands.class, null,
144 commands.toArray(new String[commands.size()]));
151 * Helper method to build a map of
152 * { featureType, { feature value, AtomSpecModel } }
161 protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
162 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
163 AlignmentViewPanel viewPanel)
165 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
167 FeatureRenderer fr = viewPanel.getFeatureRenderer();
173 AlignViewportI viewport = viewPanel.getAlignViewport();
174 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
177 * if alignment is showing features from complement, we also transfer
178 * these features to the corresponding mapped structure residues
180 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
181 List<String> complementFeatures = new ArrayList<>();
182 FeatureRenderer complementRenderer = null;
183 if (showLinkedFeatures)
185 AlignViewportI comp = fr.getViewport().getCodingComplement();
188 complementRenderer = Desktop.getAlignFrameFor(comp)
189 .getFeatureRenderer();
190 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
193 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
198 AlignmentI alignment = viewPanel.getAlignment();
199 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
201 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
203 if (mapping == null || mapping.length < 1)
208 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
210 for (int m = 0; m < mapping.length; m++)
212 final SequenceI seq = seqs[pdbfnum][seqNo];
213 int sp = alignment.findIndex(seq);
214 StructureMapping structureMapping = mapping[m];
215 if (structureMapping.getSequence() == seq && sp > -1)
218 * found a sequence with a mapping to a structure;
219 * now scan its features
221 if (!visibleFeatures.isEmpty())
223 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
226 if (showLinkedFeatures)
228 scanComplementFeatures(complementRenderer, structureMapping,
229 seq, theMap, pdbfnum);
239 * Scans visible features in mapped positions of the CDS/peptide complement, and
240 * adds any found to the map of attribute values/structure positions
242 * @param complementRenderer
243 * @param structureMapping
248 protected static void scanComplementFeatures(
249 FeatureRenderer complementRenderer,
250 StructureMapping structureMapping, SequenceI seq,
251 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
254 * for each sequence residue mapped to a structure position...
256 for (int seqPos : structureMapping.getMapping().keySet())
259 * find visible complementary features at mapped position(s)
261 MappedFeatures mf = complementRenderer
262 .findComplementFeaturesAtResidue(seq, seqPos);
265 for (SequenceFeature sf : mf.features)
267 String type = sf.getType();
270 * Don't copy features which originated from Chimera
272 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
273 .equals(sf.getFeatureGroup()))
279 * record feature 'value' (score/description/type) as at the
280 * corresponding structure position
282 List<int[]> mappedRanges = structureMapping
283 .getPDBResNumRanges(seqPos, seqPos);
285 if (!mappedRanges.isEmpty())
287 String value = sf.getDescription();
288 if (value == null || value.length() == 0)
292 float score = sf.getScore();
293 if (score != 0f && !Float.isNaN(score))
295 value = Float.toString(score);
297 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
298 if (featureValues == null)
300 featureValues = new HashMap<>();
301 theMap.put(type, featureValues);
303 for (int[] range : mappedRanges)
305 addAtomSpecRange(featureValues, value, modelNumber, range[0],
306 range[1], structureMapping.getChain());
315 * Inspect features on the sequence; for each feature that is visible, determine
316 * its mapped ranges in the structure (if any) according to the given mapping,
317 * and add them to the map.
319 * @param visibleFeatures
325 protected static void scanSequenceFeatures(List<String> visibleFeatures,
326 StructureMapping mapping, SequenceI seq,
327 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
329 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
330 visibleFeatures.toArray(new String[visibleFeatures.size()]));
331 for (SequenceFeature sf : sfs)
333 String type = sf.getType();
336 * Don't copy features which originated from Chimera
338 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
339 .equals(sf.getFeatureGroup()))
344 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
347 if (!mappedRanges.isEmpty())
349 String value = sf.getDescription();
350 if (value == null || value.length() == 0)
354 float score = sf.getScore();
355 if (score != 0f && !Float.isNaN(score))
357 value = Float.toString(score);
359 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
360 if (featureValues == null)
362 featureValues = new HashMap<>();
363 theMap.put(type, featureValues);
365 for (int[] range : mappedRanges)
367 addAtomSpecRange(featureValues, value, modelNumber, range[0],
368 range[1], mapping.getChain());
375 * Traverse the map of features/values/models/chains/positions to construct a
376 * list of 'setattr' commands (one per distinct feature type and value).
378 * The format of each command is
381 * <blockquote> setattr r <featureName> " " #modelnumber:range.chain
382 * e.g. setattr r jv:chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
390 protected static List<String> buildSetAttributeCommands(
391 Map<String, Map<Object, AtomSpecModel>> featureMap,
392 AAStructureBindingModel binding)
394 List<String> commands = new ArrayList<>();
395 for (String featureType : featureMap.keySet())
397 String attributeName = makeAttributeName(featureType);
400 * clear down existing attributes for this feature
402 // 'problem' - sets attribute to None on all residues - overkill?
403 // commands.add("~setattr r " + attributeName + " :*");
405 Map<Object, AtomSpecModel> values = featureMap.get(featureType);
406 for (Object value : values.keySet())
409 * for each distinct value recorded for this feature type,
410 * add a command to set the attribute on the mapped residues
411 * Put values in single quotes, encoding any embedded single quotes
413 StringBuilder sb = new StringBuilder(128);
414 String featureValue = value.toString();
415 featureValue = featureValue.replaceAll("\\'", "'");
416 sb.append("setattr r ").append(attributeName).append(" '")
417 .append(featureValue).append("' ");
418 sb.append(getAtomSpec(values.get(value), binding));
419 commands.add(sb.toString());
427 * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
428 * for a 'Jalview' namespace, and any non-alphanumeric character is converted
435 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
438 protected static String makeAttributeName(String featureType)
440 StringBuilder sb = new StringBuilder();
441 if (featureType != null)
443 for (char c : featureType.toCharArray())
445 sb.append(Character.isLetterOrDigit(c) ? c : '_');
448 String attName = NAMESPACE_PREFIX + sb.toString();
451 * Chimera treats an attribute name ending in 'color' as colour-valued;
452 * Jalview doesn't, so prevent this by appending an underscore
454 if (attName.toUpperCase().endsWith("COLOR"))
463 * Returns the range(s) formatted as a Chimera atomspec
467 public static String getAtomSpec(AtomSpecModel atomSpec,
468 AAStructureBindingModel binding)
470 StringBuilder sb = new StringBuilder(128);
471 boolean firstModel = true;
472 for (Integer model : atomSpec.getModels())
479 sb.append(binding.getModelSpec(model)).append(":");
481 boolean firstPositionForModel = true;
483 for (String chain : atomSpec.getChains(model))
485 chain = " ".equals(chain) ? chain : chain.trim();
487 List<int[]> rangeList = atomSpec.getRanges(model, chain);
489 String chainToken = " ".equals(chain) ? "." : "." + chain;
490 appendResidueRange(sb, rangeList, chainToken,
491 firstPositionForModel);
492 firstPositionForModel = false;
495 return sb.toString();
499 * Chimera atomspec requires chain to be specified for each start-end residue
500 * range, otherwise it will apply to all chains
505 protected static void appendChainToRange(StringBuilder sb, String chain)
508 if (!" ".equals(chain))