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.schemes.ResidueProperties;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureCommandsI;
37 import jalview.structure.StructureListener;
38 import jalview.structure.StructureMapping;
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.HashMap;
48 import java.util.List;
51 import javax.swing.SwingUtilities;
55 * A base class to hold common function for protein structure model binding.
56 * Initial version created by refactoring JMol and Chimera binding models, but
57 * other structure viewers could in principle be accommodated in future.
62 public abstract class AAStructureBindingModel
63 extends SequenceStructureBindingModel
64 implements StructureListener, StructureSelectionManagerProvider
66 private static final String COLOURING_STRUCTURES = MessageManager
67 .getString("status.colouring_structures");
70 * the Jalview panel through which the user interacts
71 * with the structure viewer
73 private JalviewStructureDisplayI viewer;
76 * helper that generates command syntax
78 private StructureCommandsI commandGenerator;
80 private StructureSelectionManager ssm;
83 * modelled chains, formatted as "pdbid:chainCode"
85 private List<String> chainNames;
88 * lookup of pdb file name by key "pdbid:chainCode"
90 private Map<String, String> chainFile;
93 * distinct PDB entries (pdb files) associated
96 private PDBEntry[] pdbEntry;
99 * sequences mapped to each pdbentry
101 private SequenceI[][] sequence;
104 * array of target chains for sequences - tied to pdbentry and sequence[]
106 private String[][] chains;
109 * datasource protocol for access to PDBEntrylatest
111 DataSourceType protocol = null;
113 protected boolean colourBySequence = true;
115 private boolean nucleotide;
117 private boolean finishedInit = false;
120 * current set of model filenames loaded in the Jmol instance
122 protected String[] modelFileNames = null;
124 public String fileLoadingError;
127 * Data bean class to simplify parameterisation in superposeStructures
129 protected class SuperposeData
132 * Constructor with alignment width argument
136 public SuperposeData(int width)
138 pdbResNo = new int[width];
141 public String filename;
145 public String chain = "";
147 public boolean isRna;
150 * The pdb residue number (if any) mapped to each column of the alignment
152 public int[] pdbResNo;
161 public AAStructureBindingModel(StructureSelectionManager ssm,
165 this.sequence = seqs;
166 chainNames = new ArrayList<>();
167 chainFile = new HashMap<>();
178 public AAStructureBindingModel(StructureSelectionManager ssm,
179 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
180 DataSourceType protocol)
182 this(ssm, sequenceIs);
183 this.nucleotide = Comparison.isNucleotide(sequenceIs);
184 this.pdbEntry = pdbentry;
185 this.protocol = protocol;
189 private boolean resolveChains()
192 * final count of chain mappings discovered
195 // JBPNote: JAL-2693 - this should be a list of chain mappings per
196 // [pdbentry][sequence]
197 String[][] newchains = new String[pdbEntry.length][];
199 for (PDBEntry pdb : pdbEntry)
201 SequenceI[] seqsForPdb = sequence[pe];
202 if (seqsForPdb != null)
204 newchains[pe] = new String[seqsForPdb.length];
206 for (SequenceI asq : seqsForPdb)
208 String chain = (chains != null && chains[pe] != null)
211 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
212 : asq.getDatasetSequence();
213 if (sq.getAllPDBEntries() != null)
215 for (PDBEntry pdbentry : sq.getAllPDBEntries())
217 if (pdb.getFile() != null && pdbentry.getFile() != null
218 && pdb.getFile().equals(pdbentry.getFile()))
220 String chaincode = pdbentry.getChainCode();
221 if (chaincode != null && chaincode.length() > 0)
230 newchains[pe][se] = chain;
238 return chainmaps > 0;
240 public StructureSelectionManager getSsm()
246 * Returns the i'th PDBEntry (or null)
251 public PDBEntry getPdbEntry(int i)
253 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
257 * Answers true if this binding includes the given PDB id, else false
262 public boolean hasPdbId(String pdbId)
264 if (pdbEntry != null)
266 for (PDBEntry pdb : pdbEntry)
268 if (pdb.getId().equals(pdbId))
278 * Returns the number of modelled PDB file entries.
282 public int getPdbCount()
284 return pdbEntry == null ? 0 : pdbEntry.length;
287 public SequenceI[][] getSequence()
292 public String[][] getChains()
297 public DataSourceType getProtocol()
302 // TODO may remove this if calling methods can be pulled up here
303 protected void setPdbentry(PDBEntry[] pdbentry)
305 this.pdbEntry = pdbentry;
308 protected void setSequence(SequenceI[][] sequence)
310 this.sequence = sequence;
313 protected void setChains(String[][] chains)
315 this.chains = chains;
319 * Construct a title string for the viewer window based on the data Jalview
328 public String getViewerTitle(String viewerName, boolean verbose)
330 if (getSequence() == null || getSequence().length < 1
331 || getPdbCount() < 1 || getSequence()[0].length < 1)
333 return ("Jalview " + viewerName + " Window");
335 // TODO: give a more informative title when multiple structures are
337 StringBuilder title = new StringBuilder(64);
338 final PDBEntry pdbe = getPdbEntry(0);
339 title.append(viewerName + " view for " + getSequence()[0][0].getName()
340 + ":" + pdbe.getId());
344 String method = (String) pdbe.getProperty("method");
347 title.append(" Method: ").append(method);
349 String chain = (String) pdbe.getProperty("chains");
352 title.append(" Chain:").append(chain);
355 return title.toString();
359 * Called by after closeViewer is called, to release any resources and
360 * references so they can be garbage collected. Override if needed.
362 protected void releaseUIResources()
367 public boolean isColourBySequence()
369 return colourBySequence;
372 public void setColourBySequence(boolean colourBySequence)
374 this.colourBySequence = colourBySequence;
377 protected void addSequenceAndChain(int pe, SequenceI[] seq,
380 if (pe < 0 || pe >= getPdbCount())
382 throw new Error(MessageManager.formatMessage(
383 "error.implementation_error_no_pdbentry_from_index",
385 { Integer.valueOf(pe).toString() }));
387 final String nullChain = "TheNullChain";
388 List<SequenceI> s = new ArrayList<>();
389 List<String> c = new ArrayList<>();
390 if (getChains() == null)
392 setChains(new String[getPdbCount()][]);
394 if (getSequence()[pe] != null)
396 for (int i = 0; i < getSequence()[pe].length; i++)
398 s.add(getSequence()[pe][i]);
399 if (getChains()[pe] != null)
401 if (i < getChains()[pe].length)
403 c.add(getChains()[pe][i]);
412 if (tchain != null && tchain.length > 0)
419 for (int i = 0; i < seq.length; i++)
421 if (!s.contains(seq[i]))
424 if (tchain != null && i < tchain.length)
426 c.add(tchain[i] == null ? nullChain : tchain[i]);
430 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
431 getSequence()[pe] = tmp;
434 String[] tch = c.toArray(new String[c.size()]);
435 for (int i = 0; i < tch.length; i++)
437 if (tch[i] == nullChain)
442 getChains()[pe] = tch;
446 getChains()[pe] = null;
451 * add structures and any known sequence associations
453 * @returns the pdb entries added to the current set.
455 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
456 SequenceI[][] seq, String[][] chns)
458 List<PDBEntry> v = new ArrayList<>();
459 List<int[]> rtn = new ArrayList<>();
460 for (int i = 0; i < getPdbCount(); i++)
462 v.add(getPdbEntry(i));
464 for (int i = 0; i < pdbe.length; i++)
466 int r = v.indexOf(pdbe[i]);
467 if (r == -1 || r >= getPdbCount())
469 rtn.add(new int[] { v.size(), i });
474 // just make sure the sequence/chain entries are all up to date
475 addSequenceAndChain(r, seq[i], chns[i]);
478 pdbe = v.toArray(new PDBEntry[v.size()]);
482 // expand the tied sequence[] and string[] arrays
483 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
484 String[][] sch = new String[getPdbCount()][];
485 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
486 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
489 pdbe = new PDBEntry[rtn.size()];
490 for (int r = 0; r < pdbe.length; r++)
492 int[] stri = (rtn.get(r));
493 // record the pdb file as a new addition
494 pdbe[r] = getPdbEntry(stri[0]);
495 // and add the new sequence/chain entries
496 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
507 * Add sequences to the pe'th pdbentry's sequence set.
512 public void addSequence(int pe, SequenceI[] seq)
514 addSequenceAndChain(pe, seq, null);
518 * add the given sequences to the mapping scope for the given pdb file handle
521 * - pdbFile identifier
523 * - set of sequences it can be mapped to
525 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
527 for (int pe = 0; pe < getPdbCount(); pe++)
529 if (getPdbEntry(pe).getFile().equals(pdbFile))
531 addSequence(pe, seq);
537 public abstract void highlightAtoms(List<AtomSpec> atoms);
539 protected boolean isNucleotide()
541 return this.nucleotide;
545 * Returns a readable description of all mappings for the wrapped pdbfile to
546 * any mapped sequences
552 public String printMappings()
554 if (pdbEntry == null)
558 StringBuilder sb = new StringBuilder(128);
559 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
561 String pdbfile = getPdbEntry(pdbe).getFile();
562 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
563 sb.append(getSsm().printMappings(pdbfile, seqs));
565 return sb.toString();
569 * Returns the mapped structure position for a given aligned column of a given
570 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
571 * not mapped to structure.
578 protected int getMappedPosition(SequenceI seq, int alignedPos,
579 StructureMapping mapping)
581 if (alignedPos >= seq.getLength())
586 if (Comparison.isGap(seq.getCharAt(alignedPos)))
590 int seqPos = seq.findPosition(alignedPos);
591 int pos = mapping.getPDBResNum(seqPos);
596 * Helper method to identify residues that can participate in a structure
597 * superposition command. For each structure, identify a sequence in the
598 * alignment which is mapped to the structure. Identify non-gapped columns in
599 * the sequence which have a mapping to a residue in the structure. Returns
600 * the index of the first structure that has a mapping to the alignment.
603 * the sequence alignment which is the basis of structure
606 * a BitSet, where bit j is set to indicate that every structure has
607 * a mapped residue present in column j (so the column can
608 * participate in structure alignment)
610 * an array of data beans corresponding to pdb file index
613 protected int findSuperposableResidues(AlignmentI alignment,
614 BitSet matched, SuperposeData[] structures)
616 int refStructure = -1;
617 String[] files = getStructureFiles();
622 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
624 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
628 * Find the first mapped sequence (if any) for this PDB entry which is in
631 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
632 for (int s = 0; s < seqCountForPdbFile; s++)
634 for (StructureMapping mapping : mappings)
636 final SequenceI theSequence = getSequence()[pdbfnum][s];
637 if (mapping.getSequence() == theSequence
638 && alignment.findIndex(theSequence) > -1)
640 if (refStructure < 0)
642 refStructure = pdbfnum;
644 for (int r = 0; r < alignment.getWidth(); r++)
650 int pos = getMappedPosition(theSequence, r, mapping);
651 if (pos < 1 || pos == lastPos)
657 structures[pdbfnum].pdbResNo[r] = pos;
659 String chain = mapping.getChain();
660 if (chain != null && chain.trim().length() > 0)
662 structures[pdbfnum].chain = chain;
664 structures[pdbfnum].pdbId = mapping.getPdbId();
665 structures[pdbfnum].isRna = theSequence.getRNA() != null;
668 * move on to next pdb file (ignore sequences for other chains
669 * for the same structure)
671 s = seqCountForPdbFile;
681 * Returns true if the structure viewer has loaded all of the files of
682 * interest (identified by the file mapping having been set up), or false if
683 * any are still not loaded after a timeout interval.
687 protected boolean waitForFileLoad(String[] files)
690 * give up after 10 secs plus 1 sec per file
692 long starttime = System.currentTimeMillis();
693 long endTime = 10000 + 1000 * files.length + starttime;
694 String notLoaded = null;
696 boolean waiting = true;
697 while (waiting && System.currentTimeMillis() < endTime)
700 for (String file : files)
709 StructureMapping[] sm = getSsm().getMapping(file);
710 if (sm == null || sm.length == 0)
714 } catch (Throwable x)
724 "Timed out waiting for structure viewer to load file "
732 public boolean isListeningFor(SequenceI seq)
734 if (sequence != null)
736 for (SequenceI[] seqs : sequence)
740 for (SequenceI s : seqs)
742 if (s == seq || (s.getDatasetSequence() != null
743 && s.getDatasetSequence() == seq.getDatasetSequence()))
754 public boolean isFinishedInit()
759 public void setFinishedInit(boolean fi)
761 this.finishedInit = fi;
765 * Returns a list of chains mapped in this viewer, formatted as
770 public List<String> getChainNames()
776 * Returns the Jalview panel hosting the structure viewer (if any)
780 public JalviewStructureDisplayI getViewer()
785 public void setViewer(JalviewStructureDisplayI v)
791 * Constructs and sends a command to align structures against a reference
792 * structure, based on one or more sequence alignments. May optionally return
793 * an error or warning message for the alignment command.
796 * an array of alignments to process
797 * @param structureIndices
798 * an array of corresponding reference structures (index into pdb
799 * file array); if a negative value is passed, the first PDB file
800 * mapped to an alignment sequence is used as the reference for
803 * an array of corresponding hidden columns for each alignment
806 public abstract String superposeStructures(AlignmentI[] alignments,
807 int[] structureIndices, HiddenColumns[] hiddenCols);
810 * returns the current sequenceRenderer that should be used to colour the
817 public abstract SequenceRenderer getSequenceRenderer(
818 AlignmentViewPanel alignment);
821 * Sends a command to the structure viewer to colour each chain with a
822 * distinct colour (to the extent supported by the viewer)
824 public void colourByChain()
826 colourBySequence = false;
828 // TODO: JAL-628 colour chains distinctly across all visible models
830 executeCommand(commandGenerator.colourByChain(), false,
831 COLOURING_STRUCTURES);
835 * Sends a command to the structure viewer to colour each chain with a
836 * distinct colour (to the extent supported by the viewer)
838 public void colourByCharge()
840 colourBySequence = false;
842 executeCommand(commandGenerator.colourByCharge(), false,
843 COLOURING_STRUCTURES);
847 * Sends a command to the structure to apply a colour scheme (defined in
848 * Jalview but not necessarily applied to the alignment), which defines a
849 * colour per residue letter. More complex schemes (e.g. that depend on
850 * consensus) cannot be used here and are ignored.
854 public void colourByJalviewColourScheme(ColourSchemeI cs)
856 colourBySequence = false;
858 if (cs == null || !cs.isSimple())
864 * build a map of {Residue3LetterCode, Color}
866 Map<String, Color> colours = new HashMap<>();
867 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
869 for (String resName : residues)
871 char res = resName.length() == 3
872 ? ResidueProperties.getSingleCharacterCode(resName)
874 Color colour = cs.findColour(res, 0, null, null, 0f);
875 colours.put(resName, colour);
879 * pass to the command constructor, and send the command
881 String cmd = commandGenerator.colourByResidues(colours);
882 executeCommand(cmd, false, COLOURING_STRUCTURES);
885 public void setBackgroundColour(Color col)
887 String cmd = commandGenerator.setBackgroundColour(col);
888 executeCommand(cmd, false, null);
892 * Sends one command to the structure viewer. If {@code getReply} is true, the
893 * command is sent synchronously, otherwise in a deferred thread.
895 * If a progress message is supplied, this is displayed before command
896 * execution, and removed afterwards.
903 private List<String> executeCommand(String cmd, boolean getReply,
908 return executeSynchronous(cmd, msg, getReply);
912 executeAsynchronous(cmd, msg);
918 * Sends the command in the current thread. If a message is supplied, this is
919 * shown before the thread is started, and removed when it completes. May
920 * return a reply to the command if requested.
927 private List<String> executeSynchronous(String cmd, String msg, boolean getReply)
929 final JalviewStructureDisplayI theViewer = getViewer();
930 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
933 return executeCommand(cmd, getReply);
938 theViewer.stopProgressBar(null, handle);
944 * Sends the command in a separate thread. If a message is supplied, this is
945 * shown before the thread is started, and removed when it completes. No value
951 private void executeAsynchronous(String cmd, String msg)
953 final JalviewStructureDisplayI theViewer = getViewer();
954 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
956 SwingUtilities.invokeLater(new Runnable()
963 executeCommand(cmd, false);
968 theViewer.stopProgressBar(null, handle);
975 protected abstract List<String> executeCommand(String command,
978 protected List<String> executeCommands(boolean getReply,
981 List<String> response = null;
982 for (String cmd : commands)
984 response = executeCommand(cmd, getReply);
990 * colour any structures associated with sequences in the given alignment
991 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
992 * if colourBySequence is enabled.
994 public void colourBySequence(AlignmentViewPanel alignmentv)
996 if (!colourBySequence || !isLoadingFinished())
1000 if (getSsm() == null)
1004 String[] files = getStructureFiles();
1006 SequenceRenderer sr = getSequenceRenderer(alignmentv);
1008 String[] colourBySequenceCommands = commandGenerator
1009 .colourBySequence(getSsm(), files, getSequence(), sr,
1011 executeCommands(false, colourBySequenceCommands);
1015 * Centre the display in the structure viewer
1017 public void focusView()
1019 executeCommand(commandGenerator.focusView(), false);
1023 * Generates and executes a command to show only specified chains in the
1024 * structure viewer. The list of chains to show should contain entries
1025 * formatted as "pdbid:chaincode".
1029 public void showChains(List<String> toShow)
1031 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1034 * Reformat the pdbid:chainCode values as modelNo:chainCode
1035 * since this is what is needed to construct the viewer command
1036 * todo: find a less messy way to do this
1038 List<String> showThese = new ArrayList<>();
1039 for (String chainId : toShow)
1041 String[] tokens = chainId.split("\\:");
1042 if (tokens.length == 2)
1044 String pdbFile = getFileForChain(chainId);
1045 int modelNo = getModelNoForFile(pdbFile);
1046 String model = modelNo == -1 ? "" : String.valueOf(modelNo);
1047 showThese.add(model + ":" + tokens[1]);
1050 executeCommand(commandGenerator.showChains(showThese), false);
1054 * Answers the structure viewer's model number given a PDB file name. Returns
1055 * -1 if model number is not found.
1060 protected abstract int getModelNoForFile(String chainId);
1062 public boolean hasFileLoadingError()
1064 return fileLoadingError != null && fileLoadingError.length() > 0;
1068 * Returns the FeatureRenderer for the given alignment view, or null if
1069 * feature display is turned off in the view.
1074 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1076 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1078 return ap.getAlignViewport().isShowSequenceFeatures()
1079 ? ap.getFeatureRenderer()
1083 protected void setStructureCommands(StructureCommandsI cmd)
1085 commandGenerator = cmd;
1089 * Records association of one chain id (formatted as "pdbid:chainCode") with
1090 * the corresponding PDB file name
1095 public void addChainFile(String chainId, String fileName)
1097 chainFile.put(chainId, fileName);
1101 * Returns the PDB filename for the given chain id (formatted as
1102 * "pdbid:chainCode"), or null if not found
1107 protected String getFileForChain(String chainId)
1109 return chainFile.get(chainId);