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.FeatureRenderer;
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 * the Jalview panel through which the user interacts
63 * with the structure viewer
65 private JalviewStructureDisplayI viewer;
67 private StructureSelectionManager ssm;
70 * distinct PDB entries (pdb files) associated
73 private PDBEntry[] pdbEntry;
76 * sequences mapped to each pdbentry
78 private SequenceI[][] sequence;
81 * array of target chains for sequences - tied to pdbentry and sequence[]
83 private String[][] chains;
86 * datasource protocol for access to PDBEntrylatest
88 DataSourceType protocol = null;
90 protected boolean colourBySequence = true;
92 private boolean nucleotide;
94 private boolean finishedInit = false;
97 * current set of model filenames loaded in the Jmol instance
99 protected String[] modelFileNames = null;
101 public String fileLoadingError;
104 * Data bean class to simplify parameterisation in superposeStructures
106 protected class SuperposeData
109 * Constructor with alignment width argument
113 public SuperposeData(int width)
115 pdbResNo = new int[width];
118 public String filename;
122 public String chain = "";
124 public boolean isRna;
127 * The pdb residue number (if any) mapped to each column of the alignment
129 public int[] pdbResNo;
138 public AAStructureBindingModel(StructureSelectionManager ssm,
142 this.sequence = seqs;
153 public AAStructureBindingModel(StructureSelectionManager ssm,
154 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
155 DataSourceType protocol)
158 this.sequence = sequenceIs;
159 this.nucleotide = Comparison.isNucleotide(sequenceIs);
160 this.pdbEntry = pdbentry;
161 this.protocol = protocol;
165 private boolean resolveChains()
168 * final count of chain mappings discovered
171 // JBPNote: JAL-2693 - this should be a list of chain mappings per
172 // [pdbentry][sequence]
173 String[][] newchains = new String[pdbEntry.length][];
175 for (PDBEntry pdb : pdbEntry)
177 SequenceI[] seqsForPdb = sequence[pe];
178 if (seqsForPdb != null)
180 newchains[pe] = new String[seqsForPdb.length];
182 for (SequenceI asq : seqsForPdb)
184 String chain = (chains != null && chains[pe] != null)
187 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
188 : asq.getDatasetSequence();
189 if (sq.getAllPDBEntries() != null)
191 for (PDBEntry pdbentry : sq.getAllPDBEntries())
193 if (pdb.getFile() != null && pdbentry.getFile() != null
194 && pdb.getFile().equals(pdbentry.getFile()))
196 String chaincode = pdbentry.getChainCode();
197 if (chaincode != null && chaincode.length() > 0)
206 newchains[pe][se] = chain;
214 return chainmaps > 0;
216 public StructureSelectionManager getSsm()
222 * Returns the i'th PDBEntry (or null)
227 public PDBEntry getPdbEntry(int i)
229 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
233 * Answers true if this binding includes the given PDB id, else false
238 public boolean hasPdbId(String pdbId)
240 if (pdbEntry != null)
242 for (PDBEntry pdb : pdbEntry)
244 if (pdb.getId().equals(pdbId))
254 * Returns the number of modelled PDB file entries.
258 public int getPdbCount()
260 return pdbEntry == null ? 0 : pdbEntry.length;
263 public SequenceI[][] getSequence()
268 public String[][] getChains()
273 public DataSourceType getProtocol()
278 // TODO may remove this if calling methods can be pulled up here
279 protected void setPdbentry(PDBEntry[] pdbentry)
281 this.pdbEntry = pdbentry;
284 protected void setSequence(SequenceI[][] sequence)
286 this.sequence = sequence;
289 protected void setChains(String[][] chains)
291 this.chains = chains;
295 * Construct a title string for the viewer window based on the data Jalview
304 public String getViewerTitle(String viewerName, boolean verbose)
306 if (getSequence() == null || getSequence().length < 1
307 || getPdbCount() < 1 || getSequence()[0].length < 1)
309 return ("Jalview " + viewerName + " Window");
311 // TODO: give a more informative title when multiple structures are
313 StringBuilder title = new StringBuilder(64);
314 final PDBEntry pdbe = getPdbEntry(0);
315 title.append(viewerName + " view for " + getSequence()[0][0].getName()
316 + ":" + pdbe.getId());
320 String method = (String) pdbe.getProperty("method");
323 title.append(" Method: ").append(method);
325 String chain = (String) pdbe.getProperty("chains");
328 title.append(" Chain:").append(chain);
331 return title.toString();
335 * Called by after closeViewer is called, to release any resources and
336 * references so they can be garbage collected. Override if needed.
338 protected void releaseUIResources()
343 public boolean isColourBySequence()
345 return colourBySequence;
348 public void setColourBySequence(boolean colourBySequence)
350 this.colourBySequence = colourBySequence;
353 protected void addSequenceAndChain(int pe, SequenceI[] seq,
356 if (pe < 0 || pe >= getPdbCount())
358 throw new Error(MessageManager.formatMessage(
359 "error.implementation_error_no_pdbentry_from_index",
361 { Integer.valueOf(pe).toString() }));
363 final String nullChain = "TheNullChain";
364 List<SequenceI> s = new ArrayList<>();
365 List<String> c = new ArrayList<>();
366 if (getChains() == null)
368 setChains(new String[getPdbCount()][]);
370 if (getSequence()[pe] != null)
372 for (int i = 0; i < getSequence()[pe].length; i++)
374 s.add(getSequence()[pe][i]);
375 if (getChains()[pe] != null)
377 if (i < getChains()[pe].length)
379 c.add(getChains()[pe][i]);
388 if (tchain != null && tchain.length > 0)
395 for (int i = 0; i < seq.length; i++)
397 if (!s.contains(seq[i]))
400 if (tchain != null && i < tchain.length)
402 c.add(tchain[i] == null ? nullChain : tchain[i]);
406 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
407 getSequence()[pe] = tmp;
410 String[] tch = c.toArray(new String[c.size()]);
411 for (int i = 0; i < tch.length; i++)
413 if (tch[i] == nullChain)
418 getChains()[pe] = tch;
422 getChains()[pe] = null;
427 * add structures and any known sequence associations
429 * @returns the pdb entries added to the current set.
431 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
432 SequenceI[][] seq, String[][] chns)
434 List<PDBEntry> v = new ArrayList<>();
435 List<int[]> rtn = new ArrayList<>();
436 for (int i = 0; i < getPdbCount(); i++)
438 v.add(getPdbEntry(i));
440 for (int i = 0; i < pdbe.length; i++)
442 int r = v.indexOf(pdbe[i]);
443 if (r == -1 || r >= getPdbCount())
445 rtn.add(new int[] { v.size(), i });
450 // just make sure the sequence/chain entries are all up to date
451 addSequenceAndChain(r, seq[i], chns[i]);
454 pdbe = v.toArray(new PDBEntry[v.size()]);
458 // expand the tied sequence[] and string[] arrays
459 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
460 String[][] sch = new String[getPdbCount()][];
461 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
462 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
465 pdbe = new PDBEntry[rtn.size()];
466 for (int r = 0; r < pdbe.length; r++)
468 int[] stri = (rtn.get(r));
469 // record the pdb file as a new addition
470 pdbe[r] = getPdbEntry(stri[0]);
471 // and add the new sequence/chain entries
472 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
483 * Add sequences to the pe'th pdbentry's sequence set.
488 public void addSequence(int pe, SequenceI[] seq)
490 addSequenceAndChain(pe, seq, null);
494 * add the given sequences to the mapping scope for the given pdb file handle
497 * - pdbFile identifier
499 * - set of sequences it can be mapped to
501 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
503 for (int pe = 0; pe < getPdbCount(); pe++)
505 if (getPdbEntry(pe).getFile().equals(pdbFile))
507 addSequence(pe, seq);
513 public abstract void highlightAtoms(List<AtomSpec> atoms);
515 protected boolean isNucleotide()
517 return this.nucleotide;
521 * Returns a readable description of all mappings for the wrapped pdbfile to
522 * any mapped sequences
528 public String printMappings()
530 if (pdbEntry == null)
534 StringBuilder sb = new StringBuilder(128);
535 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
537 String pdbfile = getPdbEntry(pdbe).getFile();
538 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
539 sb.append(getSsm().printMappings(pdbfile, seqs));
541 return sb.toString();
545 * Returns the mapped structure position for a given aligned column of a given
546 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
547 * not mapped to structure.
554 protected int getMappedPosition(SequenceI seq, int alignedPos,
555 StructureMapping mapping)
557 if (alignedPos >= seq.getLength())
562 if (Comparison.isGap(seq.getCharAt(alignedPos)))
566 int seqPos = seq.findPosition(alignedPos);
567 int pos = mapping.getPDBResNum(seqPos);
572 * Helper method to identify residues that can participate in a structure
573 * superposition command. For each structure, identify a sequence in the
574 * alignment which is mapped to the structure. Identify non-gapped columns in
575 * the sequence which have a mapping to a residue in the structure. Returns
576 * the index of the first structure that has a mapping to the alignment.
579 * the sequence alignment which is the basis of structure
582 * a BitSet, where bit j is set to indicate that every structure has
583 * a mapped residue present in column j (so the column can
584 * participate in structure alignment)
586 * an array of data beans corresponding to pdb file index
589 protected int findSuperposableResidues(AlignmentI alignment,
590 BitSet matched, SuperposeData[] structures)
592 int refStructure = -1;
593 String[] files = getStructureFiles();
598 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
600 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
604 * Find the first mapped sequence (if any) for this PDB entry which is in
607 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
608 for (int s = 0; s < seqCountForPdbFile; s++)
610 for (StructureMapping mapping : mappings)
612 final SequenceI theSequence = getSequence()[pdbfnum][s];
613 if (mapping.getSequence() == theSequence
614 && alignment.findIndex(theSequence) > -1)
616 if (refStructure < 0)
618 refStructure = pdbfnum;
620 for (int r = 0; r < alignment.getWidth(); r++)
626 int pos = getMappedPosition(theSequence, r, mapping);
627 if (pos < 1 || pos == lastPos)
633 structures[pdbfnum].pdbResNo[r] = pos;
635 String chain = mapping.getChain();
636 if (chain != null && chain.trim().length() > 0)
638 structures[pdbfnum].chain = chain;
640 structures[pdbfnum].pdbId = mapping.getPdbId();
641 structures[pdbfnum].isRna = theSequence.getRNA() != null;
644 * move on to next pdb file (ignore sequences for other chains
645 * for the same structure)
647 s = seqCountForPdbFile;
657 * Returns true if the structure viewer has loaded all of the files of
658 * interest (identified by the file mapping having been set up), or false if
659 * any are still not loaded after a timeout interval.
663 protected boolean waitForFileLoad(String[] files)
666 * give up after 10 secs plus 1 sec per file
668 long starttime = System.currentTimeMillis();
669 long endTime = 10000 + 1000 * files.length + starttime;
670 String notLoaded = null;
672 boolean waiting = true;
673 while (waiting && System.currentTimeMillis() < endTime)
676 for (String file : files)
685 StructureMapping[] sm = getSsm().getMapping(file);
686 if (sm == null || sm.length == 0)
690 } catch (Throwable x)
700 "Timed out waiting for structure viewer to load file "
708 public boolean isListeningFor(SequenceI seq)
710 if (sequence != null)
712 for (SequenceI[] seqs : sequence)
716 for (SequenceI s : seqs)
718 if (s == seq || (s.getDatasetSequence() != null
719 && s.getDatasetSequence() == seq.getDatasetSequence()))
730 public boolean isFinishedInit()
735 public void setFinishedInit(boolean fi)
737 this.finishedInit = fi;
741 * Returns a list of chains mapped in this viewer.
745 public abstract List<String> getChainNames();
748 * Returns the Jalview panel hosting the structure viewer (if any)
752 public JalviewStructureDisplayI getViewer()
757 public void setViewer(JalviewStructureDisplayI v)
762 public abstract void setJalviewColourScheme(ColourSchemeI cs);
765 * Constructs and sends a command to align structures against a reference
766 * structure, based on one or more sequence alignments. May optionally return
767 * an error or warning message for the alignment command.
770 * an array of alignments to process
771 * @param structureIndices
772 * an array of corresponding reference structures (index into pdb
773 * file array); if a negative value is passed, the first PDB file
774 * mapped to an alignment sequence is used as the reference for
777 * an array of corresponding hidden columns for each alignment
780 public abstract String superposeStructures(AlignmentI[] alignments,
781 int[] structureIndices, HiddenColumns[] hiddenCols);
783 public abstract void setBackgroundColour(Color col);
785 protected abstract StructureMappingcommandSet[] getColourBySequenceCommands(
786 String[] files, SequenceRenderer sr, AlignmentViewPanel avp);
789 * returns the current sequenceRenderer that should be used to colour the
796 public abstract SequenceRenderer getSequenceRenderer(
797 AlignmentViewPanel alignment);
799 protected abstract void colourBySequence(
800 StructureMappingcommandSet[] colourBySequenceCommands);
802 public abstract void colourByChain();
804 public abstract void colourByCharge();
807 * colour any structures associated with sequences in the given alignment
808 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
809 * if colourBySequence is enabled.
811 public void colourBySequence(AlignmentViewPanel alignmentv)
813 if (!colourBySequence || !isLoadingFinished())
817 if (getSsm() == null)
821 String[] files = getStructureFiles();
823 SequenceRenderer sr = getSequenceRenderer(alignmentv);
825 StructureMappingcommandSet[] colourBySequenceCommands = getColourBySequenceCommands(
826 files, sr, alignmentv);
827 colourBySequence(colourBySequenceCommands);
830 public boolean hasFileLoadingError()
832 return fileLoadingError != null && fileLoadingError.length() > 0;
836 * Returns the FeatureRenderer for the given alignment view, or null if
837 * feature display is turned off in the view.
842 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
844 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
846 return ap.getAlignViewport().isShowSequenceFeatures()
847 ? ap.getFeatureRenderer()