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.io.DataSourceType;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.structure.AtomSpec;
35 import jalview.structure.StructureListener;
36 import jalview.structure.StructureMapping;
37 import jalview.structure.StructureMappingcommandSet;
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.List;
50 * A base class to hold common function for protein structure model binding.
51 * Initial version created by refactoring JMol and Chimera binding models, but
52 * other structure viewers could in principle be accommodated in future.
57 public abstract class AAStructureBindingModel
58 extends SequenceStructureBindingModel
59 implements StructureListener, StructureSelectionManagerProvider
62 private StructureSelectionManager ssm;
65 * distinct PDB entries (pdb files) associated
68 private PDBEntry[] pdbEntry;
71 * sequences mapped to each pdbentry
73 private SequenceI[][] sequence;
76 * array of target chains for sequences - tied to pdbentry and sequence[]
78 private String[][] chains;
81 * datasource protocol for access to PDBEntrylatest
83 DataSourceType protocol = null;
85 protected boolean colourBySequence = true;
87 private boolean nucleotide;
89 private boolean finishedInit = false;
92 * current set of model filenames loaded in the Jmol instance
94 protected String[] modelFileNames = null;
96 public String fileLoadingError;
98 private boolean showAlignmentOnly;
101 * a list of chains "pdbid:chainid" to show in the viewer;
102 * empty means show all
104 // TODO make private once showStructures() deals with this
105 protected List<String> chainsToShow;
107 private boolean hideHiddenRegions;
110 * Data bean class to simplify parameterisation in superposeStructures
112 protected class SuperposeData
115 * Constructor with alignment width argument
119 public SuperposeData(int width)
121 pdbResNo = new int[width];
124 public String filename;
128 public String chain = "";
130 public boolean isRna;
133 * The pdb residue number (if any) mapped to each column of the alignment
135 public int[] pdbResNo;
144 public AAStructureBindingModel(StructureSelectionManager ssm,
148 this.sequence = seqs;
149 chainsToShow = new ArrayList<>();
160 public AAStructureBindingModel(StructureSelectionManager ssm,
161 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
162 DataSourceType protocol)
165 this.sequence = sequenceIs;
166 this.nucleotide = Comparison.isNucleotide(sequenceIs);
167 this.pdbEntry = pdbentry;
168 this.protocol = protocol;
169 chainsToShow = new ArrayList<>();
174 private boolean resolveChains()
177 * final count of chain mappings discovered
180 // JBPNote: JAL-2693 - this should be a list of chain mappings per
181 // [pdbentry][sequence]
182 String[][] newchains = new String[pdbEntry.length][];
184 for (PDBEntry pdb : pdbEntry)
186 SequenceI[] seqsForPdb = sequence[pe];
187 if (seqsForPdb != null)
189 newchains[pe] = new String[seqsForPdb.length];
191 for (SequenceI asq : seqsForPdb)
193 String chain = (chains != null && chains[pe] != null)
196 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
197 : asq.getDatasetSequence();
198 if (sq.getAllPDBEntries() != null)
200 for (PDBEntry pdbentry : sq.getAllPDBEntries())
202 if (pdb.getFile() != null && pdbentry.getFile() != null
203 && pdb.getFile().equals(pdbentry.getFile()))
205 String chaincode = pdbentry.getChainCode();
206 if (chaincode != null && chaincode.length() > 0)
215 newchains[pe][se] = chain;
223 return chainmaps > 0;
225 public StructureSelectionManager getSsm()
231 * Returns the i'th PDBEntry (or null)
236 public PDBEntry getPdbEntry(int i)
238 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
242 * Answers true if this binding includes the given PDB id, else false
247 public boolean hasPdbId(String pdbId)
249 if (pdbEntry != null)
251 for (PDBEntry pdb : pdbEntry)
253 if (pdb.getId().equals(pdbId))
263 * Returns the number of modelled PDB file entries.
267 public int getPdbCount()
269 return pdbEntry == null ? 0 : pdbEntry.length;
272 public SequenceI[][] getSequence()
277 public String[][] getChains()
282 public DataSourceType getProtocol()
287 // TODO may remove this if calling methods can be pulled up here
288 protected void setPdbentry(PDBEntry[] pdbentry)
290 this.pdbEntry = pdbentry;
293 protected void setSequence(SequenceI[][] sequence)
295 this.sequence = sequence;
298 protected void setChains(String[][] chains)
300 this.chains = chains;
304 * Construct a title string for the viewer window based on the data Jalview
313 public String getViewerTitle(String viewerName, boolean verbose)
315 if (getSequence() == null || getSequence().length < 1
316 || getPdbCount() < 1 || getSequence()[0].length < 1)
318 return ("Jalview " + viewerName + " Window");
320 // TODO: give a more informative title when multiple structures are
322 StringBuilder title = new StringBuilder(64);
323 final PDBEntry pdbe = getPdbEntry(0);
324 title.append(viewerName + " view for " + getSequence()[0][0].getName()
325 + ":" + pdbe.getId());
329 String method = (String) pdbe.getProperty("method");
332 title.append(" Method: ").append(method);
334 String chain = (String) pdbe.getProperty("chains");
337 title.append(" Chain:").append(chain);
340 return title.toString();
344 * Called by after closeViewer is called, to release any resources and
345 * references so they can be garbage collected. Override if needed.
347 protected void releaseUIResources()
352 public boolean isColourBySequence()
354 return colourBySequence;
357 public void setColourBySequence(boolean colourBySequence)
359 this.colourBySequence = colourBySequence;
362 protected void addSequenceAndChain(int pe, SequenceI[] seq,
365 if (pe < 0 || pe >= getPdbCount())
367 throw new Error(MessageManager.formatMessage(
368 "error.implementation_error_no_pdbentry_from_index",
370 { Integer.valueOf(pe).toString() }));
372 final String nullChain = "TheNullChain";
373 List<SequenceI> s = new ArrayList<>();
374 List<String> c = new ArrayList<>();
375 if (getChains() == null)
377 setChains(new String[getPdbCount()][]);
379 if (getSequence()[pe] != null)
381 for (int i = 0; i < getSequence()[pe].length; i++)
383 s.add(getSequence()[pe][i]);
384 if (getChains()[pe] != null)
386 if (i < getChains()[pe].length)
388 c.add(getChains()[pe][i]);
397 if (tchain != null && tchain.length > 0)
404 for (int i = 0; i < seq.length; i++)
406 if (!s.contains(seq[i]))
409 if (tchain != null && i < tchain.length)
411 c.add(tchain[i] == null ? nullChain : tchain[i]);
415 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
416 getSequence()[pe] = tmp;
419 String[] tch = c.toArray(new String[c.size()]);
420 for (int i = 0; i < tch.length; i++)
422 if (tch[i] == nullChain)
427 getChains()[pe] = tch;
431 getChains()[pe] = null;
436 * add structures and any known sequence associations
438 * @returns the pdb entries added to the current set.
440 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
441 SequenceI[][] seq, String[][] chns)
443 List<PDBEntry> v = new ArrayList<>();
444 List<int[]> rtn = new ArrayList<>();
445 for (int i = 0; i < getPdbCount(); i++)
447 v.add(getPdbEntry(i));
449 for (int i = 0; i < pdbe.length; i++)
451 int r = v.indexOf(pdbe[i]);
452 if (r == -1 || r >= getPdbCount())
454 rtn.add(new int[] { v.size(), i });
459 // just make sure the sequence/chain entries are all up to date
460 addSequenceAndChain(r, seq[i], chns[i]);
463 pdbe = v.toArray(new PDBEntry[v.size()]);
467 // expand the tied sequence[] and string[] arrays
468 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
469 String[][] sch = new String[getPdbCount()][];
470 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
471 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
474 pdbe = new PDBEntry[rtn.size()];
475 for (int r = 0; r < pdbe.length; r++)
477 int[] stri = (rtn.get(r));
478 // record the pdb file as a new addition
479 pdbe[r] = getPdbEntry(stri[0]);
480 // and add the new sequence/chain entries
481 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
492 * Add sequences to the pe'th pdbentry's sequence set.
497 public void addSequence(int pe, SequenceI[] seq)
499 addSequenceAndChain(pe, seq, null);
503 * add the given sequences to the mapping scope for the given pdb file handle
506 * - pdbFile identifier
508 * - set of sequences it can be mapped to
510 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
512 for (int pe = 0; pe < getPdbCount(); pe++)
514 if (getPdbEntry(pe).getFile().equals(pdbFile))
516 addSequence(pe, seq);
522 public abstract void highlightAtoms(List<AtomSpec> atoms);
524 protected boolean isNucleotide()
526 return this.nucleotide;
530 * Returns a readable description of all mappings for the wrapped pdbfile to
531 * any mapped sequences
537 public String printMappings()
539 if (pdbEntry == null)
543 StringBuilder sb = new StringBuilder(128);
544 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
546 String pdbfile = getPdbEntry(pdbe).getFile();
547 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
548 sb.append(getSsm().printMappings(pdbfile, seqs));
550 return sb.toString();
554 * Returns the mapped structure position for a given aligned column of a given
555 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
556 * not mapped to structure.
563 protected int getMappedPosition(SequenceI seq, int alignedPos,
564 StructureMapping mapping)
566 if (alignedPos >= seq.getLength())
571 if (Comparison.isGap(seq.getCharAt(alignedPos)))
575 int seqPos = seq.findPosition(alignedPos);
576 int pos = mapping.getPDBResNum(seqPos);
581 * Helper method to identify residues that can participate in a structure
582 * superposition command. For each structure, identify a sequence in the
583 * alignment which is mapped to the structure. Identify non-gapped columns in
584 * the sequence which have a mapping to a residue in the structure. Returns
585 * the index of the first structure that has a mapping to the alignment.
588 * the sequence alignment which is the basis of structure
591 * a BitSet, where bit j is set to indicate that every structure has
592 * a mapped residue present in column j (so the column can
593 * participate in structure alignment)
595 * an array of data beans corresponding to pdb file index
598 protected int findSuperposableResidues(AlignmentI alignment,
599 BitSet matched, SuperposeData[] structures)
601 int refStructure = -1;
602 String[] files = getStructureFiles();
607 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
609 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
613 * Find the first mapped sequence (if any) for this PDB entry which is in
616 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
617 for (int s = 0; s < seqCountForPdbFile; s++)
619 for (StructureMapping mapping : mappings)
621 final SequenceI theSequence = getSequence()[pdbfnum][s];
622 if (mapping.getSequence() == theSequence
623 && alignment.findIndex(theSequence) > -1)
625 if (refStructure < 0)
627 refStructure = pdbfnum;
629 for (int r = 0; r < alignment.getWidth(); r++)
635 int pos = getMappedPosition(theSequence, r, mapping);
636 if (pos < 1 || pos == lastPos)
642 structures[pdbfnum].pdbResNo[r] = pos;
644 String chain = mapping.getChain();
645 if (chain != null && chain.trim().length() > 0)
647 structures[pdbfnum].chain = chain;
649 structures[pdbfnum].pdbId = mapping.getPdbId();
650 structures[pdbfnum].isRna = theSequence.getRNA() != null;
653 * move on to next pdb file (ignore sequences for other chains
654 * for the same structure)
656 s = seqCountForPdbFile;
666 * Returns true if the structure viewer has loaded all of the files of
667 * interest (identified by the file mapping having been set up), or false if
668 * any are still not loaded after a timeout interval.
672 protected boolean waitForFileLoad(String[] files)
675 * give up after 10 secs plus 1 sec per file
677 long starttime = System.currentTimeMillis();
678 long endTime = 10000 + 1000 * files.length + starttime;
679 String notLoaded = null;
681 boolean waiting = true;
682 while (waiting && System.currentTimeMillis() < endTime)
685 for (String file : files)
694 StructureMapping[] sm = getSsm().getMapping(file);
695 if (sm == null || sm.length == 0)
699 } catch (Throwable x)
709 "Timed out waiting for structure viewer to load file "
717 public boolean isListeningFor(SequenceI seq)
719 if (sequence != null)
721 for (SequenceI[] seqs : sequence)
725 for (SequenceI s : seqs)
727 if (s == seq || (s.getDatasetSequence() != null
728 && s.getDatasetSequence() == seq.getDatasetSequence()))
739 public boolean isFinishedInit()
744 public void setFinishedInit(boolean fi)
746 this.finishedInit = fi;
750 * Returns a list of chains mapped in this viewer.
754 public abstract List<String> getChainNames();
757 * Returns the Jalview panel hosting the structure viewer (if any)
761 public JalviewStructureDisplayI getViewer()
766 public abstract void setJalviewColourScheme(ColourSchemeI cs);
769 * Constructs and sends a command to align structures against a reference
770 * structure, based on one or more sequence alignments. May optionally return
771 * an error or warning message for the alignment command.
774 * an array of alignments to process
775 * @param structureIndices
776 * an array of corresponding reference structures (index into pdb
777 * file array); if a negative value is passed, the first PDB file
778 * mapped to an alignment sequence is used as the reference for
781 * an array of corresponding hidden columns for each alignment
784 public abstract String superposeStructures(AlignmentI[] alignments,
785 int[] structureIndices, HiddenColumns[] hiddenCols);
787 public abstract void setBackgroundColour(Color col);
789 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
790 String[] files, AlignmentViewPanel avp);
793 * returns the current sequenceRenderer that should be used to colour the
800 public abstract SequenceRenderer getSequenceRenderer(
801 AlignmentViewPanel alignment);
803 protected abstract void colourBySequence(
804 StructureMappingcommandSet[] colourBySequenceCommands);
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 colourBySequence(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)
840 String[] files = getStructureFiles();
842 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
844 colourBySequence(colourBySequenceCommands);
847 public boolean hasFileLoadingError()
849 return fileLoadingError != null && fileLoadingError.length() > 0;
852 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
853 AlignmentViewPanel alignment);
856 * Sets the flag for whether only mapped visible residues in the alignment
857 * should be visible in the structure viewer
861 public void setShowAlignmentOnly(boolean b)
863 showAlignmentOnly = b;
867 * Answers true if only residues mapped to the alignment should be shown in the
868 * structure viewer, else false
872 public boolean isShowAlignmentOnly()
874 return showAlignmentOnly;
878 * Sets the flag for hiding regions of structure which are hidden in the
879 * alignment (only applies when the structure viewer is restricted to the
884 public void setHideHiddenRegions(boolean b)
886 hideHiddenRegions = b;
890 * Answers true if regions hidden in the alignment should also be hidden in the
891 * structure viewer, else false (only applies when the structure viewer is
892 * restricted to the alignment only)
896 public boolean isHideHiddenRegions()
898 return hideHiddenRegions;
902 * Shows the structures in the viewer, without changing their colouring. This is
903 * to support toggling of whether the whole structure is shown, or only residues
904 * mapped to visible regions of the alignment.
906 * @param alignViewportI
908 * if true, refit the display to the viewer
910 public void showStructures(AlignViewportI alignViewportI, boolean refocus)
912 // override with implementation
916 public void updateColours(Object source)
918 AlignmentViewPanel ap = (AlignmentViewPanel) source;
919 // ignore events from panels not used to colour this view
920 if (!getViewer().isUsedforcolourby(ap))
924 if (!isLoadingFromArchive())
926 colourBySequence(ap);
931 * Sets the list of chains to display (as "pdbid:chain"), where an empty list
936 public void setChainsToShow(List<String> chains)
938 chainsToShow = chains;
942 * Answers true if the specified structure and chain are selected to be shown in
943 * the viewer, else false
949 protected boolean isShowChain(String pdbId, String chainId)
951 if (chainsToShow.isEmpty())
955 return chainsToShow.contains(pdbId + ":" + chainId);