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.api.SequenceRenderer;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.MappedFeatures;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.Desktop;
33 import jalview.renderer.seqfeatures.FeatureColourFinder;
34 import jalview.structure.StructureMapping;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.ColorUtils;
37 import jalview.util.Comparison;
39 import java.awt.Color;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.LinkedHashMap;
43 import java.util.List;
45 import java.util.Map.Entry;
48 * Routines for generating ChimeraX commands for Jalview/ChimeraX binding
50 public class ChimeraXCommands extends ChimeraCommands
52 private static final String CMD_COLOUR_BY_CHARGE = "color white;color :ASP,GLU red;color :LYS,ARG blue;color :CYS yellow";
55 * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
56 * builds a ChimeraX format atom spec
58 * @param modelAndChainRanges
60 protected static String getAtomSpec(
61 Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
63 StringBuilder sb = new StringBuilder(128);
64 boolean firstModelForColour = true;
65 for (Integer model : modelAndChainRanges.keySet())
67 boolean firstPositionForModel = true;
68 if (!firstModelForColour)
72 firstModelForColour = false;
73 sb.append("#").append(model).append(":");
75 final Map<String, List<int[]>> modelData = modelAndChainRanges
77 for (String chain : modelData.keySet())
79 boolean hasChain = !"".equals(chain.trim());
80 for (int[] range : modelData.get(chain))
82 if (!firstPositionForModel)
86 if (range[0] == range[1])
92 sb.append(range[0]).append("-").append(range[1]);
96 sb.append(".").append(chain);
98 firstPositionForModel = false;
102 return sb.toString();
107 * Build a data structure which records contiguous subsequences for each colour.
108 * From this we can easily generate the Chimera command for colour by sequence.
112 * list of start/end ranges
113 * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
116 protected static Map<Object, AtomSpecModel> buildColoursMap(
117 StructureSelectionManager ssm, String[] files,
118 SequenceI[][] sequence, SequenceRenderer sr,
119 AlignmentViewPanel viewPanel)
121 FeatureRenderer fr = viewPanel.getFeatureRenderer();
122 FeatureColourFinder finder = new FeatureColourFinder(fr);
123 AlignViewportI viewport = viewPanel.getAlignViewport();
124 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
125 AlignmentI al = viewport.getAlignment();
126 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
127 Color lastColour = null;
129 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
131 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
133 if (mapping == null || mapping.length < 1)
138 int startPos = -1, lastPos = -1;
139 String lastChain = "";
140 for (int s = 0; s < sequence[pdbfnum].length; s++)
142 for (int sp, m = 0; m < mapping.length; m++)
144 final SequenceI seq = sequence[pdbfnum][s];
145 if (mapping[m].getSequence() == seq
146 && (sp = al.findIndex(seq)) > -1)
148 SequenceI asp = al.getSequenceAt(sp);
149 for (int r = 0; r < asp.getLength(); r++)
151 // no mapping to gaps in sequence
152 if (Comparison.isGap(asp.getCharAt(r)))
156 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
158 if (pos < 1 || pos == lastPos)
163 Color colour = sr.getResidueColour(seq, r, finder);
166 * darker colour for hidden regions
168 if (!cs.isVisible(r))
173 final String chain = mapping[m].getChain();
176 * Just keep incrementing the end position for this colour range
177 * _unless_ colour, PDB model or chain has changed, or there is a
178 * gap in the mapped residue sequence
180 final boolean newColour = !colour.equals(lastColour);
181 final boolean nonContig = lastPos + 1 != pos;
182 final boolean newChain = !chain.equals(lastChain);
183 if (newColour || nonContig || newChain)
187 addAtomSpecRange(colourMap, lastColour, pdbfnum, startPos,
196 // final colour range
197 if (lastColour != null)
199 addAtomSpecRange(colourMap, lastColour, pdbfnum, startPos,
212 * Helper method to build a map of
213 * { featureType, { feature value, AtomSpecModel } }
222 protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
223 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
224 AlignmentViewPanel viewPanel)
226 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
228 FeatureRenderer fr = viewPanel.getFeatureRenderer();
234 AlignViewportI viewport = viewPanel.getAlignViewport();
235 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
238 * if alignment is showing features from complement, we also transfer
239 * these features to the corresponding mapped structure residues
241 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
242 List<String> complementFeatures = new ArrayList<>();
243 FeatureRenderer complementRenderer = null;
244 if (showLinkedFeatures)
246 AlignViewportI comp = fr.getViewport().getCodingComplement();
249 complementRenderer = Desktop.getAlignFrameFor(comp)
250 .getFeatureRenderer();
251 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
254 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
259 AlignmentI alignment = viewPanel.getAlignment();
260 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
262 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
264 if (mapping == null || mapping.length < 1)
269 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
271 for (int m = 0; m < mapping.length; m++)
273 final SequenceI seq = seqs[pdbfnum][seqNo];
274 int sp = alignment.findIndex(seq);
275 StructureMapping structureMapping = mapping[m];
276 if (structureMapping.getSequence() == seq && sp > -1)
279 * found a sequence with a mapping to a structure;
280 * now scan its features
282 if (!visibleFeatures.isEmpty())
284 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
287 if (showLinkedFeatures)
289 scanComplementFeatures(complementRenderer, structureMapping,
290 seq, theMap, pdbfnum);
300 * Scans visible features in mapped positions of the CDS/peptide complement, and
301 * adds any found to the map of attribute values/structure positions
303 * @param complementRenderer
304 * @param structureMapping
309 protected static void scanComplementFeatures(
310 FeatureRenderer complementRenderer,
311 StructureMapping structureMapping, SequenceI seq,
312 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
315 * for each sequence residue mapped to a structure position...
317 for (int seqPos : structureMapping.getMapping().keySet())
320 * find visible complementary features at mapped position(s)
322 MappedFeatures mf = complementRenderer
323 .findComplementFeaturesAtResidue(seq, seqPos);
326 for (SequenceFeature sf : mf.features)
328 String type = sf.getType();
331 * Don't copy features which originated from Chimera
333 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
334 .equals(sf.getFeatureGroup()))
340 * record feature 'value' (score/description/type) as at the
341 * corresponding structure position
343 List<int[]> mappedRanges = structureMapping
344 .getPDBResNumRanges(seqPos, seqPos);
346 if (!mappedRanges.isEmpty())
348 String value = sf.getDescription();
349 if (value == null || value.length() == 0)
353 float score = sf.getScore();
354 if (score != 0f && !Float.isNaN(score))
356 value = Float.toString(score);
358 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
359 if (featureValues == null)
361 featureValues = new HashMap<>();
362 theMap.put(type, featureValues);
364 for (int[] range : mappedRanges)
366 addAtomSpecRange(featureValues, value, modelNumber, range[0],
367 range[1], structureMapping.getChain());
376 * Inspect features on the sequence; for each feature that is visible, determine
377 * its mapped ranges in the structure (if any) according to the given mapping,
378 * and add them to the map.
380 * @param visibleFeatures
386 protected static void scanSequenceFeatures(List<String> visibleFeatures,
387 StructureMapping mapping, SequenceI seq,
388 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
390 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
391 visibleFeatures.toArray(new String[visibleFeatures.size()]));
392 for (SequenceFeature sf : sfs)
394 String type = sf.getType();
397 * Don't copy features which originated from Chimera
399 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
400 .equals(sf.getFeatureGroup()))
405 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
408 if (!mappedRanges.isEmpty())
410 String value = sf.getDescription();
411 if (value == null || value.length() == 0)
415 float score = sf.getScore();
416 if (score != 0f && !Float.isNaN(score))
418 value = Float.toString(score);
420 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
421 if (featureValues == null)
423 featureValues = new HashMap<>();
424 theMap.put(type, featureValues);
426 for (int[] range : mappedRanges)
428 addAtomSpecRange(featureValues, value, modelNumber, range[0],
429 range[1], mapping.getChain());
436 * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
437 * for a 'Jalview' namespace, and any non-alphanumeric character is converted
444 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
447 protected static String makeAttributeName(String featureType)
449 StringBuilder sb = new StringBuilder();
450 if (featureType != null)
452 for (char c : featureType.toCharArray())
454 sb.append(Character.isLetterOrDigit(c) ? c : '_');
457 String attName = NAMESPACE_PREFIX + sb.toString();
460 * Chimera treats an attribute name ending in 'color' as colour-valued;
461 * Jalview doesn't, so prevent this by appending an underscore
463 if (attName.toUpperCase().endsWith("COLOR"))
472 public String colourByCharge()
474 return CMD_COLOUR_BY_CHARGE;
478 public String colourByResidues(Map<String, Color> colours)
480 StringBuilder cmd = new StringBuilder(12 * colours.size());
483 * concatenate commands like
486 for (Entry<String, Color> entry : colours.entrySet())
488 String colorSpec = ColorUtils.toTkCode(entry.getValue());
489 String resCode = entry.getKey();
490 cmd.append("color :").append(resCode).append(" ").append(colorSpec)
491 .append(CMD_SEPARATOR);
493 return cmd.toString();
497 public String setBackgroundColour(Color col)
499 return "set bgColor " + ColorUtils.toTkCode(col);
503 protected String getColourCommand(AtomSpecModel colourData,
506 return "color " + colourData.getAtomSpecX() + " " + colourCode;
510 public String focusView()
520 protected static int getModelStartNo()
526 * Returns a viewer command to set the given residue attribute value on
527 * residues specified by the AtomSpecModel, for example
530 * setattr #0/A:3-9,14-20,39-43 res jv_strand 'strand' create true
533 * @param attributeName
534 * @param attributeValue
535 * @param atomSpecModel
539 protected String getSetAttributeCommand(String attributeName,
540 String attributeValue, AtomSpecModel atomSpecModel)
542 StringBuilder sb = new StringBuilder(128);
543 sb.append("setattr ").append(atomSpecModel.getAtomSpecX());
544 sb.append(" res ").append(attributeName).append(" '")
545 .append(attributeValue).append("'");
546 sb.append(" create true");
547 return sb.toString();