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.StructureCommandsBase;
35 import jalview.structure.StructureMapping;
36 import jalview.structure.StructureSelectionManager;
37 import jalview.util.ColorUtils;
38 import jalview.util.Comparison;
40 import java.awt.Color;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.LinkedHashMap;
44 import java.util.List;
46 import java.util.Map.Entry;
49 * Routines for generating Chimera commands for Jalview/Chimera binding
54 public class ChimeraCommands extends StructureCommandsBase
56 public static final String NAMESPACE_PREFIX = "jv_";
58 protected static final String CMD_SEPARATOR = ";";
60 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";
62 private static final String CMD_COLOUR_BY_CHAIN = "rainbow chain";
65 public String[] colourBySequence(
66 StructureSelectionManager ssm, String[] files,
67 SequenceI[][] sequence, SequenceRenderer sr,
68 AlignmentViewPanel viewPanel)
70 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
71 sequence, sr, viewPanel);
73 List<String> colourCommands = buildColourCommands(colourMap);
75 return colourCommands.toArray(new String[colourCommands.size()]);
79 * Traverse the map of colours/models/chains/positions to construct a list of
80 * 'color' commands (one per distinct colour used). The format of each command
85 * color colorname #modelnumber:range.chain
86 * e.g. color #00ff00 #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
93 protected List<String> buildColourCommands(
94 Map<Object, AtomSpecModel> colourMap)
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 boolean firstColour = true;
104 for (Object key : colourMap.keySet())
106 Color colour = (Color) key;
107 String colourCode = ColorUtils.toTkCode(colour);
113 final AtomSpecModel colourData = colourMap.get(colour);
114 sb.append(getColourCommand(colourData, colourCode));
116 commands.add(sb.toString());
120 protected String getColourCommand(AtomSpecModel colourData,
123 return "color " + colourCode + " " + colourData.getAtomSpec();
127 * Traverses a map of { modelNumber, {chain, {list of from-to ranges} } } and
128 * builds a Chimera format atom spec
130 * @param modelAndChainRanges
132 protected static String getAtomSpec(
133 Map<Integer, Map<String, List<int[]>>> modelAndChainRanges)
135 StringBuilder sb = new StringBuilder(128);
136 boolean firstModelForColour = true;
137 for (Integer model : modelAndChainRanges.keySet())
139 boolean firstPositionForModel = true;
140 if (!firstModelForColour)
144 firstModelForColour = false;
145 sb.append("#").append(model).append(":");
147 final Map<String, List<int[]>> modelData = modelAndChainRanges
149 for (String chain : modelData.keySet())
151 boolean hasChain = !"".equals(chain.trim());
152 for (int[] range : modelData.get(chain))
154 if (!firstPositionForModel)
158 if (range[0] == range[1])
164 sb.append(range[0]).append("-").append(range[1]);
168 sb.append(".").append(chain);
170 firstPositionForModel = false;
174 return sb.toString();
179 * Build a data structure which records contiguous subsequences for each colour.
180 * From this we can easily generate the Chimera command for colour by sequence.
184 * list of start/end ranges
185 * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
195 protected static Map<Object, AtomSpecModel> buildColoursMap(
196 StructureSelectionManager ssm, String[] files,
197 SequenceI[][] sequence, SequenceRenderer sr,
198 AlignmentViewPanel viewPanel)
200 FeatureRenderer fr = viewPanel.getFeatureRenderer();
201 FeatureColourFinder finder = new FeatureColourFinder(fr);
202 AlignViewportI viewport = viewPanel.getAlignViewport();
203 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
204 AlignmentI al = viewport.getAlignment();
205 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
206 Color lastColour = null;
208 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
210 final int modelNumber = pdbfnum + getModelStartNo();
211 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
213 if (mapping == null || mapping.length < 1)
218 int startPos = -1, lastPos = -1;
219 String lastChain = "";
220 for (int s = 0; s < sequence[pdbfnum].length; s++)
222 for (int sp, m = 0; m < mapping.length; m++)
224 final SequenceI seq = sequence[pdbfnum][s];
225 if (mapping[m].getSequence() == seq
226 && (sp = al.findIndex(seq)) > -1)
228 SequenceI asp = al.getSequenceAt(sp);
229 for (int r = 0; r < asp.getLength(); r++)
231 // no mapping to gaps in sequence
232 if (Comparison.isGap(asp.getCharAt(r)))
236 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
238 if (pos < 1 || pos == lastPos)
243 Color colour = sr.getResidueColour(seq, r, finder);
246 * darker colour for hidden regions
248 if (!cs.isVisible(r))
253 final String chain = mapping[m].getChain();
256 * Just keep incrementing the end position for this colour range
257 * _unless_ colour, PDB model or chain has changed, or there is a
258 * gap in the mapped residue sequence
260 final boolean newColour = !colour.equals(lastColour);
261 final boolean nonContig = lastPos + 1 != pos;
262 final boolean newChain = !chain.equals(lastChain);
263 if (newColour || nonContig || newChain)
267 addAtomSpecRange(colourMap, lastColour, modelNumber,
268 startPos, lastPos, lastChain);
276 // final colour range
277 if (lastColour != null)
279 addAtomSpecRange(colourMap, lastColour, modelNumber, startPos,
291 * Returns the lowest model number used by the structure viewer
295 protected static int getModelStartNo()
301 * Helper method to add one contiguous range to the AtomSpec model for the given
302 * value (creating the model if necessary). As used by Jalview, {@code value} is
304 * <li>a colour, when building a 'colour structure by sequence' command</li>
305 * <li>a feature value, when building a 'set Chimera attributes from features'
316 protected static final void addAtomSpecRange(
317 Map<Object, AtomSpecModel> map,
318 Object value, int model, int startPos, int endPos, String chain)
321 * Get/initialize map of data for the colour
323 AtomSpecModel atomSpec = map.get(value);
324 if (atomSpec == null)
326 atomSpec = new AtomSpecModel();
327 map.put(value, atomSpec);
330 atomSpec.addRange(model, startPos, endPos, chain);
334 * Constructs and returns Chimera commands to set attributes on residues
335 * corresponding to features in Jalview. Attribute names are the Jalview feature
336 * type, with a "jv_" prefix.
345 public String[] setAttributesForFeatures(
346 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
347 AlignmentViewPanel viewPanel)
349 Map<String, Map<Object, AtomSpecModel>> featureMap = buildFeaturesMap(
350 ssm, files, seqs, viewPanel);
352 List<String> commands = buildSetAttributeCommands(featureMap);
354 return commands.toArray(new String[commands.size()]);
359 * Helper method to build a map of
360 * { featureType, { feature value, AtomSpecModel } }
369 protected static Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
370 StructureSelectionManager ssm, String[] files, SequenceI[][] seqs,
371 AlignmentViewPanel viewPanel)
373 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
375 FeatureRenderer fr = viewPanel.getFeatureRenderer();
381 AlignViewportI viewport = viewPanel.getAlignViewport();
382 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
385 * if alignment is showing features from complement, we also transfer
386 * these features to the corresponding mapped structure residues
388 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
389 List<String> complementFeatures = new ArrayList<>();
390 FeatureRenderer complementRenderer = null;
391 if (showLinkedFeatures)
393 AlignViewportI comp = fr.getViewport().getCodingComplement();
396 complementRenderer = Desktop.getAlignFrameFor(comp)
397 .getFeatureRenderer();
398 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
401 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
406 AlignmentI alignment = viewPanel.getAlignment();
407 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
409 final int modelNumber = pdbfnum + getModelStartNo();
410 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
412 if (mapping == null || mapping.length < 1)
417 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
419 for (int m = 0; m < mapping.length; m++)
421 final SequenceI seq = seqs[pdbfnum][seqNo];
422 int sp = alignment.findIndex(seq);
423 StructureMapping structureMapping = mapping[m];
424 if (structureMapping.getSequence() == seq && sp > -1)
427 * found a sequence with a mapping to a structure;
428 * now scan its features
430 if (!visibleFeatures.isEmpty())
432 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
433 theMap, modelNumber);
435 if (showLinkedFeatures)
437 scanComplementFeatures(complementRenderer, structureMapping,
438 seq, theMap, modelNumber);
448 * Scans visible features in mapped positions of the CDS/peptide complement, and
449 * adds any found to the map of attribute values/structure positions
451 * @param complementRenderer
452 * @param structureMapping
457 protected static void scanComplementFeatures(
458 FeatureRenderer complementRenderer,
459 StructureMapping structureMapping, SequenceI seq,
460 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
463 * for each sequence residue mapped to a structure position...
465 for (int seqPos : structureMapping.getMapping().keySet())
468 * find visible complementary features at mapped position(s)
470 MappedFeatures mf = complementRenderer
471 .findComplementFeaturesAtResidue(seq, seqPos);
474 for (SequenceFeature sf : mf.features)
476 String type = sf.getType();
479 * Don't copy features which originated from Chimera
481 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
482 .equals(sf.getFeatureGroup()))
488 * record feature 'value' (score/description/type) as at the
489 * corresponding structure position
491 List<int[]> mappedRanges = structureMapping
492 .getPDBResNumRanges(seqPos, seqPos);
494 if (!mappedRanges.isEmpty())
496 String value = sf.getDescription();
497 if (value == null || value.length() == 0)
501 float score = sf.getScore();
502 if (score != 0f && !Float.isNaN(score))
504 value = Float.toString(score);
506 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
507 if (featureValues == null)
509 featureValues = new HashMap<>();
510 theMap.put(type, featureValues);
512 for (int[] range : mappedRanges)
514 addAtomSpecRange(featureValues, value, modelNumber, range[0],
515 range[1], structureMapping.getChain());
524 * Inspect features on the sequence; for each feature that is visible, determine
525 * its mapped ranges in the structure (if any) according to the given mapping,
526 * and add them to the map.
528 * @param visibleFeatures
534 protected static void scanSequenceFeatures(List<String> visibleFeatures,
535 StructureMapping mapping, SequenceI seq,
536 Map<String, Map<Object, AtomSpecModel>> theMap, int modelNumber)
538 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
539 visibleFeatures.toArray(new String[visibleFeatures.size()]));
540 for (SequenceFeature sf : sfs)
542 String type = sf.getType();
545 * Don't copy features which originated from Chimera
547 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
548 .equals(sf.getFeatureGroup()))
553 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
556 if (!mappedRanges.isEmpty())
558 String value = sf.getDescription();
559 if (value == null || value.length() == 0)
563 float score = sf.getScore();
564 if (score != 0f && !Float.isNaN(score))
566 value = Float.toString(score);
568 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
569 if (featureValues == null)
571 featureValues = new HashMap<>();
572 theMap.put(type, featureValues);
574 for (int[] range : mappedRanges)
576 addAtomSpecRange(featureValues, value, modelNumber, range[0],
577 range[1], mapping.getChain());
584 * Traverse the map of features/values/models/chains/positions to construct a
585 * list of 'setattr' commands (one per distinct feature type and value).
587 * The format of each command is
590 * <blockquote> setattr r <featureName> " " #modelnumber:range.chain
591 * e.g. setattr r jv_chain <value> #0:2.B,4.B,9-12.B|#1:1.A,2-6.A,...
598 protected List<String> buildSetAttributeCommands(
599 Map<String, Map<Object, AtomSpecModel>> featureMap)
601 List<String> commands = new ArrayList<>();
602 for (String featureType : featureMap.keySet())
604 String attributeName = makeAttributeName(featureType);
607 * clear down existing attributes for this feature
609 // 'problem' - sets attribute to None on all residues - overkill?
610 // commands.add("~setattr r " + attributeName + " :*");
612 Map<Object, AtomSpecModel> values = featureMap.get(featureType);
613 for (Object value : values.keySet())
616 * for each distinct value recorded for this feature type,
617 * add a command to set the attribute on the mapped residues
618 * Put values in single quotes, encoding any embedded single quotes
620 AtomSpecModel atomSpecModel = values.get(value);
621 String featureValue = value.toString();
622 featureValue = featureValue.replaceAll("\\'", "'");
623 String cmd = getSetAttributeCommand(attributeName, featureValue,
633 * Returns a viewer command to set the given residue attribute value on
634 * residues specified by the AtomSpecModel, for example
637 * setatr res jv_chain 'primary' #1:12-34,48-55.B
640 * @param attributeName
641 * @param attributeValue
642 * @param atomSpecModel
645 protected String getSetAttributeCommand(String attributeName,
646 String attributeValue,
647 AtomSpecModel atomSpecModel)
649 StringBuilder sb = new StringBuilder(128);
650 sb.append("setattr res ").append(attributeName).append(" '")
651 .append(attributeValue).append("' ");
652 sb.append(atomSpecModel.getAtomSpec());
653 return sb.toString();
657 * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
658 * for a 'Jalview' namespace, and any non-alphanumeric character is converted
663 * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
665 protected static String makeAttributeName(String featureType)
667 StringBuilder sb = new StringBuilder();
668 if (featureType != null)
670 for (char c : featureType.toCharArray())
672 sb.append(Character.isLetterOrDigit(c) ? c : '_');
675 String attName = NAMESPACE_PREFIX + sb.toString();
678 * Chimera treats an attribute name ending in 'color' as colour-valued;
679 * Jalview doesn't, so prevent this by appending an underscore
681 if (attName.toUpperCase().endsWith("COLOR"))
690 public String colourByChain()
692 return CMD_COLOUR_BY_CHAIN;
696 public String colourByCharge()
698 return CMD_COLOUR_BY_CHARGE;
702 public String colourByResidues(Map<String, Color> colours)
704 StringBuilder cmd = new StringBuilder(12 * colours.size());
707 * concatenate commands like
708 * color #4949b6 ::VAL
710 for (Entry<String, Color> entry : colours.entrySet())
712 String colorSpec = ColorUtils.toTkCode(entry.getValue());
713 String resCode = entry.getKey();
714 cmd.append("color ").append(colorSpec).append(" ::").append(resCode)
715 .append(CMD_SEPARATOR);
717 return cmd.toString();
721 public String setBackgroundColour(Color col)
723 return "set bgColor " + ColorUtils.toTkCode(col);
727 public String focusView()
733 public String showChains(List<String> toShow)
736 * Construct a chimera command like
738 * ~display #*;~ribbon #*;ribbon :.A,:.B
740 StringBuilder cmd = new StringBuilder(64);
741 boolean first = true;
742 for (String chain : toShow)
744 String[] tokens = chain.split(":");
745 if (tokens.length == 2)
747 String showChainCmd = tokens[0] + ":." + tokens[1];
752 cmd.append(showChainCmd);
758 * could append ";focus" to this command to resize the display to fill the
759 * window, but it looks more helpful not to (easier to relate chains to the
762 final String command = "~display #*; ~ribbon #*; ribbon :"