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.ext.rbvi.chimera.AtomSpecModel;
34 import jalview.ext.rbvi.chimera.ChimeraCommands;
35 import jalview.io.DataSourceType;
36 import jalview.renderer.seqfeatures.FeatureColourFinder;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.structure.AtomSpec;
39 import jalview.structure.StructureListener;
40 import jalview.structure.StructureMapping;
41 import jalview.structure.StructureSelectionManager;
42 import jalview.util.Comparison;
43 import jalview.util.MessageManager;
45 import java.awt.Color;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.BitSet;
49 import java.util.Collections;
50 import java.util.Iterator;
51 import java.util.LinkedHashMap;
52 import java.util.List;
57 * A base class to hold common function for protein structure model binding.
58 * Initial version created by refactoring JMol and Chimera binding models, but
59 * other structure viewers could in principle be accommodated in future.
64 public abstract class AAStructureBindingModel
65 extends SequenceStructureBindingModel
66 implements StructureListener, StructureSelectionManagerProvider
69 private StructureSelectionManager ssm;
72 * distinct PDB entries (pdb files) associated
75 private PDBEntry[] pdbEntry;
78 * sequences mapped to each pdbentry
80 private SequenceI[][] sequence;
83 * array of target chains for sequences - tied to pdbentry and sequence[]
85 private String[][] chains;
88 * datasource protocol for access to PDBEntrylatest
90 DataSourceType protocol = null;
92 protected boolean colourBySequence = true;
94 private boolean nucleotide;
96 private boolean finishedInit = false;
99 * current set of model filenames loaded in the Jmol instance
101 protected String[] modelFileNames = null;
103 public String fileLoadingError;
105 private boolean showAlignmentOnly;
108 * a list of chains "pdbid:chainid" to show in the viewer;
109 * empty means show all
111 // TODO make private once deprecated JalviewJmolBinding.centerViewer removed
112 protected List<String> chainsToShow;
114 private boolean hideHiddenRegions;
116 protected List<String> chainNames = new ArrayList<>();
119 * Data bean class to simplify parameterisation in superposeStructures
121 protected class SuperposeData
124 * Constructor with alignment width argument
128 public SuperposeData(int width)
130 pdbResNo = new int[width];
133 public String filename;
137 public String chain = "";
139 public boolean isRna;
142 * The pdb residue number (if any) mapped to each column of the alignment
144 public int[] pdbResNo;
153 public AAStructureBindingModel(StructureSelectionManager ssm,
157 this.sequence = seqs;
158 chainsToShow = new ArrayList<>();
169 public AAStructureBindingModel(StructureSelectionManager ssm,
170 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
171 DataSourceType protocol)
174 this.sequence = sequenceIs;
175 this.nucleotide = Comparison.isNucleotide(sequenceIs);
176 this.pdbEntry = pdbentry;
177 this.protocol = protocol;
178 chainsToShow = new ArrayList<>();
183 private boolean resolveChains()
186 * final count of chain mappings discovered
189 // JBPNote: JAL-2693 - this should be a list of chain mappings per
190 // [pdbentry][sequence]
191 String[][] newchains = new String[pdbEntry.length][];
193 for (PDBEntry pdb : pdbEntry)
195 SequenceI[] seqsForPdb = sequence[pe];
196 if (seqsForPdb != null)
198 newchains[pe] = new String[seqsForPdb.length];
200 for (SequenceI asq : seqsForPdb)
202 String chain = (chains != null && chains[pe] != null)
205 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
206 : asq.getDatasetSequence();
207 if (sq.getAllPDBEntries() != null)
209 for (PDBEntry pdbentry : sq.getAllPDBEntries())
211 if (pdb.getFile() != null && pdbentry.getFile() != null
212 && pdb.getFile().equals(pdbentry.getFile()))
214 String chaincode = pdbentry.getChainCode();
215 if (chaincode != null && chaincode.length() > 0)
224 newchains[pe][se] = chain;
232 return chainmaps > 0;
234 public StructureSelectionManager getSsm()
240 * Returns the i'th PDBEntry (or null)
245 public PDBEntry getPdbEntry(int i)
247 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
251 * Answers true if this binding includes the given PDB id, else false
256 public boolean hasPdbId(String pdbId)
258 if (pdbEntry != null)
260 for (PDBEntry pdb : pdbEntry)
262 if (pdb.getId().equals(pdbId))
272 * Returns the number of modelled PDB file entries.
276 public int getPdbCount()
278 return pdbEntry == null ? 0 : pdbEntry.length;
281 public SequenceI[][] getSequence()
286 public String[][] getChains()
291 public DataSourceType getProtocol()
296 // TODO may remove this if calling methods can be pulled up here
297 protected void setPdbentry(PDBEntry[] pdbentry)
299 this.pdbEntry = pdbentry;
302 protected void setSequence(SequenceI[][] sequence)
304 this.sequence = sequence;
307 protected void setChains(String[][] chains)
309 this.chains = chains;
313 * Construct a title string for the viewer window based on the data Jalview
322 public String getViewerTitle(String viewerName, boolean verbose)
324 if (getSequence() == null || getSequence().length < 1
325 || getPdbCount() < 1 || getSequence()[0].length < 1)
327 return ("Jalview " + viewerName + " Window");
329 // TODO: give a more informative title when multiple structures are
331 StringBuilder title = new StringBuilder(64);
332 final PDBEntry pdbe = getPdbEntry(0);
333 title.append(viewerName + " view for " + getSequence()[0][0].getName()
334 + ":" + pdbe.getId());
338 String method = (String) pdbe.getProperty("method");
341 title.append(" Method: ").append(method);
343 String chain = (String) pdbe.getProperty("chains");
346 title.append(" Chain:").append(chain);
349 return title.toString();
353 * Called by after closeViewer is called, to release any resources and
354 * references so they can be garbage collected. Override if needed.
356 protected void releaseUIResources()
361 public boolean isColourBySequence()
363 return colourBySequence;
366 public void setColourBySequence(boolean colourBySequence)
368 this.colourBySequence = colourBySequence;
371 protected void addSequenceAndChain(int pe, SequenceI[] seq,
374 if (pe < 0 || pe >= getPdbCount())
376 throw new Error(MessageManager.formatMessage(
377 "error.implementation_error_no_pdbentry_from_index",
379 { Integer.valueOf(pe).toString() }));
381 final String nullChain = "TheNullChain";
382 List<SequenceI> s = new ArrayList<>();
383 List<String> c = new ArrayList<>();
384 if (getChains() == null)
386 setChains(new String[getPdbCount()][]);
388 if (getSequence()[pe] != null)
390 for (int i = 0; i < getSequence()[pe].length; i++)
392 s.add(getSequence()[pe][i]);
393 if (getChains()[pe] != null)
395 if (i < getChains()[pe].length)
397 c.add(getChains()[pe][i]);
406 if (tchain != null && tchain.length > 0)
413 for (int i = 0; i < seq.length; i++)
415 if (!s.contains(seq[i]))
418 if (tchain != null && i < tchain.length)
420 c.add(tchain[i] == null ? nullChain : tchain[i]);
424 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
425 getSequence()[pe] = tmp;
428 String[] tch = c.toArray(new String[c.size()]);
429 for (int i = 0; i < tch.length; i++)
431 if (tch[i] == nullChain)
436 getChains()[pe] = tch;
440 getChains()[pe] = null;
445 * add structures and any known sequence associations
447 * @returns the pdb entries added to the current set.
449 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
450 SequenceI[][] seq, String[][] chns)
452 List<PDBEntry> v = new ArrayList<>();
453 List<int[]> rtn = new ArrayList<>();
454 for (int i = 0; i < getPdbCount(); i++)
456 v.add(getPdbEntry(i));
458 for (int i = 0; i < pdbe.length; i++)
460 int r = v.indexOf(pdbe[i]);
461 if (r == -1 || r >= getPdbCount())
463 rtn.add(new int[] { v.size(), i });
468 // just make sure the sequence/chain entries are all up to date
469 addSequenceAndChain(r, seq[i], chns[i]);
472 pdbe = v.toArray(new PDBEntry[v.size()]);
476 // expand the tied sequence[] and string[] arrays
477 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
478 String[][] sch = new String[getPdbCount()][];
479 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
480 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
483 pdbe = new PDBEntry[rtn.size()];
484 for (int r = 0; r < pdbe.length; r++)
486 int[] stri = (rtn.get(r));
487 // record the pdb file as a new addition
488 pdbe[r] = getPdbEntry(stri[0]);
489 // and add the new sequence/chain entries
490 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
501 * Add sequences to the pe'th pdbentry's sequence set.
506 public void addSequence(int pe, SequenceI[] seq)
508 addSequenceAndChain(pe, seq, null);
512 * add the given sequences to the mapping scope for the given pdb file handle
515 * - pdbFile identifier
517 * - set of sequences it can be mapped to
519 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
521 for (int pe = 0; pe < getPdbCount(); pe++)
523 if (getPdbEntry(pe).getFile().equals(pdbFile))
525 addSequence(pe, seq);
531 public abstract void highlightAtoms(List<AtomSpec> atoms);
533 protected boolean isNucleotide()
535 return this.nucleotide;
539 * Returns a readable description of all mappings for the wrapped pdbfile to
540 * any mapped sequences
546 public String printMappings()
548 if (pdbEntry == null)
552 StringBuilder sb = new StringBuilder(128);
553 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
555 String pdbfile = getPdbEntry(pdbe).getFile();
556 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
557 sb.append(getSsm().printMappings(pdbfile, seqs));
559 return sb.toString();
563 * Returns the mapped structure position for a given aligned column of a given
564 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
565 * not mapped to structure.
572 protected int getMappedPosition(SequenceI seq, int alignedPos,
573 StructureMapping mapping)
575 if (alignedPos >= seq.getLength())
580 if (Comparison.isGap(seq.getCharAt(alignedPos)))
584 int seqPos = seq.findPosition(alignedPos);
585 int pos = mapping.getPDBResNum(seqPos);
590 * Helper method to identify residues that can participate in a structure
591 * superposition command. For each structure, identify a sequence in the
592 * alignment which is mapped to the structure. Identify non-gapped columns in
593 * the sequence which have a mapping to a residue in the structure. Returns
594 * the index of the first structure that has a mapping to the alignment.
597 * the sequence alignment which is the basis of structure
600 * a BitSet, where bit j is set to indicate that every structure has
601 * a mapped residue present in column j (so the column can
602 * participate in structure alignment)
604 * an array of data beans corresponding to pdb file index
607 protected int findSuperposableResidues(AlignmentI alignment,
608 BitSet matched, SuperposeData[] structures)
610 int refStructure = -1;
611 String[] files = getStructureFiles();
616 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
618 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
622 * Find the first mapped sequence (if any) for this PDB entry which is in
625 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
626 for (int s = 0; s < seqCountForPdbFile; s++)
628 for (StructureMapping mapping : mappings)
630 final SequenceI theSequence = getSequence()[pdbfnum][s];
631 if (mapping.getSequence() == theSequence
632 && alignment.findIndex(theSequence) > -1)
634 if (refStructure < 0)
636 refStructure = pdbfnum;
638 for (int r = 0; r < alignment.getWidth(); r++)
644 int pos = getMappedPosition(theSequence, r, mapping);
645 if (pos < 1 || pos == lastPos)
651 structures[pdbfnum].pdbResNo[r] = pos;
653 String chain = mapping.getChain();
654 if (chain != null && chain.trim().length() > 0)
656 structures[pdbfnum].chain = chain;
658 structures[pdbfnum].pdbId = mapping.getPdbId();
659 structures[pdbfnum].isRna = theSequence.getRNA() != null;
662 * move on to next pdb file (ignore sequences for other chains
663 * for the same structure)
665 s = seqCountForPdbFile;
675 * Returns true if the structure viewer has loaded all of the files of
676 * interest (identified by the file mapping having been set up), or false if
677 * any are still not loaded after a timeout interval.
681 protected boolean waitForFileLoad(String[] files)
684 * give up after 10 secs plus 1 sec per file
686 long starttime = System.currentTimeMillis();
687 long endTime = 10000 + 1000 * files.length + starttime;
688 String notLoaded = null;
690 boolean waiting = true;
691 while (waiting && System.currentTimeMillis() < endTime)
694 for (String file : files)
703 StructureMapping[] sm = getSsm().getMapping(file);
704 if (sm == null || sm.length == 0)
708 } catch (Throwable x)
718 "Timed out waiting for structure viewer to load file "
726 public boolean isListeningFor(SequenceI seq)
728 if (sequence != null)
730 for (SequenceI[] seqs : sequence)
734 for (SequenceI s : seqs)
736 if (s == seq || (s.getDatasetSequence() != null
737 && s.getDatasetSequence() == seq.getDatasetSequence()))
748 public boolean isFinishedInit()
753 public void setFinishedInit(boolean fi)
755 this.finishedInit = fi;
759 * Returns the Jalview panel hosting the structure viewer (if any)
763 public JalviewStructureDisplayI getViewer()
768 public abstract void setJalviewColourScheme(ColourSchemeI cs);
771 * Constructs and sends a command to align structures against a reference
772 * structure, based on one or more sequence alignments. May optionally return
773 * an error or warning message for the alignment command.
776 * an array of alignments to process
777 * @param structureIndices
778 * an array of corresponding reference structures (index into pdb
779 * file array); if a negative value is passed, the first PDB file
780 * mapped to an alignment sequence is used as the reference for
783 * an array of corresponding hidden columns for each alignment
786 public abstract String superposeStructures(AlignmentI[] alignments,
787 int[] structureIndices, HiddenColumns[] hiddenCols);
789 public abstract void setBackgroundColour(Color col);
791 protected abstract String[] getColourBySequenceCommands(
792 String[] files, AlignmentViewPanel avp);
795 * returns the current sequenceRenderer that should be used to colour the
802 public abstract SequenceRenderer getSequenceRenderer(
803 AlignmentViewPanel alignment);
805 protected abstract void colourBySequence(
806 String[] colourBySequenceCommands);
808 public abstract void colourByChain();
810 public abstract void colourByCharge();
813 * Recolours the displayed structures, if they are coloured by sequence, or
814 * 'show only visible alignment' is selected. This supports updating structure
815 * colours on either change of alignment colours, or change to the visible
816 * region of the alignment.
818 public void updateStructureColours(AlignmentViewPanel alignmentv)
820 if (!isLoadingFinished())
826 * if structure is not coloured by sequence, but restricted to the alignment,
827 * then redraw it (but don't recolour it) in case hidden regions have changed
828 * (todo: specific messaging for change of hidden region only)
830 if (!colourBySequence)
832 if (isShowAlignmentOnly())
834 showStructures(alignmentv.getAlignViewport(), false);
838 if (getSsm() == null)
842 String[] files = getStructureFiles();
844 String[] colourBySequenceCommands = getColourBySequenceCommands(
846 colourBySequence(colourBySequenceCommands);
849 public boolean hasFileLoadingError()
851 return fileLoadingError != null && fileLoadingError.length() > 0;
854 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
855 AlignmentViewPanel alignment);
858 * Sets the flag for whether only mapped visible residues in the alignment
859 * should be visible in the structure viewer
863 public void setShowAlignmentOnly(boolean b)
865 showAlignmentOnly = b;
869 * Answers true if only residues mapped to the alignment should be shown in the
870 * structure viewer, else false
874 public boolean isShowAlignmentOnly()
876 return showAlignmentOnly;
880 * Sets the flag for hiding regions of structure which are hidden in the
881 * alignment (only applies when the structure viewer is restricted to the
886 public void setHideHiddenRegions(boolean b)
888 hideHiddenRegions = b;
892 * Answers true if regions hidden in the alignment should also be hidden in the
893 * structure viewer, else false (only applies when the structure viewer is
894 * restricted to the alignment only)
898 public boolean isHideHiddenRegions()
900 return hideHiddenRegions;
904 * Shows the structures in the viewer, without changing their colouring. This is
905 * to support toggling of whether the whole structure is shown, or only residues
906 * mapped to visible regions of the alignment.
908 * @param alignViewportI
910 * if true, refit the display to the viewer
912 public void showStructures(AlignViewportI alignViewportI, boolean refocus)
914 // override with implementation
918 public void updateColours(Object source)
920 AlignmentViewPanel ap = (AlignmentViewPanel) source;
921 // ignore events from panels not used to colour this view
922 if (!getViewer().isUsedforcolourby(ap))
926 if (!isLoadingFromArchive())
928 updateStructureColours(ap);
933 * Sets the list of chains to display (as "pdbid:chain"), where an empty list
938 public void setChainsToShow(List<String> chains)
940 chainsToShow = chains;
944 * Answers true if the specified structure and chain are selected to be shown in
945 * the viewer, else false
951 protected boolean isShowChain(String pdbId, String chainId)
953 if (chainsToShow.isEmpty())
957 return chainsToShow.contains(pdbId + ":" + chainId);
961 public abstract String[] getStructureFiles();
964 * Builds a model of residues mapped from sequences to show on structure, taking
965 * into account user choices of
967 * <li>which chains are shown</li>
968 * <li>whether all structure is shown, or only that mapped to the alignment</li>
969 * <li>whether hidden regions of the alignment are hidden (excluded) or grayed
970 * out (included)</li>
976 protected AtomSpecModel getShownResidues(AlignViewportI av)
978 AlignmentI alignment = av.getAlignment();
979 final int width = alignment.getWidth();
981 String[] files = getStructureFiles();
983 AtomSpecModel model = new AtomSpecModel();
985 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
987 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
990 * Find the first mapped sequence (if any) for this PDB entry which is in
993 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
994 for (int s = 0; s < seqCountForPdbFile; s++)
996 for (StructureMapping mapping : mappings)
998 final SequenceI theSequence = getSequence()[pdbfnum][s];
999 if (mapping.getSequence() == theSequence
1000 && alignment.findIndex(theSequence) > -1)
1002 String chainCd = mapping.getChain();
1003 if (!isShowChain(mapping.getPdbId(), chainCd))
1007 Iterator<int[]> visible;
1008 if (isShowAlignmentOnly() && isHideHiddenRegions())
1010 visible = alignment.getHiddenColumns()
1011 .getVisContigsIterator(0, width, true);
1015 visible = Collections.singletonList(new int[] { 0, width })
1018 while (visible.hasNext())
1020 int[] visibleRegion = visible.next();
1021 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1022 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1023 List<int[]> residueRanges = mapping
1024 .getPDBResNumRanges(seqStartPos, seqEndPos);
1025 if (!residueRanges.isEmpty())
1027 for (int[] range : residueRanges)
1029 model.addRange(pdbfnum, range[0], range[1], chainCd);
1042 * Answers a default structure model specification which is simply the string
1043 * form of the model number. Override if needed to specify submodels.
1048 public String getModelSpec(int model)
1050 return String.valueOf(model);
1054 * Build a data structure which records contiguous subsequences for each colour.
1055 * From this we can easily generate the Chimera command for colour by sequence.
1061 * list of start/end ranges
1064 * Ordering is by order of addition (for colours and positions), natural
1065 * ordering (for models and chains)
1070 public Map<Object, AtomSpecModel> buildColoursMap(
1071 AlignmentViewPanel viewPanel)
1073 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1074 FeatureColourFinder finder = new FeatureColourFinder(fr);
1075 AlignViewportI viewport = viewPanel.getAlignViewport();
1076 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1077 AlignmentI al = viewport.getAlignment();
1078 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1079 String[] files = getStructureFiles();
1081 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1082 Color lastColour = null;
1084 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1086 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1088 if (mapping == null || mapping.length < 1)
1093 int startPos = -1, lastPos = -1;
1094 String lastChain = "";
1095 for (int s = 0; s < sequence[pdbfnum].length; s++)
1097 for (int sp, m = 0; m < mapping.length; m++)
1099 final SequenceI seq = sequence[pdbfnum][s];
1100 if (mapping[m].getSequence() == seq
1101 && (sp = al.findIndex(seq)) > -1)
1103 SequenceI asp = al.getSequenceAt(sp);
1104 for (int r = 0; r < asp.getLength(); r++)
1106 // no mapping to gaps in sequence
1107 if (Comparison.isGap(asp.getCharAt(r)))
1111 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1113 if (pos < 1 || pos == lastPos)
1118 Color colour = sr.getResidueColour(seq, r, finder);
1121 * hidden regions are shown gray or, optionally, ignored
1123 if (!cs.isVisible(r))
1125 if (hideHiddenRegions)
1131 colour = Color.GRAY;
1135 final String chain = mapping[m].getChain();
1138 * Just keep incrementing the end position for this colour range
1139 * _unless_ colour, PDB model or chain has changed, or there is a
1140 * gap in the mapped residue sequence
1142 final boolean newColour = !colour.equals(lastColour);
1143 final boolean nonContig = lastPos + 1 != pos;
1144 final boolean newChain = !chain.equals(lastChain);
1145 if (newColour || nonContig || newChain)
1149 ChimeraCommands.addAtomSpecRange(colourMap, lastColour,
1151 lastPos, lastChain);
1155 lastColour = colour;
1159 // final colour range
1160 if (lastColour != null)
1162 ChimeraCommands.addAtomSpecRange(colourMap, lastColour,
1164 startPos, lastPos, lastChain);
1175 * Returns a list of chains mapped in this viewer. Note this list is not
1176 * currently scoped per structure.
1180 public List<String> getChainNames()