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.AlignmentViewPanel;
24 import jalview.api.SequenceRendererI;
25 import jalview.api.StructureSelectionManagerProvider;
26 import jalview.api.structures.JalviewStructureDisplayI;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.AlignmentPanel;
32 import jalview.gui.SequenceRenderer;
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.List;
51 * A base class to hold common function for protein structure model binding.
52 * Initial version created by refactoring JMol and Chimera binding models, but
53 * other structure viewers could in principle be accommodated in future.
58 public abstract class AAStructureBindingModel
59 extends SequenceStructureBindingModel
60 implements StructureListener, StructureSelectionManagerProvider
64 Sequence, Chain, ChargeAndCysteine, Jalview, Viewer
68 * selected colour menu option
70 private ColourBy colourBy = ColourBy.Sequence;
73 * selected colour scheme, if a Jalview colour scheme is selected
75 private ColourSchemeI colourScheme;
77 private StructureSelectionManager ssm;
80 * distinct PDB entries (pdb files) associated
83 private PDBEntry[] pdbEntry;
86 * sequences mapped to each pdbentry
88 private SequenceI[][] sequence;
91 * array of target chains for sequences - tied to pdbentry and sequence[]
93 private String[][] chains;
96 * datasource protocol for access to PDBEntrylatest
98 DataSourceType protocol = null;
100 private boolean nucleotide;
102 private boolean finishedInit = false;
105 * current set of model filenames loaded in the Jmol instance
107 protected String[] modelFileNames = null;
109 public String fileLoadingError;
112 * Data bean class to simplify parameterisation in superposeStructures
114 protected class SuperposeData
117 * Constructor with alignment width argument
121 public SuperposeData(int width)
123 pdbResNo = new int[width];
126 public String filename;
130 public String chain = "";
132 public boolean isRna;
135 * The pdb residue number (if any) mapped to each column of the alignment
137 public int[] pdbResNo;
146 public AAStructureBindingModel(StructureSelectionManager ssm,
150 this.sequence = seqs;
161 public AAStructureBindingModel(StructureSelectionManager ssm,
162 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
163 DataSourceType protocol)
166 this.sequence = sequenceIs;
167 this.nucleotide = Comparison.isNucleotide(sequenceIs);
168 this.pdbEntry = pdbentry;
169 this.protocol = protocol;
173 private boolean resolveChains()
176 * final count of chain mappings discovered
179 // JBPNote: JAL-2693 - this should be a list of chain mappings per
180 // [pdbentry][sequence]
181 String[][] newchains = new String[pdbEntry.length][];
183 for (PDBEntry pdb : pdbEntry)
185 SequenceI[] seqsForPdb = sequence[pe];
186 if (seqsForPdb != null)
188 newchains[pe] = new String[seqsForPdb.length];
190 for (SequenceI asq : seqsForPdb)
192 String chain = (chains != null && chains[pe] != null)
195 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
196 : asq.getDatasetSequence();
197 if (sq.getAllPDBEntries() != null)
199 for (PDBEntry pdbentry : sq.getAllPDBEntries())
201 if (pdb.getFile() != null && pdbentry.getFile() != null
202 && pdb.getFile().equals(pdbentry.getFile()))
204 String chaincode = pdbentry.getChainCode();
205 if (chaincode != null && chaincode.length() > 0)
214 newchains[pe][se] = chain;
222 return chainmaps > 0;
224 public StructureSelectionManager getSsm()
230 * Returns the i'th PDBEntry (or null)
235 public PDBEntry getPdbEntry(int i)
237 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
241 * Answers true if this binding includes the given PDB id, else false
246 public boolean hasPdbId(String pdbId)
248 if (pdbEntry != null)
250 for (PDBEntry pdb : pdbEntry)
252 if (pdb.getId().equals(pdbId))
262 * Returns the number of modelled PDB file entries.
266 public int getPdbCount()
268 return pdbEntry == null ? 0 : pdbEntry.length;
271 public SequenceI[][] getSequence()
276 public String[][] getChains()
281 public DataSourceType getProtocol()
286 // TODO may remove this if calling methods can be pulled up here
287 protected void setPdbentry(PDBEntry[] pdbentry)
289 this.pdbEntry = pdbentry;
292 protected void setSequence(SequenceI[][] sequence)
294 this.sequence = sequence;
297 protected void setChains(String[][] chains)
299 this.chains = chains;
303 * Construct a title string for the viewer window based on the data Jalview
312 public String getViewerTitle(String viewerName, boolean verbose)
314 if (getSequence() == null || getSequence().length < 1
315 || getPdbCount() < 1 || getSequence()[0].length < 1)
317 return ("Jalview " + viewerName + " Window");
319 // TODO: give a more informative title when multiple structures are
321 StringBuilder title = new StringBuilder(64);
322 final PDBEntry pdbe = getPdbEntry(0);
323 title.append(viewerName + " view for " + getSequence()[0][0].getName()
324 + ":" + pdbe.getId());
328 String method = (String) pdbe.getProperty("method");
331 title.append(" Method: ").append(method);
333 String chain = (String) pdbe.getProperty("chains");
336 title.append(" Chain:").append(chain);
339 return title.toString();
343 * Called by after closeViewer is called, to release any resources and
344 * references so they can be garbage collected. Override if needed.
346 protected void releaseUIResources()
351 public void setColourBy(ColourBy option)
356 public boolean isColourBySequence()
358 return colourBy == ColourBy.Sequence;
361 protected boolean isJalviewColourScheme()
363 return colourBy == ColourBy.Jalview;
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<SequenceI>();
378 List<String> c = new ArrayList<String>();
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<PDBEntry>();
448 List<int[]> rtn = new ArrayList<int[]>();
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 a list of chains mapped in this viewer.
758 public abstract List<String> getChainNames();
761 * Returns the Jalview panel hosting the structure viewer (if any)
765 public JalviewStructureDisplayI getViewer()
771 * Sets the selected colour scheme, possibly with reference to the given
777 public void setJalviewColourScheme(ColourSchemeI cs, AlignmentViewPanel ap)
779 colourBy = ColourBy.Jalview;
782 if (cs == null || cs.isSimple())
784 setSimpleColourScheme(cs);
788 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport(), cs));
793 * Sets a colour scheme which is determined solely by the residue at each
798 protected abstract void setSimpleColourScheme(ColourSchemeI cs);
801 * Constructs and sends a command to align structures against a reference
802 * structure, based on one or more sequence alignments. May optionally return
803 * an error or warning message for the alignment command.
806 * an array of alignments to process
807 * @param structureIndices
808 * an array of corresponding reference structures (index into pdb
809 * file array); if a negative value is passed, the first PDB file
810 * mapped to an alignment sequence is used as the reference for
813 * an array of corresponding hidden columns for each alignment
816 public abstract String superposeStructures(AlignmentI[] alignments,
817 int[] structureIndices, HiddenColumns[] hiddenCols);
819 public abstract void setBackgroundColour(Color col);
821 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
822 String[] files, SequenceRendererI sr, AlignmentViewPanel avp);
824 protected abstract void colourBySequence(
825 StructureMappingcommandSet[] colourBySequenceCommands);
827 public void colourByChain()
829 colourBy = ColourBy.Chain;
832 public void colourByCharge()
834 colourBy = ColourBy.ChargeAndCysteine;
837 public void colourBySequence(AlignmentViewPanel alignmentv)
839 colourBySequence(alignmentv, alignmentv.getSequenceRenderer());
843 * Colours any structures associated with sequences in the given alignment view
844 * using the getFeatureRenderer() and getSequenceRenderer() renderers
846 public void colourBySequence(AlignmentViewPanel alignmentv, SequenceRendererI sr)
848 if (!isLoadingFinished())
852 if (getSsm() == null)
856 String[] files = getStructureFiles();
858 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
859 files, sr, alignmentv);
860 colourBySequence(colourBySequenceCommands);
863 public boolean hasFileLoadingError()
865 return fileLoadingError != null && fileLoadingError.length() > 0;
868 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
869 AlignmentViewPanel alignment);
872 public void updateColours(Object source) {
873 AlignmentPanel ap = (AlignmentPanel) source;
876 * ignore events from panels not used to colour this view
878 if (!getViewer().isUsedForColourBy(ap))
884 * no need to update colours if structure colouring is not
887 if (!isColourBySequence() && !isJalviewColourScheme())
891 if (colourScheme == null || colourScheme.isSimple())
896 if (!isLoadingFromArchive())
898 if (isColourBySequence())
900 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport()));
904 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport(), colourScheme));