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.SequenceRenderer;
26 import jalview.api.StructureSelectionManagerProvider;
27 import jalview.api.structures.JalviewStructureDisplayI;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SequenceI;
32 import jalview.ext.rbvi.chimera.AtomSpecModel;
33 import jalview.io.DataSourceType;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureListener;
37 import jalview.structure.StructureMapping;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.Comparison;
40 import jalview.util.MessageManager;
42 import java.awt.Color;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.BitSet;
46 import java.util.Collections;
47 import java.util.Iterator;
48 import java.util.List;
52 * A base class to hold common function for protein structure model binding.
53 * Initial version created by refactoring JMol and Chimera binding models, but
54 * other structure viewers could in principle be accommodated in future.
59 public abstract class AAStructureBindingModel
60 extends SequenceStructureBindingModel
61 implements StructureListener, StructureSelectionManagerProvider
64 private StructureSelectionManager ssm;
67 * distinct PDB entries (pdb files) associated
70 private PDBEntry[] pdbEntry;
73 * sequences mapped to each pdbentry
75 private SequenceI[][] sequence;
78 * array of target chains for sequences - tied to pdbentry and sequence[]
80 private String[][] chains;
83 * datasource protocol for access to PDBEntrylatest
85 DataSourceType protocol = null;
87 protected boolean colourBySequence = true;
89 private boolean nucleotide;
91 private boolean finishedInit = false;
94 * current set of model filenames loaded in the Jmol instance
96 protected String[] modelFileNames = null;
98 public String fileLoadingError;
100 private boolean showAlignmentOnly;
103 * a list of chains "pdbid:chainid" to show in the viewer;
104 * empty means show all
106 // TODO make private once deprecated JalviewJmolBinding.centerViewer removed
107 protected List<String> chainsToShow;
109 private boolean hideHiddenRegions;
111 protected List<String> chainNames = new ArrayList<>();
114 * Data bean class to simplify parameterisation in superposeStructures
116 protected class SuperposeData
119 * Constructor with alignment width argument
123 public SuperposeData(int width)
125 pdbResNo = new int[width];
128 public String filename;
132 public String chain = "";
134 public boolean isRna;
137 * The pdb residue number (if any) mapped to each column of the alignment
139 public int[] pdbResNo;
148 public AAStructureBindingModel(StructureSelectionManager ssm,
152 this.sequence = seqs;
153 chainsToShow = new ArrayList<>();
164 public AAStructureBindingModel(StructureSelectionManager ssm,
165 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
166 DataSourceType protocol)
169 this.sequence = sequenceIs;
170 this.nucleotide = Comparison.isNucleotide(sequenceIs);
171 this.pdbEntry = pdbentry;
172 this.protocol = protocol;
173 chainsToShow = new ArrayList<>();
178 private boolean resolveChains()
181 * final count of chain mappings discovered
184 // JBPNote: JAL-2693 - this should be a list of chain mappings per
185 // [pdbentry][sequence]
186 String[][] newchains = new String[pdbEntry.length][];
188 for (PDBEntry pdb : pdbEntry)
190 SequenceI[] seqsForPdb = sequence[pe];
191 if (seqsForPdb != null)
193 newchains[pe] = new String[seqsForPdb.length];
195 for (SequenceI asq : seqsForPdb)
197 String chain = (chains != null && chains[pe] != null)
200 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
201 : asq.getDatasetSequence();
202 if (sq.getAllPDBEntries() != null)
204 for (PDBEntry pdbentry : sq.getAllPDBEntries())
206 if (pdb.getFile() != null && pdbentry.getFile() != null
207 && pdb.getFile().equals(pdbentry.getFile()))
209 String chaincode = pdbentry.getChainCode();
210 if (chaincode != null && chaincode.length() > 0)
219 newchains[pe][se] = chain;
227 return chainmaps > 0;
229 public StructureSelectionManager getSsm()
235 * Returns the i'th PDBEntry (or null)
240 public PDBEntry getPdbEntry(int i)
242 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
246 * Answers true if this binding includes the given PDB id, else false
251 public boolean hasPdbId(String pdbId)
253 if (pdbEntry != null)
255 for (PDBEntry pdb : pdbEntry)
257 if (pdb.getId().equals(pdbId))
267 * Returns the number of modelled PDB file entries.
271 public int getPdbCount()
273 return pdbEntry == null ? 0 : pdbEntry.length;
276 public SequenceI[][] getSequence()
281 public String[][] getChains()
286 public DataSourceType getProtocol()
291 // TODO may remove this if calling methods can be pulled up here
292 protected void setPdbentry(PDBEntry[] pdbentry)
294 this.pdbEntry = pdbentry;
297 protected void setSequence(SequenceI[][] sequence)
299 this.sequence = sequence;
302 protected void setChains(String[][] chains)
304 this.chains = chains;
308 * Construct a title string for the viewer window based on the data Jalview
317 public String getViewerTitle(String viewerName, boolean verbose)
319 if (getSequence() == null || getSequence().length < 1
320 || getPdbCount() < 1 || getSequence()[0].length < 1)
322 return ("Jalview " + viewerName + " Window");
324 // TODO: give a more informative title when multiple structures are
326 StringBuilder title = new StringBuilder(64);
327 final PDBEntry pdbe = getPdbEntry(0);
328 title.append(viewerName + " view for " + getSequence()[0][0].getName()
329 + ":" + pdbe.getId());
333 String method = (String) pdbe.getProperty("method");
336 title.append(" Method: ").append(method);
338 String chain = (String) pdbe.getProperty("chains");
341 title.append(" Chain:").append(chain);
344 return title.toString();
348 * Called by after closeViewer is called, to release any resources and
349 * references so they can be garbage collected. Override if needed.
351 protected void releaseUIResources()
356 public boolean isColourBySequence()
358 return colourBySequence;
361 public void setColourBySequence(boolean colourBySequence)
363 this.colourBySequence = colourBySequence;
366 protected void addSequenceAndChain(int pe, SequenceI[] seq,
369 if (pe < 0 || pe >= getPdbCount())
371 throw new Error(MessageManager.formatMessage(
372 "error.implementation_error_no_pdbentry_from_index",
374 { Integer.valueOf(pe).toString() }));
376 final String nullChain = "TheNullChain";
377 List<SequenceI> s = new ArrayList<>();
378 List<String> c = new ArrayList<>();
379 if (getChains() == null)
381 setChains(new String[getPdbCount()][]);
383 if (getSequence()[pe] != null)
385 for (int i = 0; i < getSequence()[pe].length; i++)
387 s.add(getSequence()[pe][i]);
388 if (getChains()[pe] != null)
390 if (i < getChains()[pe].length)
392 c.add(getChains()[pe][i]);
401 if (tchain != null && tchain.length > 0)
408 for (int i = 0; i < seq.length; i++)
410 if (!s.contains(seq[i]))
413 if (tchain != null && i < tchain.length)
415 c.add(tchain[i] == null ? nullChain : tchain[i]);
419 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
420 getSequence()[pe] = tmp;
423 String[] tch = c.toArray(new String[c.size()]);
424 for (int i = 0; i < tch.length; i++)
426 if (tch[i] == nullChain)
431 getChains()[pe] = tch;
435 getChains()[pe] = null;
440 * add structures and any known sequence associations
442 * @returns the pdb entries added to the current set.
444 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
445 SequenceI[][] seq, String[][] chns)
447 List<PDBEntry> v = new ArrayList<>();
448 List<int[]> rtn = new ArrayList<>();
449 for (int i = 0; i < getPdbCount(); i++)
451 v.add(getPdbEntry(i));
453 for (int i = 0; i < pdbe.length; i++)
455 int r = v.indexOf(pdbe[i]);
456 if (r == -1 || r >= getPdbCount())
458 rtn.add(new int[] { v.size(), i });
463 // just make sure the sequence/chain entries are all up to date
464 addSequenceAndChain(r, seq[i], chns[i]);
467 pdbe = v.toArray(new PDBEntry[v.size()]);
471 // expand the tied sequence[] and string[] arrays
472 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
473 String[][] sch = new String[getPdbCount()][];
474 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
475 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
478 pdbe = new PDBEntry[rtn.size()];
479 for (int r = 0; r < pdbe.length; r++)
481 int[] stri = (rtn.get(r));
482 // record the pdb file as a new addition
483 pdbe[r] = getPdbEntry(stri[0]);
484 // and add the new sequence/chain entries
485 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
496 * Add sequences to the pe'th pdbentry's sequence set.
501 public void addSequence(int pe, SequenceI[] seq)
503 addSequenceAndChain(pe, seq, null);
507 * add the given sequences to the mapping scope for the given pdb file handle
510 * - pdbFile identifier
512 * - set of sequences it can be mapped to
514 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
516 for (int pe = 0; pe < getPdbCount(); pe++)
518 if (getPdbEntry(pe).getFile().equals(pdbFile))
520 addSequence(pe, seq);
526 public abstract void highlightAtoms(List<AtomSpec> atoms);
528 protected boolean isNucleotide()
530 return this.nucleotide;
534 * Returns a readable description of all mappings for the wrapped pdbfile to
535 * any mapped sequences
541 public String printMappings()
543 if (pdbEntry == null)
547 StringBuilder sb = new StringBuilder(128);
548 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
550 String pdbfile = getPdbEntry(pdbe).getFile();
551 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
552 sb.append(getSsm().printMappings(pdbfile, seqs));
554 return sb.toString();
558 * Returns the mapped structure position for a given aligned column of a given
559 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
560 * not mapped to structure.
567 protected int getMappedPosition(SequenceI seq, int alignedPos,
568 StructureMapping mapping)
570 if (alignedPos >= seq.getLength())
575 if (Comparison.isGap(seq.getCharAt(alignedPos)))
579 int seqPos = seq.findPosition(alignedPos);
580 int pos = mapping.getPDBResNum(seqPos);
585 * Helper method to identify residues that can participate in a structure
586 * superposition command. For each structure, identify a sequence in the
587 * alignment which is mapped to the structure. Identify non-gapped columns in
588 * the sequence which have a mapping to a residue in the structure. Returns
589 * the index of the first structure that has a mapping to the alignment.
592 * the sequence alignment which is the basis of structure
595 * a BitSet, where bit j is set to indicate that every structure has
596 * a mapped residue present in column j (so the column can
597 * participate in structure alignment)
599 * an array of data beans corresponding to pdb file index
602 protected int findSuperposableResidues(AlignmentI alignment,
603 BitSet matched, SuperposeData[] structures)
605 int refStructure = -1;
606 String[] files = getStructureFiles();
611 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
613 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
617 * Find the first mapped sequence (if any) for this PDB entry which is in
620 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
621 for (int s = 0; s < seqCountForPdbFile; s++)
623 for (StructureMapping mapping : mappings)
625 final SequenceI theSequence = getSequence()[pdbfnum][s];
626 if (mapping.getSequence() == theSequence
627 && alignment.findIndex(theSequence) > -1)
629 if (refStructure < 0)
631 refStructure = pdbfnum;
633 for (int r = 0; r < alignment.getWidth(); r++)
639 int pos = getMappedPosition(theSequence, r, mapping);
640 if (pos < 1 || pos == lastPos)
646 structures[pdbfnum].pdbResNo[r] = pos;
648 String chain = mapping.getChain();
649 if (chain != null && chain.trim().length() > 0)
651 structures[pdbfnum].chain = chain;
653 structures[pdbfnum].pdbId = mapping.getPdbId();
654 structures[pdbfnum].isRna = theSequence.getRNA() != null;
657 * move on to next pdb file (ignore sequences for other chains
658 * for the same structure)
660 s = seqCountForPdbFile;
670 * Returns true if the structure viewer has loaded all of the files of
671 * interest (identified by the file mapping having been set up), or false if
672 * any are still not loaded after a timeout interval.
676 protected boolean waitForFileLoad(String[] files)
679 * give up after 10 secs plus 1 sec per file
681 long starttime = System.currentTimeMillis();
682 long endTime = 10000 + 1000 * files.length + starttime;
683 String notLoaded = null;
685 boolean waiting = true;
686 while (waiting && System.currentTimeMillis() < endTime)
689 for (String file : files)
698 StructureMapping[] sm = getSsm().getMapping(file);
699 if (sm == null || sm.length == 0)
703 } catch (Throwable x)
713 "Timed out waiting for structure viewer to load file "
721 public boolean isListeningFor(SequenceI seq)
723 if (sequence != null)
725 for (SequenceI[] seqs : sequence)
729 for (SequenceI s : seqs)
731 if (s == seq || (s.getDatasetSequence() != null
732 && s.getDatasetSequence() == seq.getDatasetSequence()))
743 public boolean isFinishedInit()
748 public void setFinishedInit(boolean fi)
750 this.finishedInit = fi;
754 * Returns the Jalview panel hosting the structure viewer (if any)
758 public JalviewStructureDisplayI getViewer()
763 public abstract void setJalviewColourScheme(ColourSchemeI cs);
766 * Constructs and sends a command to align structures against a reference
767 * structure, based on one or more sequence alignments. May optionally return
768 * an error or warning message for the alignment command.
771 * an array of alignments to process
772 * @param structureIndices
773 * an array of corresponding reference structures (index into pdb
774 * file array); if a negative value is passed, the first PDB file
775 * mapped to an alignment sequence is used as the reference for
778 * an array of corresponding hidden columns for each alignment
781 public abstract String superposeStructures(AlignmentI[] alignments,
782 int[] structureIndices, HiddenColumns[] hiddenCols);
784 public abstract void setBackgroundColour(Color col);
787 * returns the current sequenceRenderer that should be used to colour the
794 public abstract SequenceRenderer getSequenceRenderer(
795 AlignmentViewPanel alignment);
798 * Recolours mapped residues in the structure viewer to match colours in the
799 * given alignment panel. Colours should also be applied to any hidden mapped
800 * residues (so that they are shown correctly if these get unhidden).
804 protected abstract void colourBySequence(AlignmentViewPanel viewPanel);
806 public abstract void colourByChain();
808 public abstract void colourByCharge();
811 * Recolours the displayed structures, if they are coloured by sequence, or
812 * 'show only visible alignment' is selected. This supports updating structure
813 * colours on either change of alignment colours, or change to the visible
814 * region of the alignment.
816 public void updateStructureColours(AlignmentViewPanel alignmentv)
818 if (!isLoadingFinished())
824 * if structure is not coloured by sequence, but restricted to the alignment,
825 * then redraw it (but don't recolour it) in case hidden regions have changed
826 * (todo: specific messaging for change of hidden region only)
828 if (!colourBySequence)
830 if (isShowAlignmentOnly())
832 showStructures(alignmentv.getAlignViewport(), false);
836 if (getSsm() == null)
841 colourBySequence(alignmentv);
844 public boolean hasFileLoadingError()
846 return fileLoadingError != null && fileLoadingError.length() > 0;
849 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
850 AlignmentViewPanel alignment);
853 * Sets the flag for whether only mapped visible residues in the alignment
854 * should be visible in the structure viewer
858 public void setShowAlignmentOnly(boolean b)
860 showAlignmentOnly = b;
864 * Answers true if only residues mapped to the alignment should be shown in the
865 * structure viewer, else false
869 public boolean isShowAlignmentOnly()
871 return showAlignmentOnly;
875 * Sets the flag for hiding regions of structure which are hidden in the
876 * alignment (only applies when the structure viewer is restricted to the
881 public void setHideHiddenRegions(boolean b)
883 hideHiddenRegions = b;
887 * Answers true if regions hidden in the alignment should also be hidden in the
888 * structure viewer, else false (only applies when the structure viewer is
889 * restricted to the alignment only)
893 public boolean isHideHiddenRegions()
895 return hideHiddenRegions;
899 * Shows the structures in the viewer, without changing their colouring. This is
900 * to support toggling of whether the whole structure is shown, or only residues
901 * mapped to visible regions of the alignment.
903 * @param alignViewportI
905 * if true, refit the display to the viewer
907 public void showStructures(AlignViewportI alignViewportI, boolean refocus)
909 // override with implementation
913 public void updateColours(Object source)
915 AlignmentViewPanel ap = (AlignmentViewPanel) source;
916 // ignore events from panels not used to colour this view
917 if (!getViewer().isUsedforcolourby(ap))
921 if (!isLoadingFromArchive())
923 updateStructureColours(ap);
928 * Sets the list of chains to display (as "pdbid:chain"), where an empty list
933 public void setChainsToShow(List<String> chains)
935 chainsToShow = chains;
939 * Answers true if the specified structure and chain are selected to be shown in
940 * the viewer, else false
946 protected boolean isShowChain(String pdbId, String chainId)
948 if (chainsToShow.isEmpty())
952 return chainsToShow.contains(pdbId + ":" + chainId);
956 public abstract String[] getStructureFiles();
959 * Builds a model of residues mapped from sequences to show on structure, taking
960 * into account user choices of
962 * <li>which chains are shown</li>
963 * <li>whether all structure is shown, or only that mapped to the alignment</li>
964 * <li>whether hidden regions of the alignment are hidden (excluded) or grayed
965 * out (included)</li>
971 protected AtomSpecModel getShownResidues(AlignViewportI av)
973 AlignmentI alignment = av.getAlignment();
974 final int width = alignment.getWidth();
976 String[] files = getStructureFiles();
978 AtomSpecModel model = new AtomSpecModel();
980 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
982 String fileName = files[pdbfnum];
983 final int modelNumber = getModelForPdbFile(fileName, pdbfnum);
984 StructureMapping[] mappings = getSsm().getMapping(fileName);
987 * Find the first mapped sequence (if any) for this PDB entry which is in
990 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
991 for (int s = 0; s < seqCountForPdbFile; s++)
993 for (StructureMapping mapping : mappings)
995 final SequenceI theSequence = getSequence()[pdbfnum][s];
996 if (mapping.getSequence() == theSequence
997 && alignment.findIndex(theSequence) > -1)
999 String chainCd = mapping.getChain();
1000 if (!isShowChain(mapping.getPdbId(), chainCd))
1004 Iterator<int[]> visible;
1005 if (isShowAlignmentOnly() && isHideHiddenRegions())
1007 visible = alignment.getHiddenColumns()
1008 .getVisContigsIterator(0, width, true);
1012 visible = Collections.singletonList(new int[] { 0, width })
1015 while (visible.hasNext())
1017 int[] visibleRegion = visible.next();
1018 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1019 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1020 List<int[]> residueRanges = mapping
1021 .getPDBResNumRanges(seqStartPos, seqEndPos);
1022 if (!residueRanges.isEmpty())
1024 for (int[] range : residueRanges)
1026 model.addRange(modelNumber, range[0], range[1], chainCd);
1039 * Answers the structure viewer's model number for the given PDB file, or -1 if
1044 * index of the file in the stored array of file names
1047 public int getModelForPdbFile(String fileName, int fileIndex)
1053 * Answers a default structure model specification which is simply the string
1054 * form of the model number. Override if needed to specify submodels.
1059 public String getModelSpec(int model)
1061 return String.valueOf(model);
1065 * Returns a list of chains mapped in this viewer. Note this list is not
1066 * currently scoped per structure.
1070 public List<String> getChainNames()
1076 * Send a command to resize and/or centre the structure display
1078 public void focusView()