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 * Data bean class to simplify parameterisation in superposeStructures
103 protected class SuperposeData
106 * Constructor with alignment width argument
110 public SuperposeData(int width)
112 pdbResNo = new int[width];
115 public String filename;
119 public String chain = "";
121 public boolean isRna;
124 * The pdb residue number (if any) mapped to each column of the alignment
126 public int[] pdbResNo;
135 public AAStructureBindingModel(StructureSelectionManager ssm,
139 this.sequence = seqs;
150 public AAStructureBindingModel(StructureSelectionManager ssm,
151 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
152 DataSourceType protocol)
155 this.sequence = sequenceIs;
156 this.nucleotide = Comparison.isNucleotide(sequenceIs);
157 this.pdbEntry = pdbentry;
158 this.protocol = protocol;
162 private boolean resolveChains()
165 * final count of chain mappings discovered
168 // JBPNote: JAL-2693 - this should be a list of chain mappings per
169 // [pdbentry][sequence]
170 String[][] newchains = new String[pdbEntry.length][];
172 for (PDBEntry pdb : pdbEntry)
174 SequenceI[] seqsForPdb = sequence[pe];
175 if (seqsForPdb != null)
177 newchains[pe] = new String[seqsForPdb.length];
179 for (SequenceI asq : seqsForPdb)
181 String chain = (chains != null && chains[pe] != null)
184 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
185 : asq.getDatasetSequence();
186 if (sq.getAllPDBEntries() != null)
188 for (PDBEntry pdbentry : sq.getAllPDBEntries())
190 if (pdb.getFile() != null && pdbentry.getFile() != null
191 && pdb.getFile().equals(pdbentry.getFile()))
193 String chaincode = pdbentry.getChainCode();
194 if (chaincode != null && chaincode.length() > 0)
203 newchains[pe][se] = chain;
211 return chainmaps > 0;
213 public StructureSelectionManager getSsm()
219 * Returns the i'th PDBEntry (or null)
224 public PDBEntry getPdbEntry(int i)
226 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
230 * Answers true if this binding includes the given PDB id, else false
235 public boolean hasPdbId(String pdbId)
237 if (pdbEntry != null)
239 for (PDBEntry pdb : pdbEntry)
241 if (pdb.getId().equals(pdbId))
251 * Returns the number of modelled PDB file entries.
255 public int getPdbCount()
257 return pdbEntry == null ? 0 : pdbEntry.length;
260 public SequenceI[][] getSequence()
265 public String[][] getChains()
270 public DataSourceType getProtocol()
275 // TODO may remove this if calling methods can be pulled up here
276 protected void setPdbentry(PDBEntry[] pdbentry)
278 this.pdbEntry = pdbentry;
281 protected void setSequence(SequenceI[][] sequence)
283 this.sequence = sequence;
286 protected void setChains(String[][] chains)
288 this.chains = chains;
292 * Construct a title string for the viewer window based on the data Jalview
301 public String getViewerTitle(String viewerName, boolean verbose)
303 if (getSequence() == null || getSequence().length < 1
304 || getPdbCount() < 1 || getSequence()[0].length < 1)
306 return ("Jalview " + viewerName + " Window");
308 // TODO: give a more informative title when multiple structures are
310 StringBuilder title = new StringBuilder(64);
311 final PDBEntry pdbe = getPdbEntry(0);
312 title.append(viewerName + " view for " + getSequence()[0][0].getName()
313 + ":" + pdbe.getId());
317 String method = (String) pdbe.getProperty("method");
320 title.append(" Method: ").append(method);
322 String chain = (String) pdbe.getProperty("chains");
325 title.append(" Chain:").append(chain);
328 return title.toString();
332 * Called by after closeViewer is called, to release any resources and
333 * references so they can be garbage collected. Override if needed.
335 protected void releaseUIResources()
340 public boolean isColourBySequence()
342 return colourBySequence;
345 public void setColourBySequence(boolean colourBySequence)
347 this.colourBySequence = colourBySequence;
350 protected void addSequenceAndChain(int pe, SequenceI[] seq,
353 if (pe < 0 || pe >= getPdbCount())
355 throw new Error(MessageManager.formatMessage(
356 "error.implementation_error_no_pdbentry_from_index",
358 { Integer.valueOf(pe).toString() }));
360 final String nullChain = "TheNullChain";
361 List<SequenceI> s = new ArrayList<>();
362 List<String> c = new ArrayList<>();
363 if (getChains() == null)
365 setChains(new String[getPdbCount()][]);
367 if (getSequence()[pe] != null)
369 for (int i = 0; i < getSequence()[pe].length; i++)
371 s.add(getSequence()[pe][i]);
372 if (getChains()[pe] != null)
374 if (i < getChains()[pe].length)
376 c.add(getChains()[pe][i]);
385 if (tchain != null && tchain.length > 0)
392 for (int i = 0; i < seq.length; i++)
394 if (!s.contains(seq[i]))
397 if (tchain != null && i < tchain.length)
399 c.add(tchain[i] == null ? nullChain : tchain[i]);
403 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
404 getSequence()[pe] = tmp;
407 String[] tch = c.toArray(new String[c.size()]);
408 for (int i = 0; i < tch.length; i++)
410 if (tch[i] == nullChain)
415 getChains()[pe] = tch;
419 getChains()[pe] = null;
424 * add structures and any known sequence associations
426 * @returns the pdb entries added to the current set.
428 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
429 SequenceI[][] seq, String[][] chns)
431 List<PDBEntry> v = new ArrayList<>();
432 List<int[]> rtn = new ArrayList<>();
433 for (int i = 0; i < getPdbCount(); i++)
435 v.add(getPdbEntry(i));
437 for (int i = 0; i < pdbe.length; i++)
439 int r = v.indexOf(pdbe[i]);
440 if (r == -1 || r >= getPdbCount())
442 rtn.add(new int[] { v.size(), i });
447 // just make sure the sequence/chain entries are all up to date
448 addSequenceAndChain(r, seq[i], chns[i]);
451 pdbe = v.toArray(new PDBEntry[v.size()]);
455 // expand the tied sequence[] and string[] arrays
456 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
457 String[][] sch = new String[getPdbCount()][];
458 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
459 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
462 pdbe = new PDBEntry[rtn.size()];
463 for (int r = 0; r < pdbe.length; r++)
465 int[] stri = (rtn.get(r));
466 // record the pdb file as a new addition
467 pdbe[r] = getPdbEntry(stri[0]);
468 // and add the new sequence/chain entries
469 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
480 * Add sequences to the pe'th pdbentry's sequence set.
485 public void addSequence(int pe, SequenceI[] seq)
487 addSequenceAndChain(pe, seq, null);
491 * add the given sequences to the mapping scope for the given pdb file handle
494 * - pdbFile identifier
496 * - set of sequences it can be mapped to
498 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
500 for (int pe = 0; pe < getPdbCount(); pe++)
502 if (getPdbEntry(pe).getFile().equals(pdbFile))
504 addSequence(pe, seq);
510 public abstract void highlightAtoms(List<AtomSpec> atoms);
512 protected boolean isNucleotide()
514 return this.nucleotide;
518 * Returns a readable description of all mappings for the wrapped pdbfile to
519 * any mapped sequences
525 public String printMappings()
527 if (pdbEntry == null)
531 StringBuilder sb = new StringBuilder(128);
532 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
534 String pdbfile = getPdbEntry(pdbe).getFile();
535 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
536 sb.append(getSsm().printMappings(pdbfile, seqs));
538 return sb.toString();
542 * Returns the mapped structure position for a given aligned column of a given
543 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
544 * not mapped to structure.
551 protected int getMappedPosition(SequenceI seq, int alignedPos,
552 StructureMapping mapping)
554 if (alignedPos >= seq.getLength())
559 if (Comparison.isGap(seq.getCharAt(alignedPos)))
563 int seqPos = seq.findPosition(alignedPos);
564 int pos = mapping.getPDBResNum(seqPos);
569 * Helper method to identify residues that can participate in a structure
570 * superposition command. For each structure, identify a sequence in the
571 * alignment which is mapped to the structure. Identify non-gapped columns in
572 * the sequence which have a mapping to a residue in the structure. Returns
573 * the index of the first structure that has a mapping to the alignment.
576 * the sequence alignment which is the basis of structure
579 * a BitSet, where bit j is set to indicate that every structure has
580 * a mapped residue present in column j (so the column can
581 * participate in structure alignment)
583 * an array of data beans corresponding to pdb file index
586 protected int findSuperposableResidues(AlignmentI alignment,
587 BitSet matched, SuperposeData[] structures)
589 int refStructure = -1;
590 String[] files = getStructureFiles();
595 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
597 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
601 * Find the first mapped sequence (if any) for this PDB entry which is in
604 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
605 for (int s = 0; s < seqCountForPdbFile; s++)
607 for (StructureMapping mapping : mappings)
609 final SequenceI theSequence = getSequence()[pdbfnum][s];
610 if (mapping.getSequence() == theSequence
611 && alignment.findIndex(theSequence) > -1)
613 if (refStructure < 0)
615 refStructure = pdbfnum;
617 for (int r = 0; r < alignment.getWidth(); r++)
623 int pos = getMappedPosition(theSequence, r, mapping);
624 if (pos < 1 || pos == lastPos)
630 structures[pdbfnum].pdbResNo[r] = pos;
632 String chain = mapping.getChain();
633 if (chain != null && chain.trim().length() > 0)
635 structures[pdbfnum].chain = chain;
637 structures[pdbfnum].pdbId = mapping.getPdbId();
638 structures[pdbfnum].isRna = theSequence.getRNA() != null;
641 * move on to next pdb file (ignore sequences for other chains
642 * for the same structure)
644 s = seqCountForPdbFile;
654 * Returns true if the structure viewer has loaded all of the files of
655 * interest (identified by the file mapping having been set up), or false if
656 * any are still not loaded after a timeout interval.
660 protected boolean waitForFileLoad(String[] files)
663 * give up after 10 secs plus 1 sec per file
665 long starttime = System.currentTimeMillis();
666 long endTime = 10000 + 1000 * files.length + starttime;
667 String notLoaded = null;
669 boolean waiting = true;
670 while (waiting && System.currentTimeMillis() < endTime)
673 for (String file : files)
682 StructureMapping[] sm = getSsm().getMapping(file);
683 if (sm == null || sm.length == 0)
687 } catch (Throwable x)
697 "Timed out waiting for structure viewer to load file "
705 public boolean isListeningFor(SequenceI seq)
707 if (sequence != null)
709 for (SequenceI[] seqs : sequence)
713 for (SequenceI s : seqs)
715 if (s == seq || (s.getDatasetSequence() != null
716 && s.getDatasetSequence() == seq.getDatasetSequence()))
727 public boolean isFinishedInit()
732 public void setFinishedInit(boolean fi)
734 this.finishedInit = fi;
738 * Returns a list of chains mapped in this viewer.
742 public abstract List<String> getChainNames();
745 * Returns the Jalview panel hosting the structure viewer (if any)
749 public JalviewStructureDisplayI getViewer()
754 public abstract void setJalviewColourScheme(ColourSchemeI cs);
757 * Constructs and sends a command to align structures against a reference
758 * structure, based on one or more sequence alignments. May optionally return
759 * an error or warning message for the alignment command.
762 * an array of alignments to process
763 * @param structureIndices
764 * an array of corresponding reference structures (index into pdb
765 * file array); if a negative value is passed, the first PDB file
766 * mapped to an alignment sequence is used as the reference for
769 * an array of corresponding hidden columns for each alignment
772 public abstract String superposeStructures(AlignmentI[] alignments,
773 int[] structureIndices, HiddenColumns[] hiddenCols);
775 public abstract void setBackgroundColour(Color col);
777 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
778 String[] files, SequenceRenderer sr, AlignmentViewPanel avp);
781 * returns the current sequenceRenderer that should be used to colour the
788 public abstract SequenceRenderer getSequenceRenderer(
789 AlignmentViewPanel alignment);
791 protected abstract void colourBySequence(
792 StructureMappingcommandSet[] colourBySequenceCommands);
794 public abstract void colourByChain();
796 public abstract void colourByCharge();
799 * Recolours the displayed structures, if they are coloured by sequence, or
800 * 'show only visible alignment' is selected. This supports updating structure
801 * colours on either change of alignment colours, or change to the visible
802 * region of the alignment.
804 public void colourBySequence(AlignmentViewPanel alignmentv)
806 if (!isLoadingFinished())
810 // todo: property change event for visibleAlignment
811 // to avoid unnecessary redraws here
812 if (!colourBySequence && !isShowAlignmentOnly())
816 if (getSsm() == null)
820 String[] files = getStructureFiles();
822 SequenceRenderer sr = getSequenceRenderer(alignmentv);
824 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
825 files, sr, alignmentv);
826 colourBySequence(colourBySequenceCommands);
829 public boolean hasFileLoadingError()
831 return fileLoadingError != null && fileLoadingError.length() > 0;
834 public abstract jalview.api.FeatureRenderer getFeatureRenderer(
835 AlignmentViewPanel alignment);
838 * Sets the flag for whether only mapped visible residues in the alignment
839 * should be visible in the structure viewer
843 public void setShowAlignmentOnly(boolean b)
845 showAlignmentOnly = b;
849 * Answers true if only mapped visible residues in the alignment should be
850 * visible in the structure viewer, else false
854 public boolean isShowAlignmentOnly()
856 return showAlignmentOnly;
860 * Shows the structures in the viewer, without changing their colouring. This is
861 * to support toggling of whether the whole structure is shown, or only residues
862 * mapped to visible regions of the alignment.
864 * @param alignViewportI
866 public void showStructures(AlignViewportI alignViewportI)
868 // override with implementation
872 public void updateColours(Object source)
874 AlignmentViewPanel ap = (AlignmentViewPanel) source;
875 // ignore events from panels not used to colour this view
876 if (!getViewer().isUsedforcolourby(ap))
880 if (!isLoadingFromArchive())
882 colourBySequence(ap);