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.FeatureRenderer;
24 import jalview.api.SequenceRenderer;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.structure.StructureMapping;
29 import jalview.structure.StructureMappingcommandSet;
30 import jalview.structure.StructureSelectionManager;
31 import jalview.util.ColorUtils;
32 import jalview.util.Comparison;
34 import java.awt.Color;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.LinkedHashMap;
38 import java.util.List;
42 * Routines for generating Chimera commands for Jalview/Chimera binding
47 public class ChimeraCommands
50 public static final String NAMESPACE_PREFIX = "jv_";
53 * Constructs Chimera commands to colour residues as per the Jalview alignment
63 public static StructureMappingcommandSet getColourBySequenceCommand(
64 StructureSelectionManager ssm, String[] files,
65 SequenceI[][] sequence, SequenceRenderer sr, FeatureRenderer fr,
68 Map<Object, AtomSpecModel> colourMap = buildColoursMap(
69 ssm, files, sequence, sr, fr, alignment);
71 List<String> colourCommands = buildColourCommands(colourMap);
73 StructureMappingcommandSet cs = new StructureMappingcommandSet(
74 ChimeraCommands.class, null,
75 colourCommands.toArray(new String[colourCommands.size()]));
81 * Traverse the map of colours/models/chains/positions to construct a list of
82 * 'color' commands (one per distinct colour used). The format of each command
87 * color colorname #modelnumber:range.chain
88 * e.g. color #00ff00 #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
95 protected static List<String> buildColourCommands(
96 Map<Object, AtomSpecModel> colourMap)
99 * This version concatenates all commands into a single String (semi-colon
100 * delimited). If length limit issues arise, refactor to return one color
101 * command per colour.
103 List<String> commands = new ArrayList<String>();
104 StringBuilder sb = new StringBuilder(256);
105 boolean firstColour = true;
106 for (Object key : colourMap.keySet())
108 Color colour = (Color) key;
109 String colourCode = ColorUtils.toTkCode(colour);
114 sb.append("color ").append(colourCode).append(" ");
116 final AtomSpecModel colourData = colourMap
118 sb.append(colourData.getAtomSpec());
120 commands.add(sb.toString());
125 * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
126 * builds a Chimera format atom spec
128 * @param modelAndChainRanges
130 protected static String getAtomSpec(
131 Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
133 StringBuilder sb = new StringBuilder(128);
134 boolean firstModelForColour = true;
135 for (Integer model : modelAndChainRanges.keySet())
137 boolean firstPositionForModel = true;
138 if (!firstModelForColour)
142 firstModelForColour = false;
143 sb.append("#").append(model).append(":");
145 final Map<String, List<int[]>> modelData = modelAndChainRanges
147 for (String chain : modelData.keySet())
149 boolean hasChain = !"".equals(chain.trim());
150 for (int[] range : modelData.get(chain))
152 if (!firstPositionForModel)
156 if (range[0] == range[1])
162 sb.append(range[0]).append("-").append(range[1]);
166 sb.append(".").append(chain);
168 firstPositionForModel = false;
172 return sb.toString();
177 * Build a data structure which maps contiguous subsequences for each colour.
178 * This generates a data structure from which we can easily generate the
179 * Chimera command for colour by sequence.
183 * list of start/end ranges
184 * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
187 protected static Map<Object, AtomSpecModel> buildColoursMap(
188 StructureSelectionManager ssm, String[] files,
189 SequenceI[][] sequence, SequenceRenderer sr, FeatureRenderer fr,
190 AlignmentI alignment)
192 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<Object, AtomSpecModel>();
193 Color lastColour = null;
194 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
196 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
198 if (mapping == null || mapping.length < 1)
203 int startPos = -1, lastPos = -1;
204 String lastChain = "";
205 for (int s = 0; s < sequence[pdbfnum].length; s++)
207 for (int sp, m = 0; m < mapping.length; m++)
209 final SequenceI seq = sequence[pdbfnum][s];
210 if (mapping[m].getSequence() == seq
211 && (sp = alignment.findIndex(seq)) > -1)
213 SequenceI asp = alignment.getSequenceAt(sp);
214 for (int r = 0; r < asp.getLength(); r++)
216 // no mapping to gaps in sequence
217 if (Comparison.isGap(asp.getCharAt(r)))
221 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
223 if (pos < 1 || pos == lastPos)
228 Color colour = sr.getResidueColour(seq, r, fr);
229 final String chain = mapping[m].getChain();
232 * Just keep incrementing the end position for this colour range
233 * _unless_ colour, PDB model or chain has changed, or there is a
234 * gap in the mapped residue sequence
236 final boolean newColour = !colour.equals(lastColour);
237 final boolean nonContig = lastPos + 1 != pos;
238 final boolean newChain = !chain.equals(lastChain);
239 if (newColour || nonContig || newChain)
243 addRange(colourMap, lastColour, pdbfnum, startPos,
252 // final colour range
253 if (lastColour != null)
255 addRange(colourMap, lastColour, pdbfnum, startPos,
267 * Helper method to add one contiguous colour range to the colour map.
276 protected static void addRange(Map<Object, AtomSpecModel> map,
277 Object key, int model, int startPos, int endPos, String chain)
280 * Get/initialize map of data for the colour
282 AtomSpecModel atomSpec = map.get(key);
283 if (atomSpec == null)
285 atomSpec = new AtomSpecModel();
286 map.put(key, atomSpec);
289 atomSpec.addRange(model, startPos, endPos, chain);
293 * Constructs and returns Chimera commands to set attributes on residues
294 * corresponding to features in Jalview. Attribute names are the Jalview
295 * feature type, with a "jv_" prefix.
304 public static StructureMappingcommandSet getSetAttributeCommandsForFeatures(
305 StructureSelectionManager ssm, String[] files,
306 SequenceI[][] seqs, FeatureRenderer fr, AlignmentI alignment)
308 Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
309 ssm, files, seqs, fr, alignment);
311 List<String> commands = buildSetAttributeCommands(featureMap);
313 StructureMappingcommandSet cs = new StructureMappingcommandSet(
314 ChimeraCommands.class, null,
315 commands.toArray(new String[commands.size()]));
322 * Helper method to build a map of
323 * { featureType, { feature value, AtomSpecModel } }
333 protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
334 StructureSelectionManager ssm, String[] files,
335 SequenceI[][] seqs, FeatureRenderer fr, AlignmentI alignment)
337 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<String, Map<Object, AtomSpecModel>>();
339 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
340 if (visibleFeatures.isEmpty())
345 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
347 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
349 if (mapping == null || mapping.length < 1)
354 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
356 for (int m = 0; m < mapping.length; m++)
358 final SequenceI seq = seqs[pdbfnum][seqNo];
359 int sp = alignment.findIndex(seq);
360 if (mapping[m].getSequence() == seq && sp > -1)
363 * found a sequence with a mapping to a structure;
364 * now scan its features
366 SequenceI asp = alignment.getSequenceAt(sp);
368 scanSequenceFeatures(visibleFeatures, mapping[m], asp, theMap,
378 * Inspect features on the sequence; for each feature that is visible,
379 * determine its mapped ranges in the structure (if any) according to the
380 * given mapping, and add them to the map
382 * @param visibleFeatures
388 protected static void scanSequenceFeatures(List<String> visibleFeatures,
389 StructureMapping mapping, SequenceI seq,
390 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
392 SequenceFeature[] sfs = seq.getSequenceFeatures();
398 for (SequenceFeature sf : sfs)
400 String type = sf.getType();
403 * Only copy visible features, don't copy any which originated
404 * from Chimera, and suppress uninteresting ones (e.g. RESNUM)
406 boolean isFromViewer = JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
407 .equals(sf.getFeatureGroup());
408 if (isFromViewer || !visibleFeatures.contains(type))
412 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
415 if (!mappedRanges.isEmpty())
417 String value = sf.getDescription();
418 if (value == null || value.length() == 0)
422 float score = sf.getScore();
423 if (score != 0f && !Float.isNaN(score))
425 value = Float.toString(score);
427 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
428 if (featureValues == null)
430 featureValues = new HashMap<Object, AtomSpecModel>();
431 theMap.put(type, featureValues);
433 for (int[] range : mappedRanges)
435 addRange(featureValues, value, modelNumber, range[0], range[1],
443 * Traverse the map of features/values/models/chains/positions to construct a
444 * list of 'setattr' commands (one per distinct feature type and value).
446 * The format of each command is
449 * <blockquote> setattr r <featureName> " " #modelnumber:range.chain
450 * e.g. setattr r jv:chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
457 protected static List<String> buildSetAttributeCommands(
458 Map<String, Map<Object, AtomSpecModel>> featureMap)
460 List<String> commands = new ArrayList<String>();
461 for (String featureType : featureMap.keySet())
463 String attributeName = makeAttributeName(featureType);
466 * clear down existing attributes for this feature
468 // 'problem' - sets attribute to None on all residues - overkill?
469 // commands.add("~setattr r " + attributeName + " :*");
471 Map<Object, AtomSpecModel> values = featureMap.get(featureType);
472 for (Object value : values.keySet())
475 * for each distinct value recorded for this feature type,
476 * add a command to set the attribute on the mapped residues
478 StringBuilder sb = new StringBuilder(128);
479 sb.append("setattr r ").append(attributeName).append(" \"")
480 .append(value.toString()).append("\" ");
481 sb.append(values.get(value).getAtomSpec());
482 commands.add(sb.toString());
490 * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
491 * for a 'Jalview' namespace, and any non-alphanumeric character is converted
496 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
499 protected static String makeAttributeName(String featureType)
501 StringBuilder sb = new StringBuilder();
502 if (featureType != null)
504 for (char c : featureType.toCharArray())
506 sb.append(Character.isLetterOrDigit(c) ? c : '_');
509 String attName = NAMESPACE_PREFIX + sb.toString();
512 * Chimera treats an attribute name ending in 'color' as colour-valued;
513 * Jalview doesn't, so prevent this by appending an underscore
515 if (attName.toUpperCase().endsWith("COLOR"))