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.StructureMappingcommandSet;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.MessageManager;
43 import java.awt.Color;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.BitSet;
47 import java.util.Collections;
48 import java.util.Iterator;
49 import java.util.List;
53 * A base class to hold common function for protein structure model binding.
54 * Initial version created by refactoring JMol and Chimera binding models, but
55 * other structure viewers could in principle be accommodated in future.
60 public abstract class AAStructureBindingModel
61 extends SequenceStructureBindingModel
62 implements StructureListener, StructureSelectionManagerProvider
65 private StructureSelectionManager ssm;
68 * distinct PDB entries (pdb files) associated
71 private PDBEntry[] pdbEntry;
74 * sequences mapped to each pdbentry
76 private SequenceI[][] sequence;
79 * array of target chains for sequences - tied to pdbentry and sequence[]
81 private String[][] chains;
84 * datasource protocol for access to PDBEntrylatest
86 DataSourceType protocol = null;
88 protected boolean colourBySequence = true;
90 private boolean nucleotide;
92 private boolean finishedInit = false;
95 * current set of model filenames loaded in the Jmol instance
97 protected String[] modelFileNames = null;
99 public String fileLoadingError;
101 private boolean showAlignmentOnly;
104 * a list of chains "pdbid:chainid" to show in the viewer;
105 * empty means show all
107 // TODO make private once showStructures() deals with this
108 protected List<String> chainsToShow;
110 private boolean hideHiddenRegions;
113 * Data bean class to simplify parameterisation in superposeStructures
115 protected class SuperposeData
118 * Constructor with alignment width argument
122 public SuperposeData(int width)
124 pdbResNo = new int[width];
127 public String filename;
131 public String chain = "";
133 public boolean isRna;
136 * The pdb residue number (if any) mapped to each column of the alignment
138 public int[] pdbResNo;
147 public AAStructureBindingModel(StructureSelectionManager ssm,
151 this.sequence = seqs;
152 chainsToShow = new ArrayList<>();
163 public AAStructureBindingModel(StructureSelectionManager ssm,
164 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
165 DataSourceType protocol)
168 this.sequence = sequenceIs;
169 this.nucleotide = Comparison.isNucleotide(sequenceIs);
170 this.pdbEntry = pdbentry;
171 this.protocol = protocol;
172 chainsToShow = new ArrayList<>();
177 private boolean resolveChains()
180 * final count of chain mappings discovered
183 // JBPNote: JAL-2693 - this should be a list of chain mappings per
184 // [pdbentry][sequence]
185 String[][] newchains = new String[pdbEntry.length][];
187 for (PDBEntry pdb : pdbEntry)
189 SequenceI[] seqsForPdb = sequence[pe];
190 if (seqsForPdb != null)
192 newchains[pe] = new String[seqsForPdb.length];
194 for (SequenceI asq : seqsForPdb)
196 String chain = (chains != null && chains[pe] != null)
199 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
200 : asq.getDatasetSequence();
201 if (sq.getAllPDBEntries() != null)
203 for (PDBEntry pdbentry : sq.getAllPDBEntries())
205 if (pdb.getFile() != null && pdbentry.getFile() != null
206 && pdb.getFile().equals(pdbentry.getFile()))
208 String chaincode = pdbentry.getChainCode();
209 if (chaincode != null && chaincode.length() > 0)
218 newchains[pe][se] = chain;
226 return chainmaps > 0;
228 public StructureSelectionManager getSsm()
234 * Returns the i'th PDBEntry (or null)
239 public PDBEntry getPdbEntry(int i)
241 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
245 * Answers true if this binding includes the given PDB id, else false
250 public boolean hasPdbId(String pdbId)
252 if (pdbEntry != null)
254 for (PDBEntry pdb : pdbEntry)
256 if (pdb.getId().equals(pdbId))
266 * Returns the number of modelled PDB file entries.
270 public int getPdbCount()
272 return pdbEntry == null ? 0 : pdbEntry.length;
275 public SequenceI[][] getSequence()
280 public String[][] getChains()
285 public DataSourceType getProtocol()
290 // TODO may remove this if calling methods can be pulled up here
291 protected void setPdbentry(PDBEntry[] pdbentry)
293 this.pdbEntry = pdbentry;
296 protected void setSequence(SequenceI[][] sequence)
298 this.sequence = sequence;
301 protected void setChains(String[][] chains)
303 this.chains = chains;
307 * Construct a title string for the viewer window based on the data Jalview
316 public String getViewerTitle(String viewerName, boolean verbose)
318 if (getSequence() == null || getSequence().length < 1
319 || getPdbCount() < 1 || getSequence()[0].length < 1)
321 return ("Jalview " + viewerName + " Window");
323 // TODO: give a more informative title when multiple structures are
325 StringBuilder title = new StringBuilder(64);
326 final PDBEntry pdbe = getPdbEntry(0);
327 title.append(viewerName + " view for " + getSequence()[0][0].getName()
328 + ":" + pdbe.getId());
332 String method = (String) pdbe.getProperty("method");
335 title.append(" Method: ").append(method);
337 String chain = (String) pdbe.getProperty("chains");
340 title.append(" Chain:").append(chain);
343 return title.toString();
347 * Called by after closeViewer is called, to release any resources and
348 * references so they can be garbage collected. Override if needed.
350 protected void releaseUIResources()
355 public boolean isColourBySequence()
357 return colourBySequence;
360 public void setColourBySequence(boolean colourBySequence)
362 this.colourBySequence = colourBySequence;
365 protected void addSequenceAndChain(int pe, SequenceI[] seq,
368 if (pe < 0 || pe >= getPdbCount())
370 throw new Error(MessageManager.formatMessage(
371 "error.implementation_error_no_pdbentry_from_index",
373 { Integer.valueOf(pe).toString() }));
375 final String nullChain = "TheNullChain";
376 List<SequenceI> s = new ArrayList<>();
377 List<String> c = new ArrayList<>();
378 if (getChains() == null)
380 setChains(new String[getPdbCount()][]);
382 if (getSequence()[pe] != null)
384 for (int i = 0; i < getSequence()[pe].length; i++)
386 s.add(getSequence()[pe][i]);
387 if (getChains()[pe] != null)
389 if (i < getChains()[pe].length)
391 c.add(getChains()[pe][i]);
400 if (tchain != null && tchain.length > 0)
407 for (int i = 0; i < seq.length; i++)
409 if (!s.contains(seq[i]))
412 if (tchain != null && i < tchain.length)
414 c.add(tchain[i] == null ? nullChain : tchain[i]);
418 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
419 getSequence()[pe] = tmp;
422 String[] tch = c.toArray(new String[c.size()]);
423 for (int i = 0; i < tch.length; i++)
425 if (tch[i] == nullChain)
430 getChains()[pe] = tch;
434 getChains()[pe] = null;
439 * add structures and any known sequence associations
441 * @returns the pdb entries added to the current set.
443 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
444 SequenceI[][] seq, String[][] chns)
446 List<PDBEntry> v = new ArrayList<>();
447 List<int[]> rtn = new ArrayList<>();
448 for (int i = 0; i < getPdbCount(); i++)
450 v.add(getPdbEntry(i));
452 for (int i = 0; i < pdbe.length; i++)
454 int r = v.indexOf(pdbe[i]);
455 if (r == -1 || r >= getPdbCount())
457 rtn.add(new int[] { v.size(), i });
462 // just make sure the sequence/chain entries are all up to date
463 addSequenceAndChain(r, seq[i], chns[i]);
466 pdbe = v.toArray(new PDBEntry[v.size()]);
470 // expand the tied sequence[] and string[] arrays
471 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
472 String[][] sch = new String[getPdbCount()][];
473 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
474 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
477 pdbe = new PDBEntry[rtn.size()];
478 for (int r = 0; r < pdbe.length; r++)
480 int[] stri = (rtn.get(r));
481 // record the pdb file as a new addition
482 pdbe[r] = getPdbEntry(stri[0]);
483 // and add the new sequence/chain entries
484 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
495 * Add sequences to the pe'th pdbentry's sequence set.
500 public void addSequence(int pe, SequenceI[] seq)
502 addSequenceAndChain(pe, seq, null);
506 * add the given sequences to the mapping scope for the given pdb file handle
509 * - pdbFile identifier
511 * - set of sequences it can be mapped to
513 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
515 for (int pe = 0; pe < getPdbCount(); pe++)
517 if (getPdbEntry(pe).getFile().equals(pdbFile))
519 addSequence(pe, seq);
525 public abstract void highlightAtoms(List<AtomSpec> atoms);
527 protected boolean isNucleotide()
529 return this.nucleotide;
533 * Returns a readable description of all mappings for the wrapped pdbfile to
534 * any mapped sequences
540 public String printMappings()
542 if (pdbEntry == null)
546 StringBuilder sb = new StringBuilder(128);
547 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
549 String pdbfile = getPdbEntry(pdbe).getFile();
550 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
551 sb.append(getSsm().printMappings(pdbfile, seqs));
553 return sb.toString();
557 * Returns the mapped structure position for a given aligned column of a given
558 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
559 * not mapped to structure.
566 protected int getMappedPosition(SequenceI seq, int alignedPos,
567 StructureMapping mapping)
569 if (alignedPos >= seq.getLength())
574 if (Comparison.isGap(seq.getCharAt(alignedPos)))
578 int seqPos = seq.findPosition(alignedPos);
579 int pos = mapping.getPDBResNum(seqPos);
584 * Helper method to identify residues that can participate in a structure
585 * superposition command. For each structure, identify a sequence in the
586 * alignment which is mapped to the structure. Identify non-gapped columns in
587 * the sequence which have a mapping to a residue in the structure. Returns
588 * the index of the first structure that has a mapping to the alignment.
591 * the sequence alignment which is the basis of structure
594 * a BitSet, where bit j is set to indicate that every structure has
595 * a mapped residue present in column j (so the column can
596 * participate in structure alignment)
598 * an array of data beans corresponding to pdb file index
601 protected int findSuperposableResidues(AlignmentI alignment,
602 BitSet matched, SuperposeData[] structures)
604 int refStructure = -1;
605 String[] files = getStructureFiles();
610 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
612 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
616 * Find the first mapped sequence (if any) for this PDB entry which is in
619 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
620 for (int s = 0; s < seqCountForPdbFile; s++)
622 for (StructureMapping mapping : mappings)
624 final SequenceI theSequence = getSequence()[pdbfnum][s];
625 if (mapping.getSequence() == theSequence
626 && alignment.findIndex(theSequence) > -1)
628 if (refStructure < 0)
630 refStructure = pdbfnum;
632 for (int r = 0; r < alignment.getWidth(); r++)
638 int pos = getMappedPosition(theSequence, r, mapping);
639 if (pos < 1 || pos == lastPos)
645 structures[pdbfnum].pdbResNo[r] = pos;
647 String chain = mapping.getChain();
648 if (chain != null && chain.trim().length() > 0)
650 structures[pdbfnum].chain = chain;
652 structures[pdbfnum].pdbId = mapping.getPdbId();
653 structures[pdbfnum].isRna = theSequence.getRNA() != null;
656 * move on to next pdb file (ignore sequences for other chains
657 * for the same structure)
659 s = seqCountForPdbFile;
669 * Returns true if the structure viewer has loaded all of the files of
670 * interest (identified by the file mapping having been set up), or false if
671 * any are still not loaded after a timeout interval.
675 protected boolean waitForFileLoad(String[] files)
678 * give up after 10 secs plus 1 sec per file
680 long starttime = System.currentTimeMillis();
681 long endTime = 10000 + 1000 * files.length + starttime;
682 String notLoaded = null;
684 boolean waiting = true;
685 while (waiting && System.currentTimeMillis() < endTime)
688 for (String file : files)
697 StructureMapping[] sm = getSsm().getMapping(file);
698 if (sm == null || sm.length == 0)
702 } catch (Throwable x)
712 "Timed out waiting for structure viewer to load file "
720 public boolean isListeningFor(SequenceI seq)
722 if (sequence != null)
724 for (SequenceI[] seqs : sequence)
728 for (SequenceI s : seqs)
730 if (s == seq || (s.getDatasetSequence() != null
731 && s.getDatasetSequence() == seq.getDatasetSequence()))
742 public boolean isFinishedInit()
747 public void setFinishedInit(boolean fi)
749 this.finishedInit = fi;
753 * Returns a list of chains mapped in this viewer.
757 public abstract List<String> getChainNames();
760 * Returns the Jalview panel hosting the structure viewer (if any)
764 public JalviewStructureDisplayI getViewer()
769 public abstract void setJalviewColourScheme(ColourSchemeI cs);
772 * Constructs and sends a command to align structures against a reference
773 * structure, based on one or more sequence alignments. May optionally return
774 * an error or warning message for the alignment command.
777 * an array of alignments to process
778 * @param structureIndices
779 * an array of corresponding reference structures (index into pdb
780 * file array); if a negative value is passed, the first PDB file
781 * mapped to an alignment sequence is used as the reference for
784 * an array of corresponding hidden columns for each alignment
787 public abstract String superposeStructures(AlignmentI[] alignments,
788 int[] structureIndices, HiddenColumns[] hiddenCols);
790 public abstract void setBackgroundColour(Color col);
792 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
793 String[] files, AlignmentViewPanel avp);
796 * returns the current sequenceRenderer that should be used to colour the
803 public abstract SequenceRenderer getSequenceRenderer(
804 AlignmentViewPanel alignment);
806 protected abstract void colourBySequence(
807 StructureMappingcommandSet[] colourBySequenceCommands);
809 public abstract void colourByChain();
811 public abstract void colourByCharge();
814 * Recolours the displayed structures, if they are coloured by sequence, or
815 * 'show only visible alignment' is selected. This supports updating structure
816 * colours on either change of alignment colours, or change to the visible
817 * region of the alignment.
819 public void colourBySequence(AlignmentViewPanel alignmentv)
821 if (!isLoadingFinished())
827 * if structure is not coloured by sequence, but restricted to the alignment,
828 * then redraw it (but don't recolour it) in case hidden regions have changed
829 * (todo: specific messaging for change of hidden region only)
831 if (!colourBySequence)
833 if (isShowAlignmentOnly())
835 showStructures(alignmentv.getAlignViewport(), false);
839 if (getSsm() == null)
843 String[] files = getStructureFiles();
845 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
847 colourBySequence(colourBySequenceCommands);
850 public boolean hasFileLoadingError()
852 return fileLoadingError != null && fileLoadingError.length() > 0;
855 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
856 AlignmentViewPanel alignment);
859 * Sets the flag for whether only mapped visible residues in the alignment
860 * should be visible in the structure viewer
864 public void setShowAlignmentOnly(boolean b)
866 showAlignmentOnly = b;
870 * Answers true if only residues mapped to the alignment should be shown in the
871 * structure viewer, else false
875 public boolean isShowAlignmentOnly()
877 return showAlignmentOnly;
881 * Sets the flag for hiding regions of structure which are hidden in the
882 * alignment (only applies when the structure viewer is restricted to the
887 public void setHideHiddenRegions(boolean b)
889 hideHiddenRegions = b;
893 * Answers true if regions hidden in the alignment should also be hidden in the
894 * structure viewer, else false (only applies when the structure viewer is
895 * restricted to the alignment only)
899 public boolean isHideHiddenRegions()
901 return hideHiddenRegions;
905 * Shows the structures in the viewer, without changing their colouring. This is
906 * to support toggling of whether the whole structure is shown, or only residues
907 * mapped to visible regions of the alignment.
909 * @param alignViewportI
911 * if true, refit the display to the viewer
913 public void showStructures(AlignViewportI alignViewportI, boolean refocus)
915 // override with implementation
919 public void updateColours(Object source)
921 AlignmentViewPanel ap = (AlignmentViewPanel) source;
922 // ignore events from panels not used to colour this view
923 if (!getViewer().isUsedforcolourby(ap))
927 if (!isLoadingFromArchive())
929 colourBySequence(ap);
934 * Sets the list of chains to display (as "pdbid:chain"), where an empty list
939 public void setChainsToShow(List<String> chains)
941 chainsToShow = chains;
945 * Answers true if the specified structure and chain are selected to be shown in
946 * the viewer, else false
952 protected boolean isShowChain(String pdbId, String chainId)
954 if (chainsToShow.isEmpty())
958 return chainsToShow.contains(pdbId + ":" + chainId);
962 public abstract String[] getStructureFiles();
965 * Builds a model of residues mapped from sequences to show on structure, taking
966 * into account user choices of
968 * <li>which chains are shown</li>
969 * <li>whether all structure is shown, or only that mapped to the alignment</li>
970 * <li>whether hidden regions of the alignment are hidden (excluded) or grayed
971 * out (included)</li>
977 protected AtomSpecModel getShownResidues(AlignViewportI av)
979 AlignmentI alignment = av.getAlignment();
980 final int width = alignment.getWidth();
982 String[] files = getStructureFiles();
984 AtomSpecModel model = new AtomSpecModel();
986 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
988 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
991 * Find the first mapped sequence (if any) for this PDB entry which is in
994 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
995 for (int s = 0; s < seqCountForPdbFile; s++)
997 for (StructureMapping mapping : mappings)
999 final SequenceI theSequence = getSequence()[pdbfnum][s];
1000 if (mapping.getSequence() == theSequence
1001 && alignment.findIndex(theSequence) > -1)
1003 String chainCd = mapping.getChain();
1004 if (!isShowChain(mapping.getPdbId(), chainCd))
1008 Iterator<int[]> visible;
1009 if (isShowAlignmentOnly() && isHideHiddenRegions())
1011 visible = alignment.getHiddenColumns()
1012 .getVisContigsIterator(0, width, true);
1016 visible = Collections.singletonList(new int[] { 0, width })
1019 while (visible.hasNext())
1021 int[] visibleRegion = visible.next();
1022 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1023 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1024 List<int[]> residueRanges = mapping
1025 .getPDBResNumRanges(seqStartPos, seqEndPos);
1026 if (!residueRanges.isEmpty())
1028 for (int[] range : residueRanges)
1030 model.addRange(pdbfnum, range[0], range[1], chainCd);
1043 * Answers a default structure model specification which is simply the string
1044 * form of the model number. Override if needed to specify submodels.
1049 public String getModelSpec(int model)
1051 return String.valueOf(model);