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;
117 * Data bean class to simplify parameterisation in superposeStructures
119 protected class SuperposeData
122 * Constructor with alignment width argument
126 public SuperposeData(int width)
128 pdbResNo = new int[width];
131 public String filename;
135 public String chain = "";
137 public boolean isRna;
140 * The pdb residue number (if any) mapped to each column of the alignment
142 public int[] pdbResNo;
151 public AAStructureBindingModel(StructureSelectionManager ssm,
155 this.sequence = seqs;
156 chainsToShow = new ArrayList<>();
167 public AAStructureBindingModel(StructureSelectionManager ssm,
168 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
169 DataSourceType protocol)
172 this.sequence = sequenceIs;
173 this.nucleotide = Comparison.isNucleotide(sequenceIs);
174 this.pdbEntry = pdbentry;
175 this.protocol = protocol;
176 chainsToShow = new ArrayList<>();
181 private boolean resolveChains()
184 * final count of chain mappings discovered
187 // JBPNote: JAL-2693 - this should be a list of chain mappings per
188 // [pdbentry][sequence]
189 String[][] newchains = new String[pdbEntry.length][];
191 for (PDBEntry pdb : pdbEntry)
193 SequenceI[] seqsForPdb = sequence[pe];
194 if (seqsForPdb != null)
196 newchains[pe] = new String[seqsForPdb.length];
198 for (SequenceI asq : seqsForPdb)
200 String chain = (chains != null && chains[pe] != null)
203 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
204 : asq.getDatasetSequence();
205 if (sq.getAllPDBEntries() != null)
207 for (PDBEntry pdbentry : sq.getAllPDBEntries())
209 if (pdb.getFile() != null && pdbentry.getFile() != null
210 && pdb.getFile().equals(pdbentry.getFile()))
212 String chaincode = pdbentry.getChainCode();
213 if (chaincode != null && chaincode.length() > 0)
222 newchains[pe][se] = chain;
230 return chainmaps > 0;
232 public StructureSelectionManager getSsm()
238 * Returns the i'th PDBEntry (or null)
243 public PDBEntry getPdbEntry(int i)
245 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
249 * Answers true if this binding includes the given PDB id, else false
254 public boolean hasPdbId(String pdbId)
256 if (pdbEntry != null)
258 for (PDBEntry pdb : pdbEntry)
260 if (pdb.getId().equals(pdbId))
270 * Returns the number of modelled PDB file entries.
274 public int getPdbCount()
276 return pdbEntry == null ? 0 : pdbEntry.length;
279 public SequenceI[][] getSequence()
284 public String[][] getChains()
289 public DataSourceType getProtocol()
294 // TODO may remove this if calling methods can be pulled up here
295 protected void setPdbentry(PDBEntry[] pdbentry)
297 this.pdbEntry = pdbentry;
300 protected void setSequence(SequenceI[][] sequence)
302 this.sequence = sequence;
305 protected void setChains(String[][] chains)
307 this.chains = chains;
311 * Construct a title string for the viewer window based on the data Jalview
320 public String getViewerTitle(String viewerName, boolean verbose)
322 if (getSequence() == null || getSequence().length < 1
323 || getPdbCount() < 1 || getSequence()[0].length < 1)
325 return ("Jalview " + viewerName + " Window");
327 // TODO: give a more informative title when multiple structures are
329 StringBuilder title = new StringBuilder(64);
330 final PDBEntry pdbe = getPdbEntry(0);
331 title.append(viewerName + " view for " + getSequence()[0][0].getName()
332 + ":" + pdbe.getId());
336 String method = (String) pdbe.getProperty("method");
339 title.append(" Method: ").append(method);
341 String chain = (String) pdbe.getProperty("chains");
344 title.append(" Chain:").append(chain);
347 return title.toString();
351 * Called by after closeViewer is called, to release any resources and
352 * references so they can be garbage collected. Override if needed.
354 protected void releaseUIResources()
359 public boolean isColourBySequence()
361 return colourBySequence;
364 public void setColourBySequence(boolean colourBySequence)
366 this.colourBySequence = colourBySequence;
369 protected void addSequenceAndChain(int pe, SequenceI[] seq,
372 if (pe < 0 || pe >= getPdbCount())
374 throw new Error(MessageManager.formatMessage(
375 "error.implementation_error_no_pdbentry_from_index",
377 { Integer.valueOf(pe).toString() }));
379 final String nullChain = "TheNullChain";
380 List<SequenceI> s = new ArrayList<>();
381 List<String> c = new ArrayList<>();
382 if (getChains() == null)
384 setChains(new String[getPdbCount()][]);
386 if (getSequence()[pe] != null)
388 for (int i = 0; i < getSequence()[pe].length; i++)
390 s.add(getSequence()[pe][i]);
391 if (getChains()[pe] != null)
393 if (i < getChains()[pe].length)
395 c.add(getChains()[pe][i]);
404 if (tchain != null && tchain.length > 0)
411 for (int i = 0; i < seq.length; i++)
413 if (!s.contains(seq[i]))
416 if (tchain != null && i < tchain.length)
418 c.add(tchain[i] == null ? nullChain : tchain[i]);
422 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
423 getSequence()[pe] = tmp;
426 String[] tch = c.toArray(new String[c.size()]);
427 for (int i = 0; i < tch.length; i++)
429 if (tch[i] == nullChain)
434 getChains()[pe] = tch;
438 getChains()[pe] = null;
443 * add structures and any known sequence associations
445 * @returns the pdb entries added to the current set.
447 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
448 SequenceI[][] seq, String[][] chns)
450 List<PDBEntry> v = new ArrayList<>();
451 List<int[]> rtn = new ArrayList<>();
452 for (int i = 0; i < getPdbCount(); i++)
454 v.add(getPdbEntry(i));
456 for (int i = 0; i < pdbe.length; i++)
458 int r = v.indexOf(pdbe[i]);
459 if (r == -1 || r >= getPdbCount())
461 rtn.add(new int[] { v.size(), i });
466 // just make sure the sequence/chain entries are all up to date
467 addSequenceAndChain(r, seq[i], chns[i]);
470 pdbe = v.toArray(new PDBEntry[v.size()]);
474 // expand the tied sequence[] and string[] arrays
475 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
476 String[][] sch = new String[getPdbCount()][];
477 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
478 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
481 pdbe = new PDBEntry[rtn.size()];
482 for (int r = 0; r < pdbe.length; r++)
484 int[] stri = (rtn.get(r));
485 // record the pdb file as a new addition
486 pdbe[r] = getPdbEntry(stri[0]);
487 // and add the new sequence/chain entries
488 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
499 * Add sequences to the pe'th pdbentry's sequence set.
504 public void addSequence(int pe, SequenceI[] seq)
506 addSequenceAndChain(pe, seq, null);
510 * add the given sequences to the mapping scope for the given pdb file handle
513 * - pdbFile identifier
515 * - set of sequences it can be mapped to
517 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
519 for (int pe = 0; pe < getPdbCount(); pe++)
521 if (getPdbEntry(pe).getFile().equals(pdbFile))
523 addSequence(pe, seq);
529 public abstract void highlightAtoms(List<AtomSpec> atoms);
531 protected boolean isNucleotide()
533 return this.nucleotide;
537 * Returns a readable description of all mappings for the wrapped pdbfile to
538 * any mapped sequences
544 public String printMappings()
546 if (pdbEntry == null)
550 StringBuilder sb = new StringBuilder(128);
551 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
553 String pdbfile = getPdbEntry(pdbe).getFile();
554 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
555 sb.append(getSsm().printMappings(pdbfile, seqs));
557 return sb.toString();
561 * Returns the mapped structure position for a given aligned column of a given
562 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
563 * not mapped to structure.
570 protected int getMappedPosition(SequenceI seq, int alignedPos,
571 StructureMapping mapping)
573 if (alignedPos >= seq.getLength())
578 if (Comparison.isGap(seq.getCharAt(alignedPos)))
582 int seqPos = seq.findPosition(alignedPos);
583 int pos = mapping.getPDBResNum(seqPos);
588 * Helper method to identify residues that can participate in a structure
589 * superposition command. For each structure, identify a sequence in the
590 * alignment which is mapped to the structure. Identify non-gapped columns in
591 * the sequence which have a mapping to a residue in the structure. Returns
592 * the index of the first structure that has a mapping to the alignment.
595 * the sequence alignment which is the basis of structure
598 * a BitSet, where bit j is set to indicate that every structure has
599 * a mapped residue present in column j (so the column can
600 * participate in structure alignment)
602 * an array of data beans corresponding to pdb file index
605 protected int findSuperposableResidues(AlignmentI alignment,
606 BitSet matched, SuperposeData[] structures)
608 int refStructure = -1;
609 String[] files = getStructureFiles();
614 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
616 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
620 * Find the first mapped sequence (if any) for this PDB entry which is in
623 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
624 for (int s = 0; s < seqCountForPdbFile; s++)
626 for (StructureMapping mapping : mappings)
628 final SequenceI theSequence = getSequence()[pdbfnum][s];
629 if (mapping.getSequence() == theSequence
630 && alignment.findIndex(theSequence) > -1)
632 if (refStructure < 0)
634 refStructure = pdbfnum;
636 for (int r = 0; r < alignment.getWidth(); r++)
642 int pos = getMappedPosition(theSequence, r, mapping);
643 if (pos < 1 || pos == lastPos)
649 structures[pdbfnum].pdbResNo[r] = pos;
651 String chain = mapping.getChain();
652 if (chain != null && chain.trim().length() > 0)
654 structures[pdbfnum].chain = chain;
656 structures[pdbfnum].pdbId = mapping.getPdbId();
657 structures[pdbfnum].isRna = theSequence.getRNA() != null;
660 * move on to next pdb file (ignore sequences for other chains
661 * for the same structure)
663 s = seqCountForPdbFile;
673 * Returns true if the structure viewer has loaded all of the files of
674 * interest (identified by the file mapping having been set up), or false if
675 * any are still not loaded after a timeout interval.
679 protected boolean waitForFileLoad(String[] files)
682 * give up after 10 secs plus 1 sec per file
684 long starttime = System.currentTimeMillis();
685 long endTime = 10000 + 1000 * files.length + starttime;
686 String notLoaded = null;
688 boolean waiting = true;
689 while (waiting && System.currentTimeMillis() < endTime)
692 for (String file : files)
701 StructureMapping[] sm = getSsm().getMapping(file);
702 if (sm == null || sm.length == 0)
706 } catch (Throwable x)
716 "Timed out waiting for structure viewer to load file "
724 public boolean isListeningFor(SequenceI seq)
726 if (sequence != null)
728 for (SequenceI[] seqs : sequence)
732 for (SequenceI s : seqs)
734 if (s == seq || (s.getDatasetSequence() != null
735 && s.getDatasetSequence() == seq.getDatasetSequence()))
746 public boolean isFinishedInit()
751 public void setFinishedInit(boolean fi)
753 this.finishedInit = fi;
757 * Returns a list of chains mapped in this viewer.
761 public abstract List<String> getChainNames();
764 * Returns the Jalview panel hosting the structure viewer (if any)
768 public JalviewStructureDisplayI getViewer()
773 public abstract void setJalviewColourScheme(ColourSchemeI cs);
776 * Constructs and sends a command to align structures against a reference
777 * structure, based on one or more sequence alignments. May optionally return
778 * an error or warning message for the alignment command.
781 * an array of alignments to process
782 * @param structureIndices
783 * an array of corresponding reference structures (index into pdb
784 * file array); if a negative value is passed, the first PDB file
785 * mapped to an alignment sequence is used as the reference for
788 * an array of corresponding hidden columns for each alignment
791 public abstract String superposeStructures(AlignmentI[] alignments,
792 int[] structureIndices, HiddenColumns[] hiddenCols);
794 public abstract void setBackgroundColour(Color col);
796 protected abstract String[] getColourBySequenceCommands(
797 String[] files, AlignmentViewPanel avp);
800 * returns the current sequenceRenderer that should be used to colour the
807 public abstract SequenceRenderer getSequenceRenderer(
808 AlignmentViewPanel alignment);
810 protected abstract void colourBySequence(
811 String[] colourBySequenceCommands);
813 public abstract void colourByChain();
815 public abstract void colourByCharge();
818 * Recolours the displayed structures, if they are coloured by sequence, or
819 * 'show only visible alignment' is selected. This supports updating structure
820 * colours on either change of alignment colours, or change to the visible
821 * region of the alignment.
823 public void updateStructureColours(AlignmentViewPanel alignmentv)
825 if (!isLoadingFinished())
831 * if structure is not coloured by sequence, but restricted to the alignment,
832 * then redraw it (but don't recolour it) in case hidden regions have changed
833 * (todo: specific messaging for change of hidden region only)
835 if (!colourBySequence)
837 if (isShowAlignmentOnly())
839 showStructures(alignmentv.getAlignViewport(), false);
843 if (getSsm() == null)
847 String[] files = getStructureFiles();
849 String[] colourBySequenceCommands = getColourBySequenceCommands(
851 colourBySequence(colourBySequenceCommands);
854 public boolean hasFileLoadingError()
856 return fileLoadingError != null && fileLoadingError.length() > 0;
859 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
860 AlignmentViewPanel alignment);
863 * Sets the flag for whether only mapped visible residues in the alignment
864 * should be visible in the structure viewer
868 public void setShowAlignmentOnly(boolean b)
870 showAlignmentOnly = b;
874 * Answers true if only residues mapped to the alignment should be shown in the
875 * structure viewer, else false
879 public boolean isShowAlignmentOnly()
881 return showAlignmentOnly;
885 * Sets the flag for hiding regions of structure which are hidden in the
886 * alignment (only applies when the structure viewer is restricted to the
891 public void setHideHiddenRegions(boolean b)
893 hideHiddenRegions = b;
897 * Answers true if regions hidden in the alignment should also be hidden in the
898 * structure viewer, else false (only applies when the structure viewer is
899 * restricted to the alignment only)
903 public boolean isHideHiddenRegions()
905 return hideHiddenRegions;
909 * Shows the structures in the viewer, without changing their colouring. This is
910 * to support toggling of whether the whole structure is shown, or only residues
911 * mapped to visible regions of the alignment.
913 * @param alignViewportI
915 * if true, refit the display to the viewer
917 public void showStructures(AlignViewportI alignViewportI, boolean refocus)
919 // override with implementation
923 public void updateColours(Object source)
925 AlignmentViewPanel ap = (AlignmentViewPanel) source;
926 // ignore events from panels not used to colour this view
927 if (!getViewer().isUsedforcolourby(ap))
931 if (!isLoadingFromArchive())
933 updateStructureColours(ap);
938 * Sets the list of chains to display (as "pdbid:chain"), where an empty list
943 public void setChainsToShow(List<String> chains)
945 chainsToShow = chains;
949 * Answers true if the specified structure and chain are selected to be shown in
950 * the viewer, else false
956 protected boolean isShowChain(String pdbId, String chainId)
958 if (chainsToShow.isEmpty())
962 return chainsToShow.contains(pdbId + ":" + chainId);
966 public abstract String[] getStructureFiles();
969 * Builds a model of residues mapped from sequences to show on structure, taking
970 * into account user choices of
972 * <li>which chains are shown</li>
973 * <li>whether all structure is shown, or only that mapped to the alignment</li>
974 * <li>whether hidden regions of the alignment are hidden (excluded) or grayed
975 * out (included)</li>
981 protected AtomSpecModel getShownResidues(AlignViewportI av)
983 AlignmentI alignment = av.getAlignment();
984 final int width = alignment.getWidth();
986 String[] files = getStructureFiles();
988 AtomSpecModel model = new AtomSpecModel();
990 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
992 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
995 * Find the first mapped sequence (if any) for this PDB entry which is in
998 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
999 for (int s = 0; s < seqCountForPdbFile; s++)
1001 for (StructureMapping mapping : mappings)
1003 final SequenceI theSequence = getSequence()[pdbfnum][s];
1004 if (mapping.getSequence() == theSequence
1005 && alignment.findIndex(theSequence) > -1)
1007 String chainCd = mapping.getChain();
1008 if (!isShowChain(mapping.getPdbId(), chainCd))
1012 Iterator<int[]> visible;
1013 if (isShowAlignmentOnly() && isHideHiddenRegions())
1015 visible = alignment.getHiddenColumns()
1016 .getVisContigsIterator(0, width, true);
1020 visible = Collections.singletonList(new int[] { 0, width })
1023 while (visible.hasNext())
1025 int[] visibleRegion = visible.next();
1026 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1027 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1028 List<int[]> residueRanges = mapping
1029 .getPDBResNumRanges(seqStartPos, seqEndPos);
1030 if (!residueRanges.isEmpty())
1032 for (int[] range : residueRanges)
1034 model.addRange(pdbfnum, range[0], range[1], chainCd);
1047 * Answers a default structure model specification which is simply the string
1048 * form of the model number. Override if needed to specify submodels.
1053 public String getModelSpec(int model)
1055 return String.valueOf(model);
1059 * Build a data structure which records contiguous subsequences for each colour.
1060 * From this we can easily generate the Chimera command for colour by sequence.
1066 * list of start/end ranges
1069 * Ordering is by order of addition (for colours and positions), natural
1070 * ordering (for models and chains)
1075 public Map<Object, AtomSpecModel> buildColoursMap(
1076 AlignmentViewPanel viewPanel)
1078 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1079 FeatureColourFinder finder = new FeatureColourFinder(fr);
1080 AlignViewportI viewport = viewPanel.getAlignViewport();
1081 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1082 AlignmentI al = viewport.getAlignment();
1083 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1084 String[] files = getStructureFiles();
1086 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1087 Color lastColour = null;
1089 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1091 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1093 if (mapping == null || mapping.length < 1)
1098 int startPos = -1, lastPos = -1;
1099 String lastChain = "";
1100 for (int s = 0; s < sequence[pdbfnum].length; s++)
1102 for (int sp, m = 0; m < mapping.length; m++)
1104 final SequenceI seq = sequence[pdbfnum][s];
1105 if (mapping[m].getSequence() == seq
1106 && (sp = al.findIndex(seq)) > -1)
1108 SequenceI asp = al.getSequenceAt(sp);
1109 for (int r = 0; r < asp.getLength(); r++)
1111 // no mapping to gaps in sequence
1112 if (Comparison.isGap(asp.getCharAt(r)))
1116 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1118 if (pos < 1 || pos == lastPos)
1123 Color colour = sr.getResidueColour(seq, r, finder);
1126 * hidden regions are shown gray or, optionally, ignored
1128 if (!cs.isVisible(r))
1130 if (hideHiddenRegions)
1136 colour = Color.GRAY;
1140 final String chain = mapping[m].getChain();
1143 * Just keep incrementing the end position for this colour range
1144 * _unless_ colour, PDB model or chain has changed, or there is a
1145 * gap in the mapped residue sequence
1147 final boolean newColour = !colour.equals(lastColour);
1148 final boolean nonContig = lastPos + 1 != pos;
1149 final boolean newChain = !chain.equals(lastChain);
1150 if (newColour || nonContig || newChain)
1154 ChimeraCommands.addAtomSpecRange(colourMap, lastColour,
1156 lastPos, lastChain);
1160 lastColour = colour;
1164 // final colour range
1165 if (lastColour != null)
1167 ChimeraCommands.addAtomSpecRange(colourMap, lastColour,
1169 startPos, lastPos, lastChain);