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.structures.models;
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureRenderer;
26 import jalview.api.SequenceRenderer;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.api.structures.JalviewStructureDisplayI;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.StructureViewer.ViewerType;
34 import jalview.io.DataSourceType;
35 import jalview.renderer.seqfeatures.FeatureColourFinder;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ResidueProperties;
38 import jalview.structure.AtomSpec;
39 import jalview.structure.AtomSpecModel;
40 import jalview.structure.StructureCommandsI;
41 import jalview.structure.StructureCommandsI.SuperposeData;
42 import jalview.structure.StructureListener;
43 import jalview.structure.StructureMapping;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.util.Comparison;
46 import jalview.util.MessageManager;
48 import java.awt.Color;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.BitSet;
52 import java.util.HashMap;
53 import java.util.LinkedHashMap;
54 import java.util.List;
57 import javax.swing.SwingUtilities;
61 * A base class to hold common function for protein structure model binding.
62 * Initial version created by refactoring JMol and Chimera binding models, but
63 * other structure viewers could in principle be accommodated in future.
68 public abstract class AAStructureBindingModel
69 extends SequenceStructureBindingModel
70 implements StructureListener, StructureSelectionManagerProvider
72 private static final int MIN_POS_TO_SUPERPOSE = 4;
74 private static final String COLOURING_STRUCTURES = MessageManager
75 .getString("status.colouring_structures");
78 * the Jalview panel through which the user interacts
79 * with the structure viewer
81 private JalviewStructureDisplayI viewer;
84 * helper that generates command syntax
86 private StructureCommandsI commandGenerator;
88 private StructureSelectionManager ssm;
91 * modelled chains, formatted as "pdbid:chainCode"
93 private List<String> chainNames;
96 * lookup of pdb file name by key "pdbid:chainCode"
98 private Map<String, String> chainFile;
101 * distinct PDB entries (pdb files) associated
104 private PDBEntry[] pdbEntry;
107 * sequences mapped to each pdbentry
109 private SequenceI[][] sequence;
112 * array of target chains for sequences - tied to pdbentry and sequence[]
114 private String[][] chains;
117 * datasource protocol for access to PDBEntrylatest
119 DataSourceType protocol = null;
121 protected boolean colourBySequence = true;
123 private boolean nucleotide;
125 private boolean finishedInit = false;
128 * current set of model filenames loaded in the Jmol instance
130 protected String[] modelFileNames = null;
132 public String fileLoadingError;
140 public AAStructureBindingModel(StructureSelectionManager ssm,
144 this.sequence = seqs;
145 chainNames = new ArrayList<>();
146 chainFile = new HashMap<>();
157 public AAStructureBindingModel(StructureSelectionManager ssm,
158 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
159 DataSourceType protocol)
161 this(ssm, sequenceIs);
162 this.nucleotide = Comparison.isNucleotide(sequenceIs);
163 this.pdbEntry = pdbentry;
164 this.protocol = protocol;
168 private boolean resolveChains()
171 * final count of chain mappings discovered
174 // JBPNote: JAL-2693 - this should be a list of chain mappings per
175 // [pdbentry][sequence]
176 String[][] newchains = new String[pdbEntry.length][];
178 for (PDBEntry pdb : pdbEntry)
180 SequenceI[] seqsForPdb = sequence[pe];
181 if (seqsForPdb != null)
183 newchains[pe] = new String[seqsForPdb.length];
185 for (SequenceI asq : seqsForPdb)
187 String chain = (chains != null && chains[pe] != null)
190 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
191 : asq.getDatasetSequence();
192 if (sq.getAllPDBEntries() != null)
194 for (PDBEntry pdbentry : sq.getAllPDBEntries())
196 if (pdb.getFile() != null && pdbentry.getFile() != null
197 && pdb.getFile().equals(pdbentry.getFile()))
199 String chaincode = pdbentry.getChainCode();
200 if (chaincode != null && chaincode.length() > 0)
209 newchains[pe][se] = chain;
217 return chainmaps > 0;
219 public StructureSelectionManager getSsm()
225 * Returns the i'th PDBEntry (or null)
230 public PDBEntry getPdbEntry(int i)
232 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
236 * Answers true if this binding includes the given PDB id, else false
241 public boolean hasPdbId(String pdbId)
243 if (pdbEntry != null)
245 for (PDBEntry pdb : pdbEntry)
247 if (pdb.getId().equals(pdbId))
257 * Returns the number of modelled PDB file entries.
261 public int getPdbCount()
263 return pdbEntry == null ? 0 : pdbEntry.length;
266 public SequenceI[][] getSequence()
271 public String[][] getChains()
276 public DataSourceType getProtocol()
281 // TODO may remove this if calling methods can be pulled up here
282 protected void setPdbentry(PDBEntry[] pdbentry)
284 this.pdbEntry = pdbentry;
287 protected void setSequence(SequenceI[][] sequence)
289 this.sequence = sequence;
292 protected void setChains(String[][] chains)
294 this.chains = chains;
298 * Construct a title string for the viewer window based on the data Jalview
307 public String getViewerTitle(String viewerName, boolean verbose)
309 if (getSequence() == null || getSequence().length < 1
310 || getPdbCount() < 1 || getSequence()[0].length < 1)
312 return ("Jalview " + viewerName + " Window");
314 // TODO: give a more informative title when multiple structures are
316 StringBuilder title = new StringBuilder(64);
317 final PDBEntry pdbe = getPdbEntry(0);
318 title.append(viewerName + " view for " + getSequence()[0][0].getName()
319 + ":" + pdbe.getId());
323 String method = (String) pdbe.getProperty("method");
326 title.append(" Method: ").append(method);
328 String chain = (String) pdbe.getProperty("chains");
331 title.append(" Chain:").append(chain);
334 return title.toString();
338 * Called by after closeViewer is called, to release any resources and
339 * references so they can be garbage collected. Override if needed.
341 protected void releaseUIResources()
346 public void releaseReferences(Object svl)
350 public boolean isColourBySequence()
352 return colourBySequence;
356 * Called when the binding thinks the UI needs to be refreshed after a
357 * structure viewer state change. This could be because structures were
358 * loaded, or because an error has occurred. Default does nothing, override as
361 public void refreshGUI()
366 * Instruct the Jalview binding to update the pdbentries vector if necessary
367 * prior to matching the jmol view's contents to the list of structure files
368 * Jalview knows about. By default does nothing, override as required.
370 public void refreshPdbEntries()
374 public void setColourBySequence(boolean colourBySequence)
376 this.colourBySequence = colourBySequence;
379 protected void addSequenceAndChain(int pe, SequenceI[] seq,
382 if (pe < 0 || pe >= getPdbCount())
384 throw new Error(MessageManager.formatMessage(
385 "error.implementation_error_no_pdbentry_from_index",
387 { Integer.valueOf(pe).toString() }));
389 final String nullChain = "TheNullChain";
390 List<SequenceI> s = new ArrayList<>();
391 List<String> c = new ArrayList<>();
392 if (getChains() == null)
394 setChains(new String[getPdbCount()][]);
396 if (getSequence()[pe] != null)
398 for (int i = 0; i < getSequence()[pe].length; i++)
400 s.add(getSequence()[pe][i]);
401 if (getChains()[pe] != null)
403 if (i < getChains()[pe].length)
405 c.add(getChains()[pe][i]);
414 if (tchain != null && tchain.length > 0)
421 for (int i = 0; i < seq.length; i++)
423 if (!s.contains(seq[i]))
426 if (tchain != null && i < tchain.length)
428 c.add(tchain[i] == null ? nullChain : tchain[i]);
432 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
433 getSequence()[pe] = tmp;
436 String[] tch = c.toArray(new String[c.size()]);
437 for (int i = 0; i < tch.length; i++)
439 if (tch[i] == nullChain)
444 getChains()[pe] = tch;
448 getChains()[pe] = null;
453 * add structures and any known sequence associations
455 * @returns the pdb entries added to the current set.
457 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
458 SequenceI[][] seq, String[][] chns)
460 List<PDBEntry> v = new ArrayList<>();
461 List<int[]> rtn = new ArrayList<>();
462 for (int i = 0; i < getPdbCount(); i++)
464 v.add(getPdbEntry(i));
466 for (int i = 0; i < pdbe.length; i++)
468 int r = v.indexOf(pdbe[i]);
469 if (r == -1 || r >= getPdbCount())
471 rtn.add(new int[] { v.size(), i });
476 // just make sure the sequence/chain entries are all up to date
477 addSequenceAndChain(r, seq[i], chns[i]);
480 pdbe = v.toArray(new PDBEntry[v.size()]);
484 // expand the tied sequence[] and string[] arrays
485 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
486 String[][] sch = new String[getPdbCount()][];
487 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
488 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
491 pdbe = new PDBEntry[rtn.size()];
492 for (int r = 0; r < pdbe.length; r++)
494 int[] stri = (rtn.get(r));
495 // record the pdb file as a new addition
496 pdbe[r] = getPdbEntry(stri[0]);
497 // and add the new sequence/chain entries
498 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
509 * Add sequences to the pe'th pdbentry's sequence set.
514 public void addSequence(int pe, SequenceI[] seq)
516 addSequenceAndChain(pe, seq, null);
520 * add the given sequences to the mapping scope for the given pdb file handle
523 * - pdbFile identifier
525 * - set of sequences it can be mapped to
527 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
529 for (int pe = 0; pe < getPdbCount(); pe++)
531 if (getPdbEntry(pe).getFile().equals(pdbFile))
533 addSequence(pe, seq);
539 public abstract void highlightAtoms(List<AtomSpec> atoms);
541 protected boolean isNucleotide()
543 return this.nucleotide;
547 * Returns a readable description of all mappings for the wrapped pdbfile to
548 * any mapped sequences
554 public String printMappings()
556 if (pdbEntry == null)
560 StringBuilder sb = new StringBuilder(128);
561 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
563 String pdbfile = getPdbEntry(pdbe).getFile();
564 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
565 sb.append(getSsm().printMappings(pdbfile, seqs));
567 return sb.toString();
571 * Returns the mapped structure position for a given aligned column of a given
572 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
573 * not mapped to structure.
580 protected int getMappedPosition(SequenceI seq, int alignedPos,
581 StructureMapping mapping)
583 if (alignedPos >= seq.getLength())
588 if (Comparison.isGap(seq.getCharAt(alignedPos)))
592 int seqPos = seq.findPosition(alignedPos);
593 int pos = mapping.getPDBResNum(seqPos);
598 * Helper method to identify residues that can participate in a structure
599 * superposition command. For each structure, identify a sequence in the
600 * alignment which is mapped to the structure. Identify non-gapped columns in
601 * the sequence which have a mapping to a residue in the structure. Returns
602 * the index of the first structure that has a mapping to the alignment.
605 * the sequence alignment which is the basis of structure
608 * a BitSet, where bit j is set to indicate that every structure has
609 * a mapped residue present in column j (so the column can
610 * participate in structure alignment)
612 * an array of data beans corresponding to pdb file index
615 protected int findSuperposableResidues(AlignmentI alignment,
616 BitSet matched, SuperposeData[] structures)
618 int refStructure = -1;
619 String[] files = getStructureFiles();
624 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
626 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
630 * Find the first mapped sequence (if any) for this PDB entry which is in
633 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
634 for (int s = 0; s < seqCountForPdbFile; s++)
636 for (StructureMapping mapping : mappings)
638 final SequenceI theSequence = getSequence()[pdbfnum][s];
639 if (mapping.getSequence() == theSequence
640 && alignment.findIndex(theSequence) > -1)
642 if (refStructure < 0)
644 refStructure = pdbfnum;
646 for (int r = 0; r < alignment.getWidth(); r++)
652 int pos = getMappedPosition(theSequence, r, mapping);
653 if (pos < 1 || pos == lastPos)
659 structures[pdbfnum].pdbResNo[r] = pos;
661 String chain = mapping.getChain();
662 if (chain != null && chain.trim().length() > 0)
664 structures[pdbfnum].chain = chain;
666 structures[pdbfnum].pdbId = mapping.getPdbId();
667 structures[pdbfnum].isRna = theSequence.getRNA() != null;
670 * move on to next pdb file (ignore sequences for other chains
671 * for the same structure)
673 s = seqCountForPdbFile;
674 break; // fixme break out of two loops here!
683 * Returns true if the structure viewer has loaded all of the files of
684 * interest (identified by the file mapping having been set up), or false if
685 * any are still not loaded after a timeout interval.
689 protected boolean waitForFileLoad(String[] files)
692 * give up after 10 secs plus 1 sec per file
694 long starttime = System.currentTimeMillis();
695 long endTime = 10000 + 1000 * files.length + starttime;
696 String notLoaded = null;
698 boolean waiting = true;
699 while (waiting && System.currentTimeMillis() < endTime)
702 for (String file : files)
711 StructureMapping[] sm = getSsm().getMapping(file);
712 if (sm == null || sm.length == 0)
716 } catch (Throwable x)
726 "Timed out waiting for structure viewer to load file "
734 public boolean isListeningFor(SequenceI seq)
736 if (sequence != null)
738 for (SequenceI[] seqs : sequence)
742 for (SequenceI s : seqs)
744 if (s == seq || (s.getDatasetSequence() != null
745 && s.getDatasetSequence() == seq.getDatasetSequence()))
756 public boolean isFinishedInit()
761 public void setFinishedInit(boolean fi)
763 this.finishedInit = fi;
767 * Returns a list of chains mapped in this viewer, formatted as
772 public List<String> getChainNames()
778 * Returns the Jalview panel hosting the structure viewer (if any)
782 public JalviewStructureDisplayI getViewer()
787 public void setViewer(JalviewStructureDisplayI v)
793 * Constructs and sends a command to align structures against a reference
794 * structure, based on one or more sequence alignments. May optionally return
795 * an error or warning message for the alignment command(s).
798 * an array of one or more alignment views to process
801 public String superposeStructures(List<AlignmentViewPanel> alignWith)
804 String[] files = getStructureFiles();
806 if (!waitForFileLoad(files))
812 for (AlignmentViewPanel view : alignWith)
814 AlignmentI alignment = view.getAlignment();
815 HiddenColumns hiddenCols = alignment.getHiddenColumns();
818 * 'matched' bit i will be set for visible alignment columns i where
819 * all sequences have a residue with a mapping to their PDB structure
821 BitSet matched = new BitSet();
822 final int width = alignment.getWidth();
823 for (int m = 0; m < width; m++)
825 if (hiddenCols == null || hiddenCols.isVisible(m))
831 SuperposeData[] structures = new SuperposeData[files.length];
832 for (int f = 0; f < files.length; f++)
834 structures[f] = new SuperposeData(width,
835 f + commandGenerator.getModelStartNo());
839 * Calculate the superposable alignment columns ('matched'), and the
840 * corresponding structure residue positions (structures.pdbResNo)
842 int refStructure = findSuperposableResidues(alignment,
843 matched, structures);
846 * require at least 4 positions to be able to execute superposition
848 int nmatched = matched.cardinality();
849 if (nmatched < MIN_POS_TO_SUPERPOSE)
851 String msg = MessageManager.formatMessage("label.insufficient_residues",
853 error += view.getViewName() + ": " + msg + "; ";
858 * get a model of the superposable residues in the reference structure
860 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
864 * Show all as backbone before doing superposition(s)
865 * (residues used for matching will be shown as ribbon)
867 executeCommand(commandGenerator.showBackbone(), false);
870 * superpose each (other) sequence to it in turn
872 for (int i = 0; i < structures.length; i++)
874 if (i != refStructure)
876 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
877 String commands = commandGenerator.superposeStructures(refAtoms,
879 List<String> replies = executeCommands(true, commands);
880 for (String reply : replies)
882 // return this error (Chimera only) to the user
883 if (reply.toLowerCase().contains("unequal numbers of atoms"))
885 error += "; " + reply;
895 private AtomSpecModel getAtomSpec(SuperposeData superposeData,
898 AtomSpecModel model = new AtomSpecModel();
899 int nextColumnMatch = matched.nextSetBit(0);
900 while (nextColumnMatch != -1)
902 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
903 model.addRange(superposeData.modelNo, pdbResNum, pdbResNum,
904 superposeData.chain);
905 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
912 * returns the current sequenceRenderer that should be used to colour the
919 public abstract SequenceRenderer getSequenceRenderer(
920 AlignmentViewPanel alignment);
923 * Sends a command to the structure viewer to colour each chain with a
924 * distinct colour (to the extent supported by the viewer)
926 public void colourByChain()
928 colourBySequence = false;
930 // TODO: JAL-628 colour chains distinctly across all visible models
932 executeCommand(commandGenerator.colourByChain(), false,
933 COLOURING_STRUCTURES);
937 * Sends a command to the structure viewer to colour each chain with a
938 * distinct colour (to the extent supported by the viewer)
940 public void colourByCharge()
942 colourBySequence = false;
944 executeCommand(commandGenerator.colourByCharge(), false,
945 COLOURING_STRUCTURES);
949 * Sends a command to the structure to apply a colour scheme (defined in
950 * Jalview but not necessarily applied to the alignment), which defines a
951 * colour per residue letter. More complex schemes (e.g. that depend on
952 * consensus) cannot be used here and are ignored.
956 public void colourByJalviewColourScheme(ColourSchemeI cs)
958 colourBySequence = false;
960 if (cs == null || !cs.isSimple())
966 * build a map of {Residue3LetterCode, Color}
968 Map<String, Color> colours = new HashMap<>();
969 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
971 for (String resName : residues)
973 char res = resName.length() == 3
974 ? ResidueProperties.getSingleCharacterCode(resName)
976 Color colour = cs.findColour(res, 0, null, null, 0f);
977 colours.put(resName, colour);
981 * pass to the command constructor, and send the command
983 String cmd = commandGenerator.colourByResidues(colours);
984 executeCommand(cmd, false, COLOURING_STRUCTURES);
987 public void setBackgroundColour(Color col)
989 String cmd = commandGenerator.setBackgroundColour(col);
990 executeCommand(cmd, false, null);
994 * Sends one command to the structure viewer. If {@code getReply} is true, the
995 * command is sent synchronously, otherwise in a deferred thread.
997 * If a progress message is supplied, this is displayed before command
998 * execution, and removed afterwards.
1005 private List<String> executeCommand(String cmd, boolean getReply,
1010 return executeSynchronous(cmd, msg, getReply);
1014 executeAsynchronous(cmd, msg);
1020 * Sends the command in the current thread. If a message is supplied, this is
1021 * shown before the thread is started, and removed when it completes. May
1022 * return a reply to the command if requested.
1029 private List<String> executeSynchronous(String cmd, String msg, boolean getReply)
1031 final JalviewStructureDisplayI theViewer = getViewer();
1032 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1035 return executeCommand(cmd, getReply);
1040 theViewer.stopProgressBar(null, handle);
1046 * Sends the command in a separate thread. If a message is supplied, this is
1047 * shown before the thread is started, and removed when it completes. No value
1053 private void executeAsynchronous(String cmd, String msg)
1055 final JalviewStructureDisplayI theViewer = getViewer();
1056 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1058 SwingUtilities.invokeLater(new Runnable()
1065 executeCommand(cmd, false);
1070 theViewer.stopProgressBar(null, handle);
1077 protected abstract List<String> executeCommand(String command,
1080 protected List<String> executeCommands(boolean getReply,
1083 // todo: tidy this up
1084 List<String> response = getReply ? new ArrayList<>() : null;
1085 for (String cmd : commands)
1087 List<String> replies = executeCommand(cmd, getReply);
1088 if (getReply && replies != null)
1090 response.addAll(replies);
1097 * colour any structures associated with sequences in the given alignment
1098 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
1099 * if colourBySequence is enabled.
1101 public void colourBySequence(AlignmentViewPanel alignmentv)
1103 if (!colourBySequence || !isLoadingFinished())
1107 if (getSsm() == null)
1111 String[] files = getStructureFiles();
1113 SequenceRenderer sr = getSequenceRenderer(alignmentv);
1114 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
1115 sequence, sr, alignmentv);
1117 String[] colourBySequenceCommands = commandGenerator
1118 .colourBySequence(colourMap);
1119 executeCommands(false, colourBySequenceCommands);
1123 * Centre the display in the structure viewer
1125 public void focusView()
1127 executeCommand(commandGenerator.focusView(), false);
1131 * Generates and executes a command to show only specified chains in the
1132 * structure viewer. The list of chains to show should contain entries
1133 * formatted as "pdbid:chaincode".
1137 public void showChains(List<String> toShow)
1139 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1142 * Reformat the pdbid:chainCode values as modelNo:chainCode
1143 * since this is what is needed to construct the viewer command
1144 * todo: find a less messy way to do this
1146 List<String> showThese = new ArrayList<>();
1147 for (String chainId : toShow)
1149 String[] tokens = chainId.split("\\:");
1150 if (tokens.length == 2)
1152 String pdbFile = getFileForChain(chainId);
1153 int modelNo = getModelNoForFile(pdbFile);
1154 String model = modelNo == -1 ? "" : String.valueOf(modelNo);
1155 showThese.add(model + ":" + tokens[1]);
1158 executeCommand(commandGenerator.showChains(showThese), false);
1162 * Answers the structure viewer's model number given a PDB file name. Returns
1163 * -1 if model number is not found.
1168 protected abstract int getModelNoForFile(String chainId);
1170 public boolean hasFileLoadingError()
1172 return fileLoadingError != null && fileLoadingError.length() > 0;
1176 * Returns the FeatureRenderer for the given alignment view, or null if
1177 * feature display is turned off in the view.
1182 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1184 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1186 return ap.getAlignViewport().isShowSequenceFeatures()
1187 ? ap.getFeatureRenderer()
1191 protected void setStructureCommands(StructureCommandsI cmd)
1193 commandGenerator = cmd;
1197 * Records association of one chain id (formatted as "pdbid:chainCode") with
1198 * the corresponding PDB file name
1203 public void addChainFile(String chainId, String fileName)
1205 chainFile.put(chainId, fileName);
1209 * Returns the PDB filename for the given chain id (formatted as
1210 * "pdbid:chainCode"), or null if not found
1215 protected String getFileForChain(String chainId)
1217 return chainFile.get(chainId);
1221 public void updateColours(Object source)
1223 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1224 // ignore events from panels not used to colour this view
1225 if (!getViewer().isUsedForColourBy(ap))
1229 if (!isLoadingFromArchive())
1231 colourBySequence(ap);
1235 public StructureCommandsI getCommandGenerator()
1237 return commandGenerator;
1240 protected abstract ViewerType getViewerType();
1243 * Send a structure viewer command asynchronously in a new thread. If the
1244 * progress message is not null, display this message while the command is
1248 * @param progressMsg
1250 protected void sendAsynchronousCommand(String command, String progressMsg)
1252 final JalviewStructureDisplayI theViewer = getViewer();
1253 final long handle = progressMsg == null ? 0
1254 : theViewer.startProgressBar(progressMsg);
1255 SwingUtilities.invokeLater(new Runnable()
1262 executeCommand(command, false);
1265 if (progressMsg != null)
1267 theViewer.stopProgressBar(null, handle);
1277 * Build a data structure which records residues for each colour.
1278 * From this we can easily generate the viewer command for colour by sequence.
1283 * Ordering is by order of addition (for colours and positions), natural ordering (for models and chains)
1293 protected Map<Object, AtomSpecModel> buildColoursMap(
1294 StructureSelectionManager ssm, String[] files,
1295 SequenceI[][] sequence, SequenceRenderer sr, AlignmentViewPanel viewPanel)
1297 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1298 FeatureColourFinder finder = new FeatureColourFinder(fr);
1299 AlignViewportI viewport = viewPanel.getAlignViewport();
1300 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1301 AlignmentI al = viewport.getAlignment();
1302 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1303 Color lastColour = null;
1305 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1307 final int modelNumber = pdbfnum + commandGenerator.getModelStartNo();
1308 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1310 if (mapping == null || mapping.length < 1)
1315 int startPos = -1, lastPos = -1;
1316 String lastChain = "";
1317 for (int s = 0; s < sequence[pdbfnum].length; s++)
1319 for (int sp, m = 0; m < mapping.length; m++)
1321 final SequenceI seq = sequence[pdbfnum][s];
1322 if (mapping[m].getSequence() == seq
1323 && (sp = al.findIndex(seq)) > -1)
1325 SequenceI asp = al.getSequenceAt(sp);
1326 for (int r = 0; r < asp.getLength(); r++)
1328 // no mapping to gaps in sequence
1329 if (Comparison.isGap(asp.getCharAt(r)))
1333 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1335 if (pos < 1 || pos == lastPos)
1340 Color colour = sr.getResidueColour(seq, r, finder);
1343 * darker colour for hidden regions
1345 if (!cs.isVisible(r))
1347 colour = Color.GRAY;
1350 final String chain = mapping[m].getChain();
1353 * Just keep incrementing the end position for this colour range
1354 * _unless_ colour, PDB model or chain has changed, or there is a
1355 * gap in the mapped residue sequence
1357 final boolean newColour = !colour.equals(lastColour);
1358 final boolean nonContig = lastPos + 1 != pos;
1359 final boolean newChain = !chain.equals(lastChain);
1360 if (newColour || nonContig || newChain)
1364 addAtomSpecRange(colourMap, lastColour, modelNumber,
1365 startPos, lastPos, lastChain);
1369 lastColour = colour;
1373 // final colour range
1374 if (lastColour != null)
1376 addAtomSpecRange(colourMap, lastColour, modelNumber, startPos,
1377 lastPos, lastChain);
1388 * Helper method to add one contiguous range to the AtomSpec model for the given
1389 * value (creating the model if necessary). As used by Jalview, {@code value} is
1391 * <li>a colour, when building a 'colour structure by sequence' command</li>
1392 * <li>a feature value, when building a 'set Chimera attributes from features'
1403 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1405 int model, int startPos, int endPos, String chain)
1408 * Get/initialize map of data for the colour
1410 AtomSpecModel atomSpec = map.get(value);
1411 if (atomSpec == null)
1413 atomSpec = new AtomSpecModel();
1414 map.put(value, atomSpec);
1417 atomSpec.addRange(model, startPos, endPos, chain);