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.SequenceRendererI;
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.gui.AlignmentPanel;
33 import jalview.gui.SequenceRenderer;
34 import jalview.io.DataSourceType;
35 import jalview.schemes.ColourSchemeI;
36 import jalview.structure.AtomSpec;
37 import jalview.structure.StructureListener;
38 import jalview.structure.StructureMapping;
39 import jalview.structure.StructureMappingcommandSet;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.util.Comparison;
42 import jalview.util.MessageManager;
44 import java.awt.Color;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.BitSet;
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
65 Sequence, Chain, ChargeAndCysteine, Jalview, Viewer
69 * selected colour menu option
71 private ColourBy colourBy = ColourBy.Sequence;
74 * selected colour scheme, if a Jalview colour scheme is selected
76 private ColourSchemeI colourScheme;
79 * flag for whether to include feature colouring, if using a Jalview colour
80 * scheme (independently of whether features are shown on alignment)
82 private boolean showFeatures;
84 private StructureSelectionManager ssm;
87 * distinct PDB entries (pdb files) associated
90 private PDBEntry[] pdbEntry;
93 * sequences mapped to each pdbentry
95 private SequenceI[][] sequence;
98 * array of target chains for sequences - tied to pdbentry and sequence[]
100 private String[][] chains;
103 * datasource protocol for access to PDBEntrylatest
105 DataSourceType protocol = null;
107 private boolean nucleotide;
109 private boolean finishedInit = false;
112 * current set of model filenames loaded in the Jmol instance
114 protected String[] modelFileNames = null;
116 public String fileLoadingError;
119 * Data bean class to simplify parameterisation in superposeStructures
121 protected class SuperposeData
124 * Constructor with alignment width argument
128 public SuperposeData(int width)
130 pdbResNo = new int[width];
133 public String filename;
137 public String chain = "";
139 public boolean isRna;
142 * The pdb residue number (if any) mapped to each column of the alignment
144 public int[] pdbResNo;
153 public AAStructureBindingModel(StructureSelectionManager ssm,
157 this.sequence = seqs;
168 public AAStructureBindingModel(StructureSelectionManager ssm,
169 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
170 DataSourceType protocol)
173 this.sequence = sequenceIs;
174 this.nucleotide = Comparison.isNucleotide(sequenceIs);
175 this.pdbEntry = pdbentry;
176 this.protocol = protocol;
180 private boolean resolveChains()
183 * final count of chain mappings discovered
186 // JBPNote: JAL-2693 - this should be a list of chain mappings per
187 // [pdbentry][sequence]
188 String[][] newchains = new String[pdbEntry.length][];
190 for (PDBEntry pdb : pdbEntry)
192 SequenceI[] seqsForPdb = sequence[pe];
193 if (seqsForPdb != null)
195 newchains[pe] = new String[seqsForPdb.length];
197 for (SequenceI asq : seqsForPdb)
199 String chain = (chains != null && chains[pe] != null)
202 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
203 : asq.getDatasetSequence();
204 if (sq.getAllPDBEntries() != null)
206 for (PDBEntry pdbentry : sq.getAllPDBEntries())
208 if (pdb.getFile() != null && pdbentry.getFile() != null
209 && pdb.getFile().equals(pdbentry.getFile()))
211 String chaincode = pdbentry.getChainCode();
212 if (chaincode != null && chaincode.length() > 0)
221 newchains[pe][se] = chain;
229 return chainmaps > 0;
231 public StructureSelectionManager getSsm()
237 * Returns the i'th PDBEntry (or null)
242 public PDBEntry getPdbEntry(int i)
244 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
248 * Answers true if this binding includes the given PDB id, else false
253 public boolean hasPdbId(String pdbId)
255 if (pdbEntry != null)
257 for (PDBEntry pdb : pdbEntry)
259 if (pdb.getId().equals(pdbId))
269 * Returns the number of modelled PDB file entries.
273 public int getPdbCount()
275 return pdbEntry == null ? 0 : pdbEntry.length;
278 public SequenceI[][] getSequence()
283 public String[][] getChains()
288 public DataSourceType getProtocol()
293 // TODO may remove this if calling methods can be pulled up here
294 protected void setPdbentry(PDBEntry[] pdbentry)
296 this.pdbEntry = pdbentry;
299 protected void setSequence(SequenceI[][] sequence)
301 this.sequence = sequence;
304 protected void setChains(String[][] chains)
306 this.chains = chains;
310 * Construct a title string for the viewer window based on the data Jalview
319 public String getViewerTitle(String viewerName, boolean verbose)
321 if (getSequence() == null || getSequence().length < 1
322 || getPdbCount() < 1 || getSequence()[0].length < 1)
324 return ("Jalview " + viewerName + " Window");
326 // TODO: give a more informative title when multiple structures are
328 StringBuilder title = new StringBuilder(64);
329 final PDBEntry pdbe = getPdbEntry(0);
330 title.append(viewerName + " view for " + getSequence()[0][0].getName()
331 + ":" + pdbe.getId());
335 String method = (String) pdbe.getProperty("method");
338 title.append(" Method: ").append(method);
340 String chain = (String) pdbe.getProperty("chains");
343 title.append(" Chain:").append(chain);
346 return title.toString();
350 * Called by after closeViewer is called, to release any resources and
351 * references so they can be garbage collected. Override if needed.
353 protected void releaseUIResources()
358 public void setColourBy(ColourBy option)
363 public boolean isColourBySequence()
365 return colourBy == ColourBy.Sequence;
368 protected boolean isJalviewColourScheme()
370 return colourBy == ColourBy.Jalview;
373 protected void addSequenceAndChain(int pe, SequenceI[] seq,
376 if (pe < 0 || pe >= getPdbCount())
378 throw new Error(MessageManager.formatMessage(
379 "error.implementation_error_no_pdbentry_from_index",
381 { Integer.valueOf(pe).toString() }));
383 final String nullChain = "TheNullChain";
384 List<SequenceI> s = new ArrayList<SequenceI>();
385 List<String> c = new ArrayList<String>();
386 if (getChains() == null)
388 setChains(new String[getPdbCount()][]);
390 if (getSequence()[pe] != null)
392 for (int i = 0; i < getSequence()[pe].length; i++)
394 s.add(getSequence()[pe][i]);
395 if (getChains()[pe] != null)
397 if (i < getChains()[pe].length)
399 c.add(getChains()[pe][i]);
408 if (tchain != null && tchain.length > 0)
415 for (int i = 0; i < seq.length; i++)
417 if (!s.contains(seq[i]))
420 if (tchain != null && i < tchain.length)
422 c.add(tchain[i] == null ? nullChain : tchain[i]);
426 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
427 getSequence()[pe] = tmp;
430 String[] tch = c.toArray(new String[c.size()]);
431 for (int i = 0; i < tch.length; i++)
433 if (tch[i] == nullChain)
438 getChains()[pe] = tch;
442 getChains()[pe] = null;
447 * add structures and any known sequence associations
449 * @returns the pdb entries added to the current set.
451 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
452 SequenceI[][] seq, String[][] chns)
454 List<PDBEntry> v = new ArrayList<PDBEntry>();
455 List<int[]> rtn = new ArrayList<int[]>();
456 for (int i = 0; i < getPdbCount(); i++)
458 v.add(getPdbEntry(i));
460 for (int i = 0; i < pdbe.length; i++)
462 int r = v.indexOf(pdbe[i]);
463 if (r == -1 || r >= getPdbCount())
465 rtn.add(new int[] { v.size(), i });
470 // just make sure the sequence/chain entries are all up to date
471 addSequenceAndChain(r, seq[i], chns[i]);
474 pdbe = v.toArray(new PDBEntry[v.size()]);
478 // expand the tied sequence[] and string[] arrays
479 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
480 String[][] sch = new String[getPdbCount()][];
481 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
482 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
485 pdbe = new PDBEntry[rtn.size()];
486 for (int r = 0; r < pdbe.length; r++)
488 int[] stri = (rtn.get(r));
489 // record the pdb file as a new addition
490 pdbe[r] = getPdbEntry(stri[0]);
491 // and add the new sequence/chain entries
492 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
503 * Add sequences to the pe'th pdbentry's sequence set.
508 public void addSequence(int pe, SequenceI[] seq)
510 addSequenceAndChain(pe, seq, null);
514 * add the given sequences to the mapping scope for the given pdb file handle
517 * - pdbFile identifier
519 * - set of sequences it can be mapped to
521 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
523 for (int pe = 0; pe < getPdbCount(); pe++)
525 if (getPdbEntry(pe).getFile().equals(pdbFile))
527 addSequence(pe, seq);
533 public abstract void highlightAtoms(List<AtomSpec> atoms);
535 protected boolean isNucleotide()
537 return this.nucleotide;
541 * Returns a readable description of all mappings for the wrapped pdbfile to
542 * any mapped sequences
548 public String printMappings()
550 if (pdbEntry == null)
554 StringBuilder sb = new StringBuilder(128);
555 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
557 String pdbfile = getPdbEntry(pdbe).getFile();
558 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
559 sb.append(getSsm().printMappings(pdbfile, seqs));
561 return sb.toString();
565 * Returns the mapped structure position for a given aligned column of a given
566 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
567 * not mapped to structure.
574 protected int getMappedPosition(SequenceI seq, int alignedPos,
575 StructureMapping mapping)
577 if (alignedPos >= seq.getLength())
582 if (Comparison.isGap(seq.getCharAt(alignedPos)))
586 int seqPos = seq.findPosition(alignedPos);
587 int pos = mapping.getPDBResNum(seqPos);
592 * Helper method to identify residues that can participate in a structure
593 * superposition command. For each structure, identify a sequence in the
594 * alignment which is mapped to the structure. Identify non-gapped columns in
595 * the sequence which have a mapping to a residue in the structure. Returns
596 * the index of the first structure that has a mapping to the alignment.
599 * the sequence alignment which is the basis of structure
602 * a BitSet, where bit j is set to indicate that every structure has
603 * a mapped residue present in column j (so the column can
604 * participate in structure alignment)
606 * an array of data beans corresponding to pdb file index
609 protected int findSuperposableResidues(AlignmentI alignment,
610 BitSet matched, SuperposeData[] structures)
612 int refStructure = -1;
613 String[] files = getStructureFiles();
618 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
620 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
624 * Find the first mapped sequence (if any) for this PDB entry which is in
627 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
628 for (int s = 0; s < seqCountForPdbFile; s++)
630 for (StructureMapping mapping : mappings)
632 final SequenceI theSequence = getSequence()[pdbfnum][s];
633 if (mapping.getSequence() == theSequence
634 && alignment.findIndex(theSequence) > -1)
636 if (refStructure < 0)
638 refStructure = pdbfnum;
640 for (int r = 0; r < alignment.getWidth(); r++)
646 int pos = getMappedPosition(theSequence, r, mapping);
647 if (pos < 1 || pos == lastPos)
653 structures[pdbfnum].pdbResNo[r] = pos;
655 String chain = mapping.getChain();
656 if (chain != null && chain.trim().length() > 0)
658 structures[pdbfnum].chain = chain;
660 structures[pdbfnum].pdbId = mapping.getPdbId();
661 structures[pdbfnum].isRna = theSequence.getRNA() != null;
664 * move on to next pdb file (ignore sequences for other chains
665 * for the same structure)
667 s = seqCountForPdbFile;
677 * Returns true if the structure viewer has loaded all of the files of
678 * interest (identified by the file mapping having been set up), or false if
679 * any are still not loaded after a timeout interval.
683 protected boolean waitForFileLoad(String[] files)
686 * give up after 10 secs plus 1 sec per file
688 long starttime = System.currentTimeMillis();
689 long endTime = 10000 + 1000 * files.length + starttime;
690 String notLoaded = null;
692 boolean waiting = true;
693 while (waiting && System.currentTimeMillis() < endTime)
696 for (String file : files)
705 StructureMapping[] sm = getSsm().getMapping(file);
706 if (sm == null || sm.length == 0)
710 } catch (Throwable x)
720 "Timed out waiting for structure viewer to load file "
728 public boolean isListeningFor(SequenceI seq)
730 if (sequence != null)
732 for (SequenceI[] seqs : sequence)
736 for (SequenceI s : seqs)
738 if (s == seq || (s.getDatasetSequence() != null
739 && s.getDatasetSequence() == seq.getDatasetSequence()))
750 public boolean isFinishedInit()
755 public void setFinishedInit(boolean fi)
757 this.finishedInit = fi;
761 * Returns a list of chains mapped in this viewer.
765 public abstract List<String> getChainNames();
768 * Returns the Jalview panel hosting the structure viewer (if any)
772 public JalviewStructureDisplayI getViewer()
778 * Sets the selected colour scheme, possibly with reference to the given
785 public void setJalviewColourScheme(ColourSchemeI cs, AlignmentViewPanel ap,
788 colourBy = ColourBy.Jalview;
790 showFeatures = showFeats;
792 if (!showFeats && (cs == null || cs.isSimple()))
794 setSimpleColourScheme(cs);
798 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport(), cs), showFeatures);
803 * Sets a colour scheme which is determined solely by the residue at each
808 protected abstract void setSimpleColourScheme(ColourSchemeI cs);
811 * Constructs and sends a command to align structures against a reference
812 * structure, based on one or more sequence alignments. May optionally return
813 * an error or warning message for the alignment command.
816 * an array of alignments to process
817 * @param structureIndices
818 * an array of corresponding reference structures (index into pdb
819 * file array); if a negative value is passed, the first PDB file
820 * mapped to an alignment sequence is used as the reference for
823 * an array of corresponding hidden columns for each alignment
826 public abstract String superposeStructures(AlignmentI[] alignments,
827 int[] structureIndices, HiddenColumns[] hiddenCols);
829 public abstract void setBackgroundColour(Color col);
831 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
832 String[] files, SequenceRendererI sr, AlignmentViewPanel avp, boolean showFeatures);
834 protected abstract void colourBySequence(
835 StructureMappingcommandSet[] colourBySequenceCommands);
837 public void colourByChain()
839 colourBy = ColourBy.Chain;
842 public void colourByCharge()
844 colourBy = ColourBy.ChargeAndCysteine;
847 public void colourBySequence(AlignmentViewPanel alignmentv, boolean showFeatures)
849 colourBySequence(alignmentv, alignmentv.getSequenceRenderer(), showFeatures);
853 * Colours any structures associated with sequences in the given alignment view
854 * using the getFeatureRenderer() and getSequenceRenderer() renderers
856 public void colourBySequence(AlignmentViewPanel alignmentv, SequenceRendererI sr, boolean showFeats)
858 showFeatures = showFeats;
859 colourBy = ColourBy.Sequence;
861 if (!isLoadingFinished())
865 if (getSsm() == null)
869 String[] files = getStructureFiles();
871 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
872 files, sr, alignmentv, showFeatures);
873 colourBySequence(colourBySequenceCommands);
876 public boolean hasFileLoadingError()
878 return fileLoadingError != null && fileLoadingError.length() > 0;
881 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
882 AlignmentViewPanel alignment);
885 public void updateColours(Object source) {
886 AlignmentPanel ap = (AlignmentPanel) source;
889 * ignore events from panels not used to colour this view
891 if (!getViewer().isUsedForColourBy(ap))
897 * no need to update colours if structure colouring is not
900 if (!isColourBySequence() && !isJalviewColourScheme())
904 if (!isColourBySequence() && !showFeatures &&
905 (colourScheme == null || colourScheme.isSimple()))
910 if (!isLoadingFromArchive())
912 AlignViewportI av = ap.getAlignViewport();
913 if (isColourBySequence())
915 showFeatures = av.isShowSequenceFeatures();
916 colourBySequence(ap, new SequenceRenderer(av),
921 colourBySequence(ap, new SequenceRenderer(av,
922 colourScheme), showFeatures);