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.io.StructureFile;
36 import jalview.renderer.seqfeatures.FeatureColourFinder;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.schemes.ResidueProperties;
39 import jalview.structure.AtomSpec;
40 import jalview.structure.AtomSpecModel;
41 import jalview.structure.StructureCommandI;
42 import jalview.structure.StructureCommandsI;
43 import jalview.structure.StructureListener;
44 import jalview.structure.StructureMapping;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.util.Comparison;
47 import jalview.util.MessageManager;
49 import java.awt.Color;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.BitSet;
53 import java.util.HashMap;
54 import java.util.LinkedHashMap;
55 import java.util.List;
58 import javax.swing.SwingUtilities;
62 * A base class to hold common function for protein structure model binding.
63 * Initial version created by refactoring JMol and Chimera binding models, but
64 * other structure viewers could in principle be accommodated in future.
69 public abstract class AAStructureBindingModel
70 extends SequenceStructureBindingModel
71 implements StructureListener, StructureSelectionManagerProvider
74 * Data bean class to simplify parameterisation in superposeStructures
76 public static class SuperposeData
78 public String filename;
82 public String chain = "";
87 * The pdb residue number (if any) mapped to columns of the alignment
89 public int[] pdbResNo; // or use SparseIntArray?
91 public String modelId;
97 * width of alignment (number of columns that may potentially
98 * participate in superposition)
100 * structure viewer model number
102 public SuperposeData(int width, String model)
104 pdbResNo = new int[width];
109 private static final int MIN_POS_TO_SUPERPOSE = 4;
111 private static final String COLOURING_STRUCTURES = MessageManager
112 .getString("status.colouring_structures");
115 * the Jalview panel through which the user interacts
116 * with the structure viewer
118 private JalviewStructureDisplayI viewer;
121 * helper that generates command syntax
123 private StructureCommandsI commandGenerator;
125 private StructureSelectionManager ssm;
128 * modelled chains, formatted as "pdbid:chainCode"
130 private List<String> chainNames;
133 * lookup of pdb file name by key "pdbid:chainCode"
135 private Map<String, String> chainFile;
138 * distinct PDB entries (pdb files) associated
141 private PDBEntry[] pdbEntry;
144 * sequences mapped to each pdbentry
146 private SequenceI[][] sequence;
149 * array of target chains for sequences - tied to pdbentry and sequence[]
151 private String[][] chains;
154 * datasource protocol for access to PDBEntrylatest
156 DataSourceType protocol = null;
158 protected boolean colourBySequence = true;
160 private boolean nucleotide;
162 private boolean finishedInit = false;
165 * current set of model filenames loaded in the viewer
167 protected String[] modelFileNames = null;
169 public String fileLoadingError;
177 public AAStructureBindingModel(StructureSelectionManager ssm,
181 this.sequence = seqs;
182 chainNames = new ArrayList<>();
183 chainFile = new HashMap<>();
194 public AAStructureBindingModel(StructureSelectionManager ssm,
195 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
196 DataSourceType protocol)
198 this(ssm, sequenceIs);
199 this.nucleotide = Comparison.isNucleotide(sequenceIs);
200 this.pdbEntry = pdbentry;
201 this.protocol = protocol;
205 private boolean resolveChains()
208 * final count of chain mappings discovered
211 // JBPNote: JAL-2693 - this should be a list of chain mappings per
212 // [pdbentry][sequence]
213 String[][] newchains = new String[pdbEntry.length][];
215 for (PDBEntry pdb : pdbEntry)
217 SequenceI[] seqsForPdb = sequence[pe];
218 if (seqsForPdb != null)
220 newchains[pe] = new String[seqsForPdb.length];
222 for (SequenceI asq : seqsForPdb)
224 String chain = (chains != null && chains[pe] != null)
227 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
228 : asq.getDatasetSequence();
229 if (sq.getAllPDBEntries() != null)
231 for (PDBEntry pdbentry : sq.getAllPDBEntries())
233 if (pdb.getFile() != null && pdbentry.getFile() != null
234 && pdb.getFile().equals(pdbentry.getFile()))
236 String chaincode = pdbentry.getChainCode();
237 if (chaincode != null && chaincode.length() > 0)
246 newchains[pe][se] = chain;
254 return chainmaps > 0;
256 public StructureSelectionManager getSsm()
262 * Returns the i'th PDBEntry (or null)
267 public PDBEntry getPdbEntry(int i)
269 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
273 * Answers true if this binding includes the given PDB id, else false
278 public boolean hasPdbId(String pdbId)
280 if (pdbEntry != null)
282 for (PDBEntry pdb : pdbEntry)
284 if (pdb.getId().equals(pdbId))
294 * Returns the number of modelled PDB file entries.
298 public int getPdbCount()
300 return pdbEntry == null ? 0 : pdbEntry.length;
303 public SequenceI[][] getSequence()
308 public String[][] getChains()
313 public DataSourceType getProtocol()
318 // TODO may remove this if calling methods can be pulled up here
319 protected void setPdbentry(PDBEntry[] pdbentry)
321 this.pdbEntry = pdbentry;
324 protected void setSequence(SequenceI[][] sequence)
326 this.sequence = sequence;
329 protected void setChains(String[][] chains)
331 this.chains = chains;
335 * Construct a title string for the viewer window based on the data Jalview
344 public String getViewerTitle(String viewerName, boolean verbose)
346 if (getSequence() == null || getSequence().length < 1
347 || getPdbCount() < 1 || getSequence()[0].length < 1)
349 return ("Jalview " + viewerName + " Window");
351 // TODO: give a more informative title when multiple structures are
353 StringBuilder title = new StringBuilder(64);
354 final PDBEntry pdbe = getPdbEntry(0);
355 title.append(viewerName + " view for " + getSequence()[0][0].getName()
356 + ":" + pdbe.getId());
360 String method = (String) pdbe.getProperty("method");
363 title.append(" Method: ").append(method);
365 String chain = (String) pdbe.getProperty("chains");
368 title.append(" Chain:").append(chain);
371 return title.toString();
375 * Called by after closeViewer is called, to release any resources and
376 * references so they can be garbage collected. Override if needed.
378 protected void releaseUIResources()
383 public void releaseReferences(Object svl)
387 public boolean isColourBySequence()
389 return colourBySequence;
393 * Called when the binding thinks the UI needs to be refreshed after a
394 * structure viewer state change. This could be because structures were
395 * loaded, or because an error has occurred. Default does nothing, override as
398 public void refreshGUI()
403 * Instruct the Jalview binding to update the pdbentries vector if necessary
404 * prior to matching the jmol view's contents to the list of structure files
405 * Jalview knows about. By default does nothing, override as required.
407 public void refreshPdbEntries()
411 public void setColourBySequence(boolean colourBySequence)
413 this.colourBySequence = colourBySequence;
416 protected void addSequenceAndChain(int pe, SequenceI[] seq,
419 if (pe < 0 || pe >= getPdbCount())
421 throw new Error(MessageManager.formatMessage(
422 "error.implementation_error_no_pdbentry_from_index",
424 { Integer.valueOf(pe).toString() }));
426 final String nullChain = "TheNullChain";
427 List<SequenceI> s = new ArrayList<>();
428 List<String> c = new ArrayList<>();
429 if (getChains() == null)
431 setChains(new String[getPdbCount()][]);
433 if (getSequence()[pe] != null)
435 for (int i = 0; i < getSequence()[pe].length; i++)
437 s.add(getSequence()[pe][i]);
438 if (getChains()[pe] != null)
440 if (i < getChains()[pe].length)
442 c.add(getChains()[pe][i]);
451 if (tchain != null && tchain.length > 0)
458 for (int i = 0; i < seq.length; i++)
460 if (!s.contains(seq[i]))
463 if (tchain != null && i < tchain.length)
465 c.add(tchain[i] == null ? nullChain : tchain[i]);
469 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
470 getSequence()[pe] = tmp;
473 String[] tch = c.toArray(new String[c.size()]);
474 for (int i = 0; i < tch.length; i++)
476 if (tch[i] == nullChain)
481 getChains()[pe] = tch;
485 getChains()[pe] = null;
490 * add structures and any known sequence associations
492 * @returns the pdb entries added to the current set.
494 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
495 SequenceI[][] seq, String[][] chns)
497 List<PDBEntry> v = new ArrayList<>();
498 List<int[]> rtn = new ArrayList<>();
499 for (int i = 0; i < getPdbCount(); i++)
501 v.add(getPdbEntry(i));
503 for (int i = 0; i < pdbe.length; i++)
505 int r = v.indexOf(pdbe[i]);
506 if (r == -1 || r >= getPdbCount())
508 rtn.add(new int[] { v.size(), i });
513 // just make sure the sequence/chain entries are all up to date
514 addSequenceAndChain(r, seq[i], chns[i]);
517 pdbe = v.toArray(new PDBEntry[v.size()]);
521 // expand the tied sequence[] and string[] arrays
522 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
523 String[][] sch = new String[getPdbCount()][];
524 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
525 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
528 pdbe = new PDBEntry[rtn.size()];
529 for (int r = 0; r < pdbe.length; r++)
531 int[] stri = (rtn.get(r));
532 // record the pdb file as a new addition
533 pdbe[r] = getPdbEntry(stri[0]);
534 // and add the new sequence/chain entries
535 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
546 * Add sequences to the pe'th pdbentry's sequence set.
551 public void addSequence(int pe, SequenceI[] seq)
553 addSequenceAndChain(pe, seq, null);
557 * add the given sequences to the mapping scope for the given pdb file handle
560 * - pdbFile identifier
562 * - set of sequences it can be mapped to
564 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
566 for (int pe = 0; pe < getPdbCount(); pe++)
568 if (getPdbEntry(pe).getFile().equals(pdbFile))
570 addSequence(pe, seq);
576 public abstract void highlightAtoms(List<AtomSpec> atoms);
578 protected boolean isNucleotide()
580 return this.nucleotide;
584 * Returns a readable description of all mappings for the wrapped pdbfile to
585 * any mapped sequences
591 public String printMappings()
593 if (pdbEntry == null)
597 StringBuilder sb = new StringBuilder(128);
598 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
600 String pdbfile = getPdbEntry(pdbe).getFile();
601 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
602 sb.append(getSsm().printMappings(pdbfile, seqs));
604 return sb.toString();
608 * Returns the mapped structure position for a given aligned column of a given
609 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
610 * not mapped to structure.
617 protected int getMappedPosition(SequenceI seq, int alignedPos,
618 StructureMapping mapping)
620 if (alignedPos >= seq.getLength())
625 if (Comparison.isGap(seq.getCharAt(alignedPos)))
629 int seqPos = seq.findPosition(alignedPos);
630 int pos = mapping.getPDBResNum(seqPos);
635 * Helper method to identify residues that can participate in a structure
636 * superposition command. For each structure, identify a sequence in the
637 * alignment which is mapped to the structure. Identify non-gapped columns in
638 * the sequence which have a mapping to a residue in the structure. Returns
639 * the index of the first structure that has a mapping to the alignment.
642 * the sequence alignment which is the basis of structure
645 * a BitSet, where bit j is set to indicate that every structure has
646 * a mapped residue present in column j (so the column can
647 * participate in structure alignment)
649 * an array of data beans corresponding to pdb file index
652 protected int findSuperposableResidues(AlignmentI alignment,
653 BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
655 int refStructure = -1;
656 String[] files = getStructureFiles();
661 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
663 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
667 * Find the first mapped sequence (if any) for this PDB entry which is in
670 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
671 for (int s = 0; s < seqCountForPdbFile; s++)
673 for (StructureMapping mapping : mappings)
675 final SequenceI theSequence = getSequence()[pdbfnum][s];
676 if (mapping.getSequence() == theSequence
677 && alignment.findIndex(theSequence) > -1)
679 if (refStructure < 0)
681 refStructure = pdbfnum;
683 for (int r = 0; r < alignment.getWidth(); r++)
689 int pos = getMappedPosition(theSequence, r, mapping);
690 if (pos < 1 || pos == lastPos)
696 structures[pdbfnum].pdbResNo[r] = pos;
698 String chain = mapping.getChain();
699 if (chain != null && chain.trim().length() > 0)
701 structures[pdbfnum].chain = chain;
703 structures[pdbfnum].pdbId = mapping.getPdbId();
704 structures[pdbfnum].isRna = theSequence.getRNA() != null;
707 * move on to next pdb file (ignore sequences for other chains
708 * for the same structure)
710 s = seqCountForPdbFile;
711 break; // fixme break out of two loops here!
720 * Returns true if the structure viewer has loaded all of the files of
721 * interest (identified by the file mapping having been set up), or false if
722 * any are still not loaded after a timeout interval.
726 protected boolean waitForFileLoad(String[] files)
729 * give up after 10 secs plus 1 sec per file
731 long starttime = System.currentTimeMillis();
732 long endTime = 10000 + 1000 * files.length + starttime;
733 String notLoaded = null;
735 boolean waiting = true;
736 while (waiting && System.currentTimeMillis() < endTime)
739 for (String file : files)
748 StructureMapping[] sm = getSsm().getMapping(file);
749 if (sm == null || sm.length == 0)
753 } catch (Throwable x)
763 "Timed out waiting for structure viewer to load file "
771 public boolean isListeningFor(SequenceI seq)
773 if (sequence != null)
775 for (SequenceI[] seqs : sequence)
779 for (SequenceI s : seqs)
781 if (s == seq || (s.getDatasetSequence() != null
782 && s.getDatasetSequence() == seq.getDatasetSequence()))
793 public boolean isFinishedInit()
798 public void setFinishedInit(boolean fi)
800 this.finishedInit = fi;
804 * Returns a list of chains mapped in this viewer, formatted as
809 public List<String> getChainNames()
815 * Returns the Jalview panel hosting the structure viewer (if any)
819 public JalviewStructureDisplayI getViewer()
824 public void setViewer(JalviewStructureDisplayI v)
830 * Constructs and sends a command to align structures against a reference
831 * structure, based on one or more sequence alignments. May optionally return
832 * an error or warning message for the alignment command(s).
835 * an array of one or more alignment views to process
838 public String superposeStructures(List<AlignmentViewPanel> alignWith)
841 String[] files = getStructureFiles();
843 if (!waitForFileLoad(files))
849 for (AlignmentViewPanel view : alignWith)
851 AlignmentI alignment = view.getAlignment();
852 HiddenColumns hiddenCols = alignment.getHiddenColumns();
855 * 'matched' bit i will be set for visible alignment columns i where
856 * all sequences have a residue with a mapping to their PDB structure
858 BitSet matched = new BitSet();
859 final int width = alignment.getWidth();
860 for (int m = 0; m < width; m++)
862 if (hiddenCols == null || hiddenCols.isVisible(m))
868 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
869 for (int f = 0; f < files.length; f++)
871 structures[f] = new AAStructureBindingModel.SuperposeData(width,
872 getModelIdForFile(files[f]));
876 * Calculate the superposable alignment columns ('matched'), and the
877 * corresponding structure residue positions (structures.pdbResNo)
879 int refStructure = findSuperposableResidues(alignment,
880 matched, structures);
883 * require at least 4 positions to be able to execute superposition
885 int nmatched = matched.cardinality();
886 if (nmatched < MIN_POS_TO_SUPERPOSE)
888 String msg = MessageManager.formatMessage("label.insufficient_residues",
890 error += view.getViewName() + ": " + msg + "; ";
895 * get a model of the superposable residues in the reference structure
897 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
901 * Show all as backbone before doing superposition(s)
902 * (residues used for matching will be shown as ribbon)
904 // todo better way to ensure synchronous than setting getReply true!!
905 executeCommands(commandGenerator.showBackbone(), true, null);
908 * superpose each (other) structure to the reference in turn
910 for (int i = 0; i < structures.length; i++)
912 if (i != refStructure)
914 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
915 List<StructureCommandI> commands = commandGenerator
916 .superposeStructures(refAtoms,
918 List<String> replies = executeCommands(commands, true, null);
919 for (String reply : replies)
921 // return this error (Chimera only) to the user
922 if (reply.toLowerCase().contains("unequal numbers of atoms"))
924 error += "; " + reply;
934 private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
937 AtomSpecModel model = new AtomSpecModel();
938 int nextColumnMatch = matched.nextSetBit(0);
939 while (nextColumnMatch != -1)
941 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
942 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
943 superposeData.chain);
944 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
951 * returns the current sequenceRenderer that should be used to colour the
958 public abstract SequenceRenderer getSequenceRenderer(
959 AlignmentViewPanel alignment);
962 * Sends a command to the structure viewer to colour each chain with a
963 * distinct colour (to the extent supported by the viewer)
965 public void colourByChain()
967 colourBySequence = false;
969 // TODO: JAL-628 colour chains distinctly across all visible models
971 executeCommand(commandGenerator.colourByChain(), false,
972 COLOURING_STRUCTURES);
976 * Sends a command to the structure viewer to colour each chain with a
977 * distinct colour (to the extent supported by the viewer)
979 public void colourByCharge()
981 colourBySequence = false;
983 executeCommands(commandGenerator.colourByCharge(), false,
984 COLOURING_STRUCTURES);
988 * Sends a command to the structure to apply a colour scheme (defined in
989 * Jalview but not necessarily applied to the alignment), which defines a
990 * colour per residue letter. More complex schemes (e.g. that depend on
991 * consensus) cannot be used here and are ignored.
995 public void colourByJalviewColourScheme(ColourSchemeI cs)
997 colourBySequence = false;
999 if (cs == null || !cs.isSimple())
1005 * build a map of {Residue3LetterCode, Color}
1007 Map<String, Color> colours = new HashMap<>();
1008 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1010 for (String resName : residues)
1012 char res = resName.length() == 3
1013 ? ResidueProperties.getSingleCharacterCode(resName)
1014 : resName.charAt(0);
1015 Color colour = cs.findColour(res, 0, null, null, 0f);
1016 colours.put(resName, colour);
1020 * pass to the command constructor, and send the command
1022 List<StructureCommandI> cmd = commandGenerator
1023 .colourByResidues(colours);
1024 executeCommands(cmd, false, COLOURING_STRUCTURES);
1027 public void setBackgroundColour(Color col)
1029 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1030 executeCommand(cmd, false, null);
1034 * Sends one command to the structure viewer. If {@code getReply} is true, the
1035 * command is sent synchronously, otherwise in a deferred thread.
1037 * If a progress message is supplied, this is displayed before command
1038 * execution, and removed afterwards.
1045 private List<String> executeCommand(StructureCommandI cmd,
1046 boolean getReply, String msg)
1051 * synchronous (same thread) execution so reply can be returned
1053 final JalviewStructureDisplayI theViewer = getViewer();
1054 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1057 return executeCommand(cmd, getReply);
1062 theViewer.stopProgressBar(null, handle);
1069 * asynchronous (new thread) execution if no reply needed
1071 final JalviewStructureDisplayI theViewer = getViewer();
1072 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1074 SwingUtilities.invokeLater(new Runnable()
1081 executeCommand(cmd, false);
1086 theViewer.stopProgressBar(null, handle);
1096 * Execute one structure viewer command. If {@code getReply} is true, may
1097 * optionally return one or more reply messages, else returns null.
1102 protected abstract List<String> executeCommand(StructureCommandI cmd,
1106 * A helper method that converts list of commands to a vararg array
1112 private List<String> executeCommands(List<StructureCommandI> commands,
1113 boolean getReply, String msg)
1115 return executeCommands(getReply, msg,
1116 commands.toArray(new StructureCommandI[commands.size()]));
1120 * Executes one or more structure viewer commands. If a progress message is
1121 * provided, it is shown first, and removed after all commands have been run.
1128 protected List<String> executeCommands(boolean getReply, String msg,
1129 StructureCommandI[] commands)
1131 // todo: tidy this up
1134 * show progress message if specified
1136 final JalviewStructureDisplayI theViewer = getViewer();
1137 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1139 List<String> response = getReply ? new ArrayList<>() : null;
1142 for (StructureCommandI cmd : commands)
1144 List<String> replies = executeCommand(cmd, getReply, null);
1145 if (getReply && replies != null)
1147 response.addAll(replies);
1155 theViewer.stopProgressBar(null, handle);
1161 * colour any structures associated with sequences in the given alignment
1162 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
1163 * if colourBySequence is enabled.
1165 public void colourBySequence(AlignmentViewPanel alignmentv)
1167 if (!colourBySequence || !isLoadingFinished())
1171 if (getSsm() == null)
1175 String[] files = getStructureFiles();
1177 SequenceRenderer sr = getSequenceRenderer(alignmentv);
1178 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
1179 sequence, sr, alignmentv);
1181 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1182 .colourBySequence(colourMap);
1183 executeCommands(colourBySequenceCommands, false, null);
1187 * Centre the display in the structure viewer
1189 public void focusView()
1191 executeCommand(commandGenerator.focusView(), false, null);
1195 * Generates and executes a command to show only specified chains in the
1196 * structure viewer. The list of chains to show should contain entries
1197 * formatted as "pdbid:chaincode".
1201 public void showChains(List<String> toShow)
1203 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1206 * Reformat the pdbid:chainCode values as modelNo:chainCode
1207 * since this is what is needed to construct the viewer command
1208 * todo: find a less messy way to do this
1210 List<String> showThese = new ArrayList<>();
1211 for (String chainId : toShow)
1213 String[] tokens = chainId.split("\\:");
1214 if (tokens.length == 2)
1216 String pdbFile = getFileForChain(chainId);
1217 String model = getModelIdForFile(pdbFile);
1218 showThese.add(model + ":" + tokens[1]);
1221 executeCommands(commandGenerator.showChains(showThese), false, null);
1225 * Answers the structure viewer's model id given a PDB file name. Returns an
1226 * empty string if model id is not found.
1231 protected abstract String getModelIdForFile(String chainId);
1233 public boolean hasFileLoadingError()
1235 return fileLoadingError != null && fileLoadingError.length() > 0;
1239 * Returns the FeatureRenderer for the given alignment view, or null if
1240 * feature display is turned off in the view.
1245 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1247 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1249 return ap.getAlignViewport().isShowSequenceFeatures()
1250 ? ap.getFeatureRenderer()
1254 protected void setStructureCommands(StructureCommandsI cmd)
1256 commandGenerator = cmd;
1260 * Records association of one chain id (formatted as "pdbid:chainCode") with
1261 * the corresponding PDB file name
1266 public void addChainFile(String chainId, String fileName)
1268 chainFile.put(chainId, fileName);
1272 * Returns the PDB filename for the given chain id (formatted as
1273 * "pdbid:chainCode"), or null if not found
1278 protected String getFileForChain(String chainId)
1280 return chainFile.get(chainId);
1284 public void updateColours(Object source)
1286 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1287 // ignore events from panels not used to colour this view
1288 if (!getViewer().isUsedForColourBy(ap))
1292 if (!isLoadingFromArchive())
1294 colourBySequence(ap);
1298 public StructureCommandsI getCommandGenerator()
1300 return commandGenerator;
1303 protected abstract ViewerType getViewerType();
1306 * Send a structure viewer command asynchronously in a new thread. If the
1307 * progress message is not null, display this message while the command is
1311 * @param progressMsg
1313 protected void sendAsynchronousCommand(StructureCommandI command,
1316 final JalviewStructureDisplayI theViewer = getViewer();
1317 final long handle = progressMsg == null ? 0
1318 : theViewer.startProgressBar(progressMsg);
1319 SwingUtilities.invokeLater(new Runnable()
1326 executeCommand(command, false, null);
1329 if (progressMsg != null)
1331 theViewer.stopProgressBar(null, handle);
1340 * Builds a data structure which records mapped structure residues for each
1341 * colour. From this we can easily generate the viewer commands for colour by
1342 * sequence. Constructs and returns a map of {@code Color} to
1343 * {@code AtomSpecModel}, where the atomspec model holds
1351 * Ordering is by order of addition (for colours), natural ordering (for
1352 * models and chains)
1361 protected Map<Object, AtomSpecModel> buildColoursMap(
1362 StructureSelectionManager ssm, String[] files,
1363 SequenceI[][] sequence, SequenceRenderer sr, AlignmentViewPanel viewPanel)
1365 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1366 FeatureColourFinder finder = new FeatureColourFinder(fr);
1367 AlignViewportI viewport = viewPanel.getAlignViewport();
1368 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1369 AlignmentI al = viewport.getAlignment();
1370 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1371 Color lastColour = null;
1373 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1375 // todo indirect this resolution / allow override
1376 final String modelId = getModelIdForFile(files[pdbfnum]);
1377 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1379 if (mapping == null || mapping.length < 1)
1384 int startPos = -1, lastPos = -1;
1385 String lastChain = "";
1386 for (int s = 0; s < sequence[pdbfnum].length; s++)
1388 for (int sp, m = 0; m < mapping.length; m++)
1390 final SequenceI seq = sequence[pdbfnum][s];
1391 if (mapping[m].getSequence() == seq
1392 && (sp = al.findIndex(seq)) > -1)
1394 SequenceI asp = al.getSequenceAt(sp);
1395 for (int r = 0; r < asp.getLength(); r++)
1397 // no mapping to gaps in sequence
1398 if (Comparison.isGap(asp.getCharAt(r)))
1402 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1404 if (pos < 1 || pos == lastPos)
1409 Color colour = sr.getResidueColour(seq, r, finder);
1412 * darker colour for hidden regions
1414 if (!cs.isVisible(r))
1416 colour = Color.GRAY;
1419 final String chain = mapping[m].getChain();
1422 * Just keep incrementing the end position for this colour range
1423 * _unless_ colour, PDB model or chain has changed, or there is a
1424 * gap in the mapped residue sequence
1426 final boolean newColour = !colour.equals(lastColour);
1427 final boolean nonContig = lastPos + 1 != pos;
1428 final boolean newChain = !chain.equals(lastChain);
1429 if (newColour || nonContig || newChain)
1433 addAtomSpecRange(colourMap, lastColour, modelId,
1434 startPos, lastPos, lastChain);
1438 lastColour = colour;
1442 // final colour range
1443 if (lastColour != null)
1445 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1446 lastPos, lastChain);
1457 * todo better refactoring (map lookup or similar to get viewer structure id)
1463 protected String getModelId(int pdbfnum, String file)
1465 return String.valueOf(pdbfnum);
1469 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1470 * full PDB file path
1475 public void stashFoundChains(StructureFile pdb, String file)
1477 for (int i = 0; i < pdb.getChains().size(); i++)
1479 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1480 addChainFile(chid, file);
1481 getChainNames().add(chid);
1486 * Helper method to add one contiguous range to the AtomSpec model for the given
1487 * value (creating the model if necessary). As used by Jalview, {@code value} is
1489 * <li>a colour, when building a 'colour structure by sequence' command</li>
1490 * <li>a feature value, when building a 'set Chimera attributes from features'
1501 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1503 String model, int startPos, int endPos, String chain)
1506 * Get/initialize map of data for the colour
1508 AtomSpecModel atomSpec = map.get(value);
1509 if (atomSpec == null)
1511 atomSpec = new AtomSpecModel();
1512 map.put(value, atomSpec);
1515 atomSpec.addRange(model, startPos, endPos, chain);