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;
108 * Data bean class to simplify parameterisation in superposeStructures
110 protected class SuperposeData
113 * Constructor with alignment width argument
117 public SuperposeData(int width)
119 pdbResNo = new int[width];
122 public String filename;
126 public String chain = "";
128 public boolean isRna;
131 * The pdb residue number (if any) mapped to each column of the alignment
133 public int[] pdbResNo;
142 public AAStructureBindingModel(StructureSelectionManager ssm,
146 this.sequence = seqs;
147 chainsToShow = new ArrayList<>();
158 public AAStructureBindingModel(StructureSelectionManager ssm,
159 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
160 DataSourceType protocol)
163 this.sequence = sequenceIs;
164 this.nucleotide = Comparison.isNucleotide(sequenceIs);
165 this.pdbEntry = pdbentry;
166 this.protocol = protocol;
167 chainsToShow = new ArrayList<>();
172 private boolean resolveChains()
175 * final count of chain mappings discovered
178 // JBPNote: JAL-2693 - this should be a list of chain mappings per
179 // [pdbentry][sequence]
180 String[][] newchains = new String[pdbEntry.length][];
182 for (PDBEntry pdb : pdbEntry)
184 SequenceI[] seqsForPdb = sequence[pe];
185 if (seqsForPdb != null)
187 newchains[pe] = new String[seqsForPdb.length];
189 for (SequenceI asq : seqsForPdb)
191 String chain = (chains != null && chains[pe] != null)
194 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
195 : asq.getDatasetSequence();
196 if (sq.getAllPDBEntries() != null)
198 for (PDBEntry pdbentry : sq.getAllPDBEntries())
200 if (pdb.getFile() != null && pdbentry.getFile() != null
201 && pdb.getFile().equals(pdbentry.getFile()))
203 String chaincode = pdbentry.getChainCode();
204 if (chaincode != null && chaincode.length() > 0)
213 newchains[pe][se] = chain;
221 return chainmaps > 0;
223 public StructureSelectionManager getSsm()
229 * Returns the i'th PDBEntry (or null)
234 public PDBEntry getPdbEntry(int i)
236 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
240 * Answers true if this binding includes the given PDB id, else false
245 public boolean hasPdbId(String pdbId)
247 if (pdbEntry != null)
249 for (PDBEntry pdb : pdbEntry)
251 if (pdb.getId().equals(pdbId))
261 * Returns the number of modelled PDB file entries.
265 public int getPdbCount()
267 return pdbEntry == null ? 0 : pdbEntry.length;
270 public SequenceI[][] getSequence()
275 public String[][] getChains()
280 public DataSourceType getProtocol()
285 // TODO may remove this if calling methods can be pulled up here
286 protected void setPdbentry(PDBEntry[] pdbentry)
288 this.pdbEntry = pdbentry;
291 protected void setSequence(SequenceI[][] sequence)
293 this.sequence = sequence;
296 protected void setChains(String[][] chains)
298 this.chains = chains;
302 * Construct a title string for the viewer window based on the data Jalview
311 public String getViewerTitle(String viewerName, boolean verbose)
313 if (getSequence() == null || getSequence().length < 1
314 || getPdbCount() < 1 || getSequence()[0].length < 1)
316 return ("Jalview " + viewerName + " Window");
318 // TODO: give a more informative title when multiple structures are
320 StringBuilder title = new StringBuilder(64);
321 final PDBEntry pdbe = getPdbEntry(0);
322 title.append(viewerName + " view for " + getSequence()[0][0].getName()
323 + ":" + pdbe.getId());
327 String method = (String) pdbe.getProperty("method");
330 title.append(" Method: ").append(method);
332 String chain = (String) pdbe.getProperty("chains");
335 title.append(" Chain:").append(chain);
338 return title.toString();
342 * Called by after closeViewer is called, to release any resources and
343 * references so they can be garbage collected. Override if needed.
345 protected void releaseUIResources()
350 public boolean isColourBySequence()
352 return colourBySequence;
355 public void setColourBySequence(boolean colourBySequence)
357 this.colourBySequence = colourBySequence;
360 protected void addSequenceAndChain(int pe, SequenceI[] seq,
363 if (pe < 0 || pe >= getPdbCount())
365 throw new Error(MessageManager.formatMessage(
366 "error.implementation_error_no_pdbentry_from_index",
368 { Integer.valueOf(pe).toString() }));
370 final String nullChain = "TheNullChain";
371 List<SequenceI> s = new ArrayList<>();
372 List<String> c = new ArrayList<>();
373 if (getChains() == null)
375 setChains(new String[getPdbCount()][]);
377 if (getSequence()[pe] != null)
379 for (int i = 0; i < getSequence()[pe].length; i++)
381 s.add(getSequence()[pe][i]);
382 if (getChains()[pe] != null)
384 if (i < getChains()[pe].length)
386 c.add(getChains()[pe][i]);
395 if (tchain != null && tchain.length > 0)
402 for (int i = 0; i < seq.length; i++)
404 if (!s.contains(seq[i]))
407 if (tchain != null && i < tchain.length)
409 c.add(tchain[i] == null ? nullChain : tchain[i]);
413 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
414 getSequence()[pe] = tmp;
417 String[] tch = c.toArray(new String[c.size()]);
418 for (int i = 0; i < tch.length; i++)
420 if (tch[i] == nullChain)
425 getChains()[pe] = tch;
429 getChains()[pe] = null;
434 * add structures and any known sequence associations
436 * @returns the pdb entries added to the current set.
438 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
439 SequenceI[][] seq, String[][] chns)
441 List<PDBEntry> v = new ArrayList<>();
442 List<int[]> rtn = new ArrayList<>();
443 for (int i = 0; i < getPdbCount(); i++)
445 v.add(getPdbEntry(i));
447 for (int i = 0; i < pdbe.length; i++)
449 int r = v.indexOf(pdbe[i]);
450 if (r == -1 || r >= getPdbCount())
452 rtn.add(new int[] { v.size(), i });
457 // just make sure the sequence/chain entries are all up to date
458 addSequenceAndChain(r, seq[i], chns[i]);
461 pdbe = v.toArray(new PDBEntry[v.size()]);
465 // expand the tied sequence[] and string[] arrays
466 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
467 String[][] sch = new String[getPdbCount()][];
468 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
469 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
472 pdbe = new PDBEntry[rtn.size()];
473 for (int r = 0; r < pdbe.length; r++)
475 int[] stri = (rtn.get(r));
476 // record the pdb file as a new addition
477 pdbe[r] = getPdbEntry(stri[0]);
478 // and add the new sequence/chain entries
479 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
490 * Add sequences to the pe'th pdbentry's sequence set.
495 public void addSequence(int pe, SequenceI[] seq)
497 addSequenceAndChain(pe, seq, null);
501 * add the given sequences to the mapping scope for the given pdb file handle
504 * - pdbFile identifier
506 * - set of sequences it can be mapped to
508 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
510 for (int pe = 0; pe < getPdbCount(); pe++)
512 if (getPdbEntry(pe).getFile().equals(pdbFile))
514 addSequence(pe, seq);
520 public abstract void highlightAtoms(List<AtomSpec> atoms);
522 protected boolean isNucleotide()
524 return this.nucleotide;
528 * Returns a readable description of all mappings for the wrapped pdbfile to
529 * any mapped sequences
535 public String printMappings()
537 if (pdbEntry == null)
541 StringBuilder sb = new StringBuilder(128);
542 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
544 String pdbfile = getPdbEntry(pdbe).getFile();
545 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
546 sb.append(getSsm().printMappings(pdbfile, seqs));
548 return sb.toString();
552 * Returns the mapped structure position for a given aligned column of a given
553 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
554 * not mapped to structure.
561 protected int getMappedPosition(SequenceI seq, int alignedPos,
562 StructureMapping mapping)
564 if (alignedPos >= seq.getLength())
569 if (Comparison.isGap(seq.getCharAt(alignedPos)))
573 int seqPos = seq.findPosition(alignedPos);
574 int pos = mapping.getPDBResNum(seqPos);
579 * Helper method to identify residues that can participate in a structure
580 * superposition command. For each structure, identify a sequence in the
581 * alignment which is mapped to the structure. Identify non-gapped columns in
582 * the sequence which have a mapping to a residue in the structure. Returns
583 * the index of the first structure that has a mapping to the alignment.
586 * the sequence alignment which is the basis of structure
589 * a BitSet, where bit j is set to indicate that every structure has
590 * a mapped residue present in column j (so the column can
591 * participate in structure alignment)
593 * an array of data beans corresponding to pdb file index
596 protected int findSuperposableResidues(AlignmentI alignment,
597 BitSet matched, SuperposeData[] structures)
599 int refStructure = -1;
600 String[] files = getStructureFiles();
605 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
607 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
611 * Find the first mapped sequence (if any) for this PDB entry which is in
614 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
615 for (int s = 0; s < seqCountForPdbFile; s++)
617 for (StructureMapping mapping : mappings)
619 final SequenceI theSequence = getSequence()[pdbfnum][s];
620 if (mapping.getSequence() == theSequence
621 && alignment.findIndex(theSequence) > -1)
623 if (refStructure < 0)
625 refStructure = pdbfnum;
627 for (int r = 0; r < alignment.getWidth(); r++)
633 int pos = getMappedPosition(theSequence, r, mapping);
634 if (pos < 1 || pos == lastPos)
640 structures[pdbfnum].pdbResNo[r] = pos;
642 String chain = mapping.getChain();
643 if (chain != null && chain.trim().length() > 0)
645 structures[pdbfnum].chain = chain;
647 structures[pdbfnum].pdbId = mapping.getPdbId();
648 structures[pdbfnum].isRna = theSequence.getRNA() != null;
651 * move on to next pdb file (ignore sequences for other chains
652 * for the same structure)
654 s = seqCountForPdbFile;
664 * Returns true if the structure viewer has loaded all of the files of
665 * interest (identified by the file mapping having been set up), or false if
666 * any are still not loaded after a timeout interval.
670 protected boolean waitForFileLoad(String[] files)
673 * give up after 10 secs plus 1 sec per file
675 long starttime = System.currentTimeMillis();
676 long endTime = 10000 + 1000 * files.length + starttime;
677 String notLoaded = null;
679 boolean waiting = true;
680 while (waiting && System.currentTimeMillis() < endTime)
683 for (String file : files)
692 StructureMapping[] sm = getSsm().getMapping(file);
693 if (sm == null || sm.length == 0)
697 } catch (Throwable x)
707 "Timed out waiting for structure viewer to load file "
715 public boolean isListeningFor(SequenceI seq)
717 if (sequence != null)
719 for (SequenceI[] seqs : sequence)
723 for (SequenceI s : seqs)
725 if (s == seq || (s.getDatasetSequence() != null
726 && s.getDatasetSequence() == seq.getDatasetSequence()))
737 public boolean isFinishedInit()
742 public void setFinishedInit(boolean fi)
744 this.finishedInit = fi;
748 * Returns a list of chains mapped in this viewer.
752 public abstract List<String> getChainNames();
755 * Returns the Jalview panel hosting the structure viewer (if any)
759 public JalviewStructureDisplayI getViewer()
764 public abstract void setJalviewColourScheme(ColourSchemeI cs);
767 * Constructs and sends a command to align structures against a reference
768 * structure, based on one or more sequence alignments. May optionally return
769 * an error or warning message for the alignment command.
772 * an array of alignments to process
773 * @param structureIndices
774 * an array of corresponding reference structures (index into pdb
775 * file array); if a negative value is passed, the first PDB file
776 * mapped to an alignment sequence is used as the reference for
779 * an array of corresponding hidden columns for each alignment
782 public abstract String superposeStructures(AlignmentI[] alignments,
783 int[] structureIndices, HiddenColumns[] hiddenCols);
785 public abstract void setBackgroundColour(Color col);
787 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
788 String[] files, SequenceRenderer sr, AlignmentViewPanel avp);
791 * returns the current sequenceRenderer that should be used to colour the
798 public abstract SequenceRenderer getSequenceRenderer(
799 AlignmentViewPanel alignment);
801 protected abstract void colourBySequence(
802 StructureMappingcommandSet[] colourBySequenceCommands);
804 public abstract void colourByChain();
806 public abstract void colourByCharge();
809 * Recolours the displayed structures, if they are coloured by sequence, or
810 * 'show only visible alignment' is selected. This supports updating structure
811 * colours on either change of alignment colours, or change to the visible
812 * region of the alignment.
814 public void colourBySequence(AlignmentViewPanel alignmentv)
816 if (!isLoadingFinished())
820 // todo: property change event for visibleAlignment
821 // to avoid unnecessary redraws here
822 if (!colourBySequence && !isShowAlignmentOnly())
826 if (getSsm() == null)
830 String[] files = getStructureFiles();
832 SequenceRenderer sr = getSequenceRenderer(alignmentv);
834 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
835 files, sr, alignmentv);
836 colourBySequence(colourBySequenceCommands);
839 public boolean hasFileLoadingError()
841 return fileLoadingError != null && fileLoadingError.length() > 0;
844 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
845 AlignmentViewPanel alignment);
848 * Sets the flag for whether only mapped visible residues in the alignment
849 * should be visible in the structure viewer
853 public void setShowAlignmentOnly(boolean b)
855 showAlignmentOnly = b;
859 * Answers true if only mapped visible residues in the alignment should be
860 * visible in the structure viewer, else false
864 public boolean isShowAlignmentOnly()
866 return showAlignmentOnly;
870 * Shows the structures in the viewer, without changing their colouring. This is
871 * to support toggling of whether the whole structure is shown, or only residues
872 * mapped to visible regions of the alignment.
874 * @param alignViewportI
876 * if true, refit the display to the viewer
878 public void showStructures(AlignViewportI alignViewportI, boolean refocus)
880 // override with implementation
884 public void updateColours(Object source)
886 AlignmentViewPanel ap = (AlignmentViewPanel) source;
887 // ignore events from panels not used to colour this view
888 if (!getViewer().isUsedforcolourby(ap))
892 if (!isLoadingFromArchive())
894 colourBySequence(ap);
899 * Sets the list of chains to display (as "pdbid:chain"), where an empty list
904 public void setChainsToShow(List<String> chains)
906 chainsToShow = chains;
910 * Answers true if the specified structure and chain are selected to be shown in
911 * the viewer, else false
917 protected boolean isShowChain(String pdbId, String chainId)
919 if (chainsToShow.isEmpty())
923 return chainsToShow.contains(pdbId + ":" + chainId);