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;
49 import org.springframework.web.filter.ShallowEtagHeaderFilter;
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
66 Sequence, Chain, ChargeAndCysteine, Jalview, Viewer
70 * selected colour menu option
72 private ColourBy colourBy = ColourBy.Sequence;
75 * selected colour scheme, if a Jalview colour scheme is selected
77 private ColourSchemeI colourScheme;
80 * flag for whether to include feature colouring, if using a Jalview colour
81 * scheme (independently of whether features are shown on alignment)
83 private boolean showFeatures;
85 private StructureSelectionManager ssm;
88 * distinct PDB entries (pdb files) associated
91 private PDBEntry[] pdbEntry;
94 * sequences mapped to each pdbentry
96 private SequenceI[][] sequence;
99 * array of target chains for sequences - tied to pdbentry and sequence[]
101 private String[][] chains;
104 * datasource protocol for access to PDBEntrylatest
106 DataSourceType protocol = null;
108 private boolean nucleotide;
110 private boolean finishedInit = false;
113 * current set of model filenames loaded in the Jmol instance
115 protected String[] modelFileNames = null;
117 public String fileLoadingError;
120 * Data bean class to simplify parameterisation in superposeStructures
122 protected class SuperposeData
125 * Constructor with alignment width argument
129 public SuperposeData(int width)
131 pdbResNo = new int[width];
134 public String filename;
138 public String chain = "";
140 public boolean isRna;
143 * The pdb residue number (if any) mapped to each column of the alignment
145 public int[] pdbResNo;
154 public AAStructureBindingModel(StructureSelectionManager ssm,
158 this.sequence = seqs;
169 public AAStructureBindingModel(StructureSelectionManager ssm,
170 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
171 DataSourceType protocol)
174 this.sequence = sequenceIs;
175 this.nucleotide = Comparison.isNucleotide(sequenceIs);
176 this.pdbEntry = pdbentry;
177 this.protocol = protocol;
181 private boolean resolveChains()
184 * final count of chain mappings discovered
187 // JBPNote: JAL-2693 - this should be a list of chain mappings per
188 // [pdbentry][sequence]
189 String[][] newchains = new String[pdbEntry.length][];
191 for (PDBEntry pdb : pdbEntry)
193 SequenceI[] seqsForPdb = sequence[pe];
194 if (seqsForPdb != null)
196 newchains[pe] = new String[seqsForPdb.length];
198 for (SequenceI asq : seqsForPdb)
200 String chain = (chains != null && chains[pe] != null)
203 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
204 : asq.getDatasetSequence();
205 if (sq.getAllPDBEntries() != null)
207 for (PDBEntry pdbentry : sq.getAllPDBEntries())
209 if (pdb.getFile() != null && pdbentry.getFile() != null
210 && pdb.getFile().equals(pdbentry.getFile()))
212 String chaincode = pdbentry.getChainCode();
213 if (chaincode != null && chaincode.length() > 0)
222 newchains[pe][se] = chain;
230 return chainmaps > 0;
232 public StructureSelectionManager getSsm()
238 * Returns the i'th PDBEntry (or null)
243 public PDBEntry getPdbEntry(int i)
245 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
249 * Answers true if this binding includes the given PDB id, else false
254 public boolean hasPdbId(String pdbId)
256 if (pdbEntry != null)
258 for (PDBEntry pdb : pdbEntry)
260 if (pdb.getId().equals(pdbId))
270 * Returns the number of modelled PDB file entries.
274 public int getPdbCount()
276 return pdbEntry == null ? 0 : pdbEntry.length;
279 public SequenceI[][] getSequence()
284 public String[][] getChains()
289 public DataSourceType getProtocol()
294 // TODO may remove this if calling methods can be pulled up here
295 protected void setPdbentry(PDBEntry[] pdbentry)
297 this.pdbEntry = pdbentry;
300 protected void setSequence(SequenceI[][] sequence)
302 this.sequence = sequence;
305 protected void setChains(String[][] chains)
307 this.chains = chains;
311 * Construct a title string for the viewer window based on the data Jalview
320 public String getViewerTitle(String viewerName, boolean verbose)
322 if (getSequence() == null || getSequence().length < 1
323 || getPdbCount() < 1 || getSequence()[0].length < 1)
325 return ("Jalview " + viewerName + " Window");
327 // TODO: give a more informative title when multiple structures are
329 StringBuilder title = new StringBuilder(64);
330 final PDBEntry pdbe = getPdbEntry(0);
331 title.append(viewerName + " view for " + getSequence()[0][0].getName()
332 + ":" + pdbe.getId());
336 String method = (String) pdbe.getProperty("method");
339 title.append(" Method: ").append(method);
341 String chain = (String) pdbe.getProperty("chains");
344 title.append(" Chain:").append(chain);
347 return title.toString();
351 * Called by after closeViewer is called, to release any resources and
352 * references so they can be garbage collected. Override if needed.
354 protected void releaseUIResources()
359 public void setColourBy(ColourBy option)
364 public boolean isColourBySequence()
366 return colourBy == ColourBy.Sequence;
369 protected boolean isJalviewColourScheme()
371 return colourBy == ColourBy.Jalview;
374 protected void addSequenceAndChain(int pe, SequenceI[] seq,
377 if (pe < 0 || pe >= getPdbCount())
379 throw new Error(MessageManager.formatMessage(
380 "error.implementation_error_no_pdbentry_from_index",
382 { Integer.valueOf(pe).toString() }));
384 final String nullChain = "TheNullChain";
385 List<SequenceI> s = new ArrayList<SequenceI>();
386 List<String> c = new ArrayList<String>();
387 if (getChains() == null)
389 setChains(new String[getPdbCount()][]);
391 if (getSequence()[pe] != null)
393 for (int i = 0; i < getSequence()[pe].length; i++)
395 s.add(getSequence()[pe][i]);
396 if (getChains()[pe] != null)
398 if (i < getChains()[pe].length)
400 c.add(getChains()[pe][i]);
409 if (tchain != null && tchain.length > 0)
416 for (int i = 0; i < seq.length; i++)
418 if (!s.contains(seq[i]))
421 if (tchain != null && i < tchain.length)
423 c.add(tchain[i] == null ? nullChain : tchain[i]);
427 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
428 getSequence()[pe] = tmp;
431 String[] tch = c.toArray(new String[c.size()]);
432 for (int i = 0; i < tch.length; i++)
434 if (tch[i] == nullChain)
439 getChains()[pe] = tch;
443 getChains()[pe] = null;
448 * add structures and any known sequence associations
450 * @returns the pdb entries added to the current set.
452 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
453 SequenceI[][] seq, String[][] chns)
455 List<PDBEntry> v = new ArrayList<PDBEntry>();
456 List<int[]> rtn = new ArrayList<int[]>();
457 for (int i = 0; i < getPdbCount(); i++)
459 v.add(getPdbEntry(i));
461 for (int i = 0; i < pdbe.length; i++)
463 int r = v.indexOf(pdbe[i]);
464 if (r == -1 || r >= getPdbCount())
466 rtn.add(new int[] { v.size(), i });
471 // just make sure the sequence/chain entries are all up to date
472 addSequenceAndChain(r, seq[i], chns[i]);
475 pdbe = v.toArray(new PDBEntry[v.size()]);
479 // expand the tied sequence[] and string[] arrays
480 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
481 String[][] sch = new String[getPdbCount()][];
482 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
483 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
486 pdbe = new PDBEntry[rtn.size()];
487 for (int r = 0; r < pdbe.length; r++)
489 int[] stri = (rtn.get(r));
490 // record the pdb file as a new addition
491 pdbe[r] = getPdbEntry(stri[0]);
492 // and add the new sequence/chain entries
493 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
504 * Add sequences to the pe'th pdbentry's sequence set.
509 public void addSequence(int pe, SequenceI[] seq)
511 addSequenceAndChain(pe, seq, null);
515 * add the given sequences to the mapping scope for the given pdb file handle
518 * - pdbFile identifier
520 * - set of sequences it can be mapped to
522 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
524 for (int pe = 0; pe < getPdbCount(); pe++)
526 if (getPdbEntry(pe).getFile().equals(pdbFile))
528 addSequence(pe, seq);
534 public abstract void highlightAtoms(List<AtomSpec> atoms);
536 protected boolean isNucleotide()
538 return this.nucleotide;
542 * Returns a readable description of all mappings for the wrapped pdbfile to
543 * any mapped sequences
549 public String printMappings()
551 if (pdbEntry == null)
555 StringBuilder sb = new StringBuilder(128);
556 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
558 String pdbfile = getPdbEntry(pdbe).getFile();
559 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
560 sb.append(getSsm().printMappings(pdbfile, seqs));
562 return sb.toString();
566 * Returns the mapped structure position for a given aligned column of a given
567 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
568 * not mapped to structure.
575 protected int getMappedPosition(SequenceI seq, int alignedPos,
576 StructureMapping mapping)
578 if (alignedPos >= seq.getLength())
583 if (Comparison.isGap(seq.getCharAt(alignedPos)))
587 int seqPos = seq.findPosition(alignedPos);
588 int pos = mapping.getPDBResNum(seqPos);
593 * Helper method to identify residues that can participate in a structure
594 * superposition command. For each structure, identify a sequence in the
595 * alignment which is mapped to the structure. Identify non-gapped columns in
596 * the sequence which have a mapping to a residue in the structure. Returns
597 * the index of the first structure that has a mapping to the alignment.
600 * the sequence alignment which is the basis of structure
603 * a BitSet, where bit j is set to indicate that every structure has
604 * a mapped residue present in column j (so the column can
605 * participate in structure alignment)
607 * an array of data beans corresponding to pdb file index
610 protected int findSuperposableResidues(AlignmentI alignment,
611 BitSet matched, SuperposeData[] structures)
613 int refStructure = -1;
614 String[] files = getStructureFiles();
619 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
621 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
625 * Find the first mapped sequence (if any) for this PDB entry which is in
628 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
629 for (int s = 0; s < seqCountForPdbFile; s++)
631 for (StructureMapping mapping : mappings)
633 final SequenceI theSequence = getSequence()[pdbfnum][s];
634 if (mapping.getSequence() == theSequence
635 && alignment.findIndex(theSequence) > -1)
637 if (refStructure < 0)
639 refStructure = pdbfnum;
641 for (int r = 0; r < alignment.getWidth(); r++)
647 int pos = getMappedPosition(theSequence, r, mapping);
648 if (pos < 1 || pos == lastPos)
654 structures[pdbfnum].pdbResNo[r] = pos;
656 String chain = mapping.getChain();
657 if (chain != null && chain.trim().length() > 0)
659 structures[pdbfnum].chain = chain;
661 structures[pdbfnum].pdbId = mapping.getPdbId();
662 structures[pdbfnum].isRna = theSequence.getRNA() != null;
665 * move on to next pdb file (ignore sequences for other chains
666 * for the same structure)
668 s = seqCountForPdbFile;
678 * Returns true if the structure viewer has loaded all of the files of
679 * interest (identified by the file mapping having been set up), or false if
680 * any are still not loaded after a timeout interval.
684 protected boolean waitForFileLoad(String[] files)
687 * give up after 10 secs plus 1 sec per file
689 long starttime = System.currentTimeMillis();
690 long endTime = 10000 + 1000 * files.length + starttime;
691 String notLoaded = null;
693 boolean waiting = true;
694 while (waiting && System.currentTimeMillis() < endTime)
697 for (String file : files)
706 StructureMapping[] sm = getSsm().getMapping(file);
707 if (sm == null || sm.length == 0)
711 } catch (Throwable x)
721 "Timed out waiting for structure viewer to load file "
729 public boolean isListeningFor(SequenceI seq)
731 if (sequence != null)
733 for (SequenceI[] seqs : sequence)
737 for (SequenceI s : seqs)
739 if (s == seq || (s.getDatasetSequence() != null
740 && s.getDatasetSequence() == seq.getDatasetSequence()))
751 public boolean isFinishedInit()
756 public void setFinishedInit(boolean fi)
758 this.finishedInit = fi;
762 * Returns a list of chains mapped in this viewer.
766 public abstract List<String> getChainNames();
769 * Returns the Jalview panel hosting the structure viewer (if any)
773 public JalviewStructureDisplayI getViewer()
779 * Sets the selected colour scheme, possibly with reference to the given
786 public void setJalviewColourScheme(ColourSchemeI cs, AlignmentViewPanel ap,
789 colourBy = ColourBy.Jalview;
791 showFeatures = showFeats;
793 if (!showFeats && (cs == null || cs.isSimple()))
795 setSimpleColourScheme(cs);
799 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport(), cs), showFeatures);
804 * Sets a colour scheme which is determined solely by the residue at each
809 protected abstract void setSimpleColourScheme(ColourSchemeI cs);
812 * Constructs and sends a command to align structures against a reference
813 * structure, based on one or more sequence alignments. May optionally return
814 * an error or warning message for the alignment command.
817 * an array of alignments to process
818 * @param structureIndices
819 * an array of corresponding reference structures (index into pdb
820 * file array); if a negative value is passed, the first PDB file
821 * mapped to an alignment sequence is used as the reference for
824 * an array of corresponding hidden columns for each alignment
827 public abstract String superposeStructures(AlignmentI[] alignments,
828 int[] structureIndices, HiddenColumns[] hiddenCols);
830 public abstract void setBackgroundColour(Color col);
832 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
833 String[] files, SequenceRendererI sr, AlignmentViewPanel avp, boolean showFeatures);
835 protected abstract void colourBySequence(
836 StructureMappingcommandSet[] colourBySequenceCommands);
838 public void colourByChain()
840 colourBy = ColourBy.Chain;
843 public void colourByCharge()
845 colourBy = ColourBy.ChargeAndCysteine;
848 public void colourBySequence(AlignmentViewPanel alignmentv, boolean showFeatures)
850 colourBySequence(alignmentv, alignmentv.getSequenceRenderer(), showFeatures);
854 * Colours any structures associated with sequences in the given alignment view
855 * using the getFeatureRenderer() and getSequenceRenderer() renderers
857 public void colourBySequence(AlignmentViewPanel alignmentv, SequenceRendererI sr, boolean showFeats)
859 showFeatures = showFeats;
860 if (!isLoadingFinished())
864 if (getSsm() == null)
868 String[] files = getStructureFiles();
870 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
871 files, sr, alignmentv, showFeatures);
872 colourBySequence(colourBySequenceCommands);
875 public boolean hasFileLoadingError()
877 return fileLoadingError != null && fileLoadingError.length() > 0;
880 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
881 AlignmentViewPanel alignment);
884 public void updateColours(Object source) {
885 AlignmentPanel ap = (AlignmentPanel) source;
888 * ignore events from panels not used to colour this view
890 if (!getViewer().isUsedForColourBy(ap))
896 * no need to update colours if structure colouring is not
899 if (!isColourBySequence() && !isJalviewColourScheme())
903 if (!showFeatures && (colourScheme == null || colourScheme.isSimple()))
908 if (!isLoadingFromArchive())
910 if (isColourBySequence())
912 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport()),
917 colourBySequence(ap, new SequenceRenderer(ap.getAlignViewport(),
918 colourScheme), showFeatures);