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 java.awt.Color;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.BitSet;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Locale;
35 import javax.swing.SwingUtilities;
37 import jalview.api.AlignViewportI;
38 import jalview.api.AlignmentViewPanel;
39 import jalview.api.FeatureRenderer;
40 import jalview.api.SequenceRenderer;
41 import jalview.api.StructureSelectionManagerProvider;
42 import jalview.api.structures.JalviewStructureDisplayI;
43 import jalview.bin.Console;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.HiddenColumns;
46 import jalview.datamodel.MappedFeatures;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.SequenceFeature;
49 import jalview.datamodel.SequenceI;
50 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
51 import jalview.gui.AlignmentPanel;
52 import jalview.gui.Desktop;
53 import jalview.gui.StructureViewer.ViewerType;
54 import jalview.io.DataSourceType;
55 import jalview.io.StructureFile;
56 import jalview.renderer.seqfeatures.FeatureColourFinder;
57 import jalview.schemes.ColourSchemeI;
58 import jalview.schemes.ResidueProperties;
59 import jalview.structure.AtomSpec;
60 import jalview.structure.AtomSpecModel;
61 import jalview.structure.StructureCommandI;
62 import jalview.structure.StructureCommandsI;
63 import jalview.structure.StructureCommandsI.AtomSpecType;
64 import jalview.structure.StructureListener;
65 import jalview.structure.StructureMapping;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.Comparison;
68 import jalview.util.MessageManager;
72 * A base class to hold common function for 3D structure model binding. Initial
73 * version created by refactoring JMol and Chimera binding models, but other
74 * structure viewers could in principle be accommodated in future.
79 public abstract class AAStructureBindingModel
80 extends SequenceStructureBindingModel
81 implements StructureListener, StructureSelectionManagerProvider
84 * Data bean class to simplify parameterisation in superposeStructures
86 public static class SuperposeData
88 public String filename;
92 public String chain = "";
95 * is the mapped sequence not protein ?
100 * The pdb residue number (if any) mapped to columns of the alignment
102 public int[] pdbResNo; // or use SparseIntArray?
104 public String modelId;
110 * width of alignment (number of columns that may potentially
111 * participate in superposition)
113 * structure viewer model number
115 public SuperposeData(int width, String model)
117 pdbResNo = new int[width];
122 private static final int MIN_POS_TO_SUPERPOSE = 4;
124 private static final String COLOURING_STRUCTURES = MessageManager
125 .getString("status.colouring_structures");
128 * the Jalview panel through which the user interacts
129 * with the structure viewer
131 private JalviewStructureDisplayI viewer;
134 * helper that generates command syntax
136 private StructureCommandsI commandGenerator;
138 private StructureSelectionManager ssm;
141 * modelled chains, formatted as "pdbid:chainCode"
143 private List<String> chainNames;
146 * lookup of pdb file name by key "pdbid:chainCode"
148 private Map<String, String> chainFile;
151 * distinct PDB entries (pdb files) associated
154 private PDBEntry[] pdbEntry;
157 * sequences mapped to each pdbentry
159 private SequenceI[][] sequence;
162 * array of target chains for sequences - tied to pdbentry and sequence[]
164 private String[][] chains;
167 * datasource protocol for access to PDBEntrylatest
169 DataSourceType protocol = null;
171 protected boolean colourBySequence = true;
174 * true if all sequences appear to be nucleotide
176 private boolean nucleotide;
178 private boolean finishedInit = false;
181 * current set of model filenames loaded in the viewer
183 protected String[] modelFileNames = null;
185 public String fileLoadingError;
187 protected Thread externalViewerMonitor;
195 public AAStructureBindingModel(StructureSelectionManager ssm,
199 this.sequence = seqs;
200 chainNames = new ArrayList<>();
201 chainFile = new HashMap<>();
212 public AAStructureBindingModel(StructureSelectionManager ssm,
213 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
214 DataSourceType protocol)
216 this(ssm, sequenceIs);
217 this.nucleotide = Comparison.isNucleotide(sequenceIs);
218 this.pdbEntry = pdbentry;
219 this.protocol = protocol;
223 private boolean resolveChains()
226 * final count of chain mappings discovered
229 // JBPNote: JAL-2693 - this should be a list of chain mappings per
230 // [pdbentry][sequence]
231 String[][] newchains = new String[pdbEntry.length][];
233 for (PDBEntry pdb : pdbEntry)
235 SequenceI[] seqsForPdb = sequence[pe];
236 if (seqsForPdb != null)
238 newchains[pe] = new String[seqsForPdb.length];
240 for (SequenceI asq : seqsForPdb)
242 String chain = (chains != null && chains[pe] != null)
245 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
246 : asq.getDatasetSequence();
247 if (sq.getAllPDBEntries() != null)
249 for (PDBEntry pdbentry : sq.getAllPDBEntries())
251 if (pdb.getFile() != null && pdbentry.getFile() != null
252 && pdb.getFile().equals(pdbentry.getFile()))
254 String chaincode = pdbentry.getChainCode();
255 if (chaincode != null && chaincode.length() > 0)
264 newchains[pe][se] = chain;
272 return chainmaps > 0;
275 public StructureSelectionManager getSsm()
281 * Returns the i'th PDBEntry (or null)
286 public PDBEntry getPdbEntry(int i)
288 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
292 * Answers true if this binding includes the given PDB id, else false
297 public boolean hasPdbId(String pdbId)
299 if (pdbEntry != null)
301 for (PDBEntry pdb : pdbEntry)
303 if (pdb.getId().equals(pdbId))
313 * Returns the number of modelled PDB file entries.
317 public int getPdbCount()
319 return pdbEntry == null ? 0 : pdbEntry.length;
322 public SequenceI[][] getSequence()
327 public String[][] getChains()
332 public DataSourceType getProtocol()
337 // TODO may remove this if calling methods can be pulled up here
338 protected void setPdbentry(PDBEntry[] pdbentry)
340 this.pdbEntry = pdbentry;
343 protected void setSequence(SequenceI[][] sequence)
345 this.sequence = sequence;
348 protected void setChains(String[][] chains)
350 this.chains = chains;
354 * Construct a title string for the viewer window based on the data Jalview
363 public String getViewerTitle(String viewerName, boolean verbose)
365 if (getSequence() == null || getSequence().length < 1
366 || getPdbCount() < 1 || getSequence()[0].length < 1)
368 return ("Jalview " + viewerName + " Window");
370 // TODO: give a more informative title when multiple structures are
372 StringBuilder title = new StringBuilder(64);
373 final PDBEntry pdbe = getPdbEntry(0);
374 title.append(viewerName + " view for " + getSequence()[0][0].getName()
375 + ":" + pdbe.getId());
379 String method = (String) pdbe.getProperty("method");
382 title.append(" Method: ").append(method);
384 String chain = (String) pdbe.getProperty("chains");
387 title.append(" Chain:").append(chain);
390 return title.toString();
394 * Called by after closeViewer is called, to release any resources and
395 * references so they can be garbage collected. Override if needed.
397 protected void releaseUIResources()
402 public void releaseReferences(Object svl)
406 public boolean isColourBySequence()
408 return colourBySequence;
412 * Called when the binding thinks the UI needs to be refreshed after a
413 * structure viewer state change. This could be because structures were
414 * loaded, or because an error has occurred. Default does nothing, override as
417 public void refreshGUI()
422 * Instruct the Jalview binding to update the pdbentries vector if necessary
423 * prior to matching the jmol view's contents to the list of structure files
424 * Jalview knows about. By default does nothing, override as required.
426 public void refreshPdbEntries()
430 public void setColourBySequence(boolean colourBySequence)
432 this.colourBySequence = colourBySequence;
435 protected void addSequenceAndChain(int pe, SequenceI[] seq,
438 if (pe < 0 || pe >= getPdbCount())
440 throw new Error(MessageManager.formatMessage(
441 "error.implementation_error_no_pdbentry_from_index",
443 { Integer.valueOf(pe).toString() }));
445 final String nullChain = "TheNullChain";
446 List<SequenceI> s = new ArrayList<>();
447 List<String> c = new ArrayList<>();
448 if (getChains() == null)
450 setChains(new String[getPdbCount()][]);
452 if (getSequence()[pe] != null)
454 for (int i = 0; i < getSequence()[pe].length; i++)
456 s.add(getSequence()[pe][i]);
457 if (getChains()[pe] != null)
459 if (i < getChains()[pe].length)
461 c.add(getChains()[pe][i]);
470 if (tchain != null && tchain.length > 0)
477 for (int i = 0; i < seq.length; i++)
479 if (!s.contains(seq[i]))
482 if (tchain != null && i < tchain.length)
484 c.add(tchain[i] == null ? nullChain : tchain[i]);
488 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
489 getSequence()[pe] = tmp;
492 String[] tch = c.toArray(new String[c.size()]);
493 for (int i = 0; i < tch.length; i++)
495 if (tch[i] == nullChain)
500 getChains()[pe] = tch;
504 getChains()[pe] = null;
509 * add structures and any known sequence associations
511 * @returns the pdb entries added to the current set.
513 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
514 SequenceI[][] seq, String[][] chns)
516 List<PDBEntry> v = new ArrayList<>();
517 List<int[]> rtn = new ArrayList<>();
518 for (int i = 0; i < getPdbCount(); i++)
520 v.add(getPdbEntry(i));
522 for (int i = 0; i < pdbe.length; i++)
524 int r = v.indexOf(pdbe[i]);
525 if (r == -1 || r >= getPdbCount())
527 rtn.add(new int[] { v.size(), i });
532 // just make sure the sequence/chain entries are all up to date
533 addSequenceAndChain(r, seq[i], chns[i]);
536 pdbe = v.toArray(new PDBEntry[v.size()]);
540 // expand the tied sequence[] and string[] arrays
541 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
542 String[][] sch = new String[getPdbCount()][];
543 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
544 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
547 pdbe = new PDBEntry[rtn.size()];
548 for (int r = 0; r < pdbe.length; r++)
550 int[] stri = (rtn.get(r));
551 // record the pdb file as a new addition
552 pdbe[r] = getPdbEntry(stri[0]);
553 // and add the new sequence/chain entries
554 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
565 * Add sequences to the pe'th pdbentry's sequence set.
570 public void addSequence(int pe, SequenceI[] seq)
572 addSequenceAndChain(pe, seq, null);
576 * add the given sequences to the mapping scope for the given pdb file handle
579 * - pdbFile identifier
581 * - set of sequences it can be mapped to
583 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
585 for (int pe = 0; pe < getPdbCount(); pe++)
587 if (getPdbEntry(pe).getFile().equals(pdbFile))
589 addSequence(pe, seq);
595 public abstract void highlightAtoms(List<AtomSpec> atoms);
597 protected boolean isNucleotide()
599 return this.nucleotide;
603 * Returns a readable description of all mappings for the wrapped pdbfile to
604 * any mapped sequences
610 public String printMappings()
612 if (pdbEntry == null)
616 StringBuilder sb = new StringBuilder(128);
617 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
619 String pdbfile = getPdbEntry(pdbe).getFile();
620 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
621 sb.append(getSsm().printMappings(pdbfile, seqs));
623 return sb.toString();
627 * Returns the mapped structure position for a given aligned column of a given
628 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
629 * not mapped to structure.
636 protected int getMappedPosition(SequenceI seq, int alignedPos,
637 StructureMapping mapping)
639 if (alignedPos >= seq.getLength())
644 if (Comparison.isGap(seq.getCharAt(alignedPos)))
648 int seqPos = seq.findPosition(alignedPos);
649 int pos = mapping.getPDBResNum(seqPos);
654 * Helper method to identify residues that can participate in a structure
655 * superposition command. For each structure, identify a sequence in the
656 * alignment which is mapped to the structure. Identify non-gapped columns in
657 * the sequence which have a mapping to a residue in the structure. Returns
658 * the index of the first structure that has a mapping to the alignment.
661 * the sequence alignment which is the basis of structure
664 * a BitSet, where bit j is set to indicate that every structure has
665 * a mapped residue present in column j (so the column can
666 * participate in structure alignment)
668 * an array of data beans corresponding to pdb file index
671 protected int findSuperposableResidues(AlignmentI alignment,
673 AAStructureBindingModel.SuperposeData[] structures)
675 int refStructure = -1;
676 String[] files = getStructureFiles();
681 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
683 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
687 * Find the first mapped sequence (if any) for this PDB entry which is in
690 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
691 for (int s = 0; s < seqCountForPdbFile; s++)
693 for (StructureMapping mapping : mappings)
695 final SequenceI theSequence = getSequence()[pdbfnum][s];
696 if (mapping.getSequence() == theSequence
697 && alignment.findIndex(theSequence) > -1)
699 if (refStructure < 0)
701 refStructure = pdbfnum;
703 for (int r = 0; r < alignment.getWidth(); r++)
709 int pos = getMappedPosition(theSequence, r, mapping);
710 if (pos < 1 || pos == lastPos)
716 structures[pdbfnum].pdbResNo[r] = pos;
718 String chain = mapping.getChain();
719 if (chain != null && chain.trim().length() > 0)
721 structures[pdbfnum].chain = chain;
723 structures[pdbfnum].pdbId = mapping.getPdbId();
724 structures[pdbfnum].isRna = !theSequence.isProtein();
727 * move on to next pdb file (ignore sequences for other chains
728 * for the same structure)
730 s = seqCountForPdbFile;
731 break; // fixme break out of two loops here!
740 * Returns true if the structure viewer has loaded all of the files of
741 * interest (identified by the file mapping having been set up), or false if
742 * any are still not loaded after a timeout interval.
746 protected boolean waitForFileLoad(String[] files)
749 * give up after 10 secs plus 1 sec per file
751 long starttime = System.currentTimeMillis();
752 long endTime = 10000 + 1000 * files.length + starttime;
753 String notLoaded = null;
755 boolean waiting = true;
756 while (waiting && System.currentTimeMillis() < endTime)
759 for (String file : files)
768 StructureMapping[] sm = getSsm().getMapping(file);
769 if (sm == null || sm.length == 0)
773 } catch (Throwable x)
783 "Timed out waiting for structure viewer to load file "
791 public boolean isListeningFor(SequenceI seq)
793 if (sequence != null)
795 for (SequenceI[] seqs : sequence)
799 for (SequenceI s : seqs)
801 if (s == seq || (s.getDatasetSequence() != null
802 && s.getDatasetSequence() == seq.getDatasetSequence()))
813 public boolean isFinishedInit()
818 public void setFinishedInit(boolean fi)
820 this.finishedInit = fi;
824 * Returns a list of chains mapped in this viewer, formatted as
829 public List<String> getChainNames()
835 * Returns the Jalview panel hosting the structure viewer (if any)
839 public JalviewStructureDisplayI getViewer()
844 public void setViewer(JalviewStructureDisplayI v)
850 * Constructs and sends a command to align structures against a reference
851 * structure, based on one or more sequence alignments. May optionally return
852 * an error or warning message for the alignment command(s).
855 * an array of one or more alignment views to process
858 public String superposeStructures(List<AlignmentViewPanel> alignWith)
861 String[] files = getStructureFiles();
863 if (!waitForFileLoad(files))
869 for (AlignmentViewPanel view : alignWith)
871 AlignmentI alignment = view.getAlignment();
872 HiddenColumns hiddenCols = alignment.getHiddenColumns();
875 * 'matched' bit i will be set for visible alignment columns i where
876 * all sequences have a residue with a mapping to their PDB structure
878 BitSet matched = new BitSet();
879 final int width = alignment.getWidth();
880 for (int m = 0; m < width; m++)
882 if (hiddenCols == null || hiddenCols.isVisible(m))
888 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
889 for (int f = 0; f < files.length; f++)
891 structures[f] = new AAStructureBindingModel.SuperposeData(width,
892 getModelIdForFile(files[f]));
896 * Calculate the superposable alignment columns ('matched'), and the
897 * corresponding structure residue positions (structures.pdbResNo)
899 int refStructure = findSuperposableResidues(alignment, matched,
903 * require at least 4 positions to be able to execute superposition
905 int nmatched = matched.cardinality();
906 if (nmatched < MIN_POS_TO_SUPERPOSE)
908 String msg = MessageManager
909 .formatMessage("label.insufficient_residues", nmatched);
910 error += view.getViewName() + ": " + msg + "; ";
915 * get a model of the superposable residues in the reference structure
917 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
921 * Show all as backbone before doing superposition(s)
922 * (residues used for matching will be shown as ribbon)
924 // todo better way to ensure synchronous than setting getReply true!!
925 executeCommands(commandGenerator.showBackbone(), true, null);
927 AtomSpecType backbone = structures[refStructure].isRna
928 ? AtomSpecType.PHOSPHATE
929 : AtomSpecType.ALPHA;
931 * superpose each (other) structure to the reference in turn
933 for (int i = 0; i < structures.length; i++)
935 if (i != refStructure)
937 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
938 List<StructureCommandI> commands = commandGenerator
939 .superposeStructures(refAtoms, atomSpec, backbone);
940 List<String> replies = executeCommands(commands, true, null);
941 for (String reply : replies)
943 // return this error (Chimera only) to the user
944 if (reply.toLowerCase(Locale.ROOT)
945 .contains("unequal numbers of atoms"))
947 error += "; " + reply;
957 private AtomSpecModel getAtomSpec(
958 AAStructureBindingModel.SuperposeData superposeData,
961 AtomSpecModel model = new AtomSpecModel();
962 int nextColumnMatch = matched.nextSetBit(0);
963 while (nextColumnMatch != -1)
965 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
966 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
967 superposeData.chain);
968 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
975 * returns the current sequenceRenderer that should be used to colour the
982 public abstract SequenceRenderer getSequenceRenderer(
983 AlignmentViewPanel alignment);
986 * Sends a command to the structure viewer to colour each chain with a
987 * distinct colour (to the extent supported by the viewer)
989 public void colourByChain()
991 colourBySequence = false;
993 // TODO: JAL-628 colour chains distinctly across all visible models
995 executeCommand(false, COLOURING_STRUCTURES,
996 commandGenerator.colourByChain());
1000 * Sends a command to the structure viewer to colour each chain with a
1001 * distinct colour (to the extent supported by the viewer)
1003 public void colourByCharge()
1005 colourBySequence = false;
1007 executeCommands(commandGenerator.colourByCharge(), false,
1008 COLOURING_STRUCTURES);
1012 * Sends a command to the structure to apply a colour scheme (defined in
1013 * Jalview but not necessarily applied to the alignment), which defines a
1014 * colour per residue letter. More complex schemes (e.g. that depend on
1015 * consensus) cannot be used here and are ignored.
1019 public void colourByJalviewColourScheme(ColourSchemeI cs)
1021 colourBySequence = false;
1023 if (cs == null || !cs.isSimple())
1029 * build a map of {Residue3LetterCode, Color}
1031 Map<String, Color> colours = new HashMap<>();
1032 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1034 for (String resName : residues)
1036 char res = resName.length() == 3
1037 ? ResidueProperties.getSingleCharacterCode(resName)
1038 : resName.charAt(0);
1039 Color colour = cs.findColour(res, 0, null, null, 0f);
1040 colours.put(resName, colour);
1044 * pass to the command constructor, and send the command
1046 List<StructureCommandI> cmd = commandGenerator
1047 .colourByResidues(colours);
1048 executeCommands(cmd, false, COLOURING_STRUCTURES);
1051 public void setBackgroundColour(Color col)
1053 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1054 executeCommand(false, null, cmd);
1058 * Execute one structure viewer command. If {@code getReply} is true, may
1059 * optionally return one or more reply messages, else returns null.
1064 protected abstract List<String> executeCommand(StructureCommandI cmd,
1068 * Executes one or more structure viewer commands
1074 protected List<String> executeCommands(List<StructureCommandI> commands,
1075 boolean getReply, String msg)
1077 return executeCommand(getReply, msg,
1078 commands.toArray(new StructureCommandI[commands.size()]));
1082 * Executes one or more structure viewer commands, optionally returning the
1083 * reply, and optionally showing a status message while the command is being
1086 * If a reply is wanted, the execution is done synchronously (waits),
1087 * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1088 * are sending commands that need to execute before later calls to
1089 * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1090 * set getReply true to ensure that commands are not executed out of order.
1097 protected List<String> executeCommand(boolean getReply, String msg,
1098 StructureCommandI... cmds)
1100 JalviewStructureDisplayI theViewer = getViewer();
1101 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1106 * execute and wait for reply
1108 List<String> response = new ArrayList<>();
1111 for (StructureCommandI cmd : cmds)
1113 List<String> replies = executeCommand(cmd, true);
1114 if (replies != null)
1116 response.addAll(replies);
1124 theViewer.stopProgressBar(null, handle);
1132 String threadName = msg == null ? "StructureCommand" : msg;
1133 new Thread(new Runnable()
1140 for (StructureCommandI cmd : cmds)
1142 executeCommand(cmd, false);
1148 SwingUtilities.invokeLater(new Runnable()
1153 theViewer.stopProgressBar(null, handle);
1159 }, threadName).start();
1164 * Colours any structures associated with sequences in the given alignment as
1165 * coloured in the alignment view, provided colourBySequence is enabled
1167 public void colourBySequence(AlignmentViewPanel alignmentv)
1169 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1173 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1176 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1177 .colourBySequence(colourMap);
1178 executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1182 * Centre the display in the structure viewer
1184 public void focusView()
1186 executeCommand(false, null, commandGenerator.focusView());
1190 * Generates and executes a command to show only specified chains in the
1191 * structure viewer. The list of chains to show should contain entries
1192 * formatted as "pdbid:chaincode".
1196 public void showChains(List<String> toShow)
1198 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1201 * Reformat the pdbid:chainCode values as modelNo:chainCode
1202 * since this is what is needed to construct the viewer command
1203 * todo: find a less messy way to do this
1205 List<String> showThese = new ArrayList<>();
1206 for (String chainId : toShow)
1208 String[] tokens = chainId.split("\\:");
1209 if (tokens.length == 2)
1211 String pdbFile = getFileForChain(chainId);
1212 String model = getModelIdForFile(pdbFile);
1213 showThese.add(model + ":" + tokens[1]);
1216 executeCommands(commandGenerator.showChains(showThese), false, null);
1220 * Answers the structure viewer's model id given a PDB file name. Returns an
1221 * empty string if model id is not found.
1226 protected abstract String getModelIdForFile(String chainId);
1228 public boolean hasFileLoadingError()
1230 return fileLoadingError != null && fileLoadingError.length() > 0;
1234 * Returns the FeatureRenderer for the given alignment view
1239 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1241 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1247 return ap.getFeatureRenderer();
1250 protected void setStructureCommands(StructureCommandsI cmd)
1252 commandGenerator = cmd;
1256 * Records association of one chain id (formatted as "pdbid:chainCode") with
1257 * the corresponding PDB file name
1262 public void addChainFile(String chainId, String fileName)
1264 chainFile.put(chainId, fileName);
1268 * Returns the PDB filename for the given chain id (formatted as
1269 * "pdbid:chainCode"), or null if not found
1274 protected String getFileForChain(String chainId)
1276 return chainFile.get(chainId);
1280 public void updateColours(Object source)
1282 if (getViewer() == null)
1284 // can happen if a viewer was not instantiated or cleaned up and is still
1285 // registered - mostly during tests
1288 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1289 // ignore events from panels not used to colour this view
1290 if (!getViewer().isUsedForColourBy(ap))
1294 if (!isLoadingFromArchive())
1296 colourBySequence(ap);
1300 public StructureCommandsI getCommandGenerator()
1302 return commandGenerator;
1305 protected abstract ViewerType getViewerType();
1308 * Builds a data structure which records mapped structure residues for each
1309 * colour. From this we can easily generate the viewer commands for colour by
1310 * sequence. Constructs and returns a map of {@code Color} to
1311 * {@code AtomSpecModel}, where the atomspec model holds
1319 * Ordering is by order of addition (for colours), natural ordering (for
1320 * models and chains)
1327 protected Map<Object, AtomSpecModel> buildColoursMap(
1328 StructureSelectionManager ssm, SequenceI[][] sequence,
1329 AlignmentViewPanel viewPanel)
1331 String[] files = getStructureFiles();
1332 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1333 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1334 FeatureColourFinder finder = new FeatureColourFinder(fr);
1335 AlignViewportI viewport = viewPanel.getAlignViewport();
1336 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1337 AlignmentI al = viewport.getAlignment();
1338 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1339 Color lastColour = null;
1341 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1343 final String modelId = getModelIdForFile(files[pdbfnum]);
1344 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1346 if (mapping == null || mapping.length < 1)
1351 int startPos = -1, lastPos = -1;
1352 String lastChain = "";
1353 for (int s = 0; s < sequence[pdbfnum].length; s++)
1355 for (int sp, m = 0; m < mapping.length; m++)
1357 final SequenceI seq = sequence[pdbfnum][s];
1358 if (mapping[m].getSequence() == seq
1359 && (sp = al.findIndex(seq)) > -1)
1361 SequenceI asp = al.getSequenceAt(sp);
1362 for (int r = 0; r < asp.getLength(); r++)
1364 // no mapping to gaps in sequence
1365 if (Comparison.isGap(asp.getCharAt(r)))
1369 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1371 if (pos < 1 || pos == lastPos)
1376 Color colour = sr.getResidueColour(seq, r, finder);
1379 * darker colour for hidden regions
1381 if (!cs.isVisible(r))
1383 colour = Color.GRAY;
1386 final String chain = mapping[m].getChain();
1389 * Just keep incrementing the end position for this colour range
1390 * _unless_ colour, PDB model or chain has changed, or there is a
1391 * gap in the mapped residue sequence
1393 final boolean newColour = !colour.equals(lastColour);
1394 final boolean nonContig = lastPos + 1 != pos;
1395 final boolean newChain = !chain.equals(lastChain);
1396 if (newColour || nonContig || newChain)
1400 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1401 lastPos, lastChain);
1405 lastColour = colour;
1409 // final colour range
1410 if (lastColour != null)
1412 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1413 lastPos, lastChain);
1424 * todo better refactoring (map lookup or similar to get viewer structure id)
1430 protected String getModelId(int pdbfnum, String file)
1432 return String.valueOf(pdbfnum);
1436 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1437 * full PDB file path
1442 public void stashFoundChains(StructureFile pdb, String file)
1444 for (int i = 0; i < pdb.getChains().size(); i++)
1446 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1447 addChainFile(chid, file);
1448 getChainNames().add(chid);
1453 * Helper method to add one contiguous range to the AtomSpec model for the
1454 * given value (creating the model if necessary). As used by Jalview,
1457 * <li>a colour, when building a 'colour structure by sequence' command</li>
1458 * <li>a feature value, when building a 'set Chimera attributes from features'
1469 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1470 Object value, String model, int startPos, int endPos,
1474 * Get/initialize map of data for the colour
1476 AtomSpecModel atomSpec = map.get(value);
1477 if (atomSpec == null)
1479 atomSpec = new AtomSpecModel();
1480 map.put(value, atomSpec);
1483 atomSpec.addRange(model, startPos, endPos, chain);
1487 * Returns the file extension (including '.' separator) to use for a saved
1488 * viewer session file. Default is to return null (not supported), override as
1493 public String getSessionFileExtension()
1499 * If supported, saves the state of the structure viewer to a temporary file
1500 * and returns the file. Returns null and logs an error on any failure.
1504 public File saveSession()
1506 String prefix = getViewerType().toString();
1507 String suffix = getSessionFileExtension();
1511 f = File.createTempFile(prefix, suffix);
1513 } catch (IOException e)
1515 Console.error(String.format("Error saving %s session: %s", prefix,
1523 * Saves the structure viewer session to the given file
1527 protected void saveSession(File f)
1529 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1532 executeCommand(cmd, false);
1537 * Returns true if the viewer is an external structure viewer for which the
1538 * process is still alive, else false (for Jmol, or an external viewer which
1539 * the user has independently closed)
1543 public boolean isViewerRunning()
1549 * Closes Jalview's structure viewer panel and releases associated resources.
1550 * If it is managing an external viewer program, and {@code forceClose} is
1551 * true, also asks that program to close.
1555 public void closeViewer(boolean forceClose)
1557 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1558 releaseUIResources();
1561 * end the thread that closes this panel if the external viewer closes
1563 if (externalViewerMonitor != null)
1565 externalViewerMonitor.interrupt();
1566 externalViewerMonitor = null;
1573 StructureCommandI cmd = getCommandGenerator().closeViewer();
1576 executeCommand(cmd, false);
1582 * Returns the URL of a help page for the structure viewer, or null if none is
1587 public String getHelpURL()
1594 * Helper method to build a map of
1595 * { featureType, { feature value, AtomSpecModel } }
1601 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1602 AlignmentViewPanel viewPanel)
1604 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1605 String[] files = getStructureFiles();
1611 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1617 AlignViewportI viewport = viewPanel.getAlignViewport();
1618 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1621 * if alignment is showing features from complement, we also transfer
1622 * these features to the corresponding mapped structure residues
1624 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1625 List<String> complementFeatures = new ArrayList<>();
1626 FeatureRenderer complementRenderer = null;
1627 if (showLinkedFeatures)
1629 AlignViewportI comp = fr.getViewport().getCodingComplement();
1632 complementRenderer = Desktop.getAlignFrameFor(comp)
1633 .getFeatureRenderer();
1634 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1637 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1642 AlignmentI alignment = viewPanel.getAlignment();
1643 SequenceI[][] seqs = getSequence();
1645 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1647 String modelId = getModelIdForFile(files[pdbfnum]);
1648 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1650 if (mapping == null || mapping.length < 1)
1655 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1657 for (int m = 0; m < mapping.length; m++)
1659 final SequenceI seq = seqs[pdbfnum][seqNo];
1660 int sp = alignment.findIndex(seq);
1661 StructureMapping structureMapping = mapping[m];
1662 if (structureMapping.getSequence() == seq && sp > -1)
1665 * found a sequence with a mapping to a structure;
1666 * now scan its features
1668 if (!visibleFeatures.isEmpty())
1670 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1673 if (showLinkedFeatures)
1675 scanComplementFeatures(complementRenderer, structureMapping,
1676 seq, theMap, modelId);
1686 * Ask the structure viewer to open a session file. Returns true if
1687 * successful, else false (or not supported).
1692 public boolean openSession(String filepath)
1694 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1699 executeCommand(cmd, true);
1700 // todo: test for failure - how?
1705 * Scans visible features in mapped positions of the CDS/peptide complement,
1706 * and adds any found to the map of attribute values/structure positions
1708 * @param complementRenderer
1709 * @param structureMapping
1712 * @param modelNumber
1714 protected static void scanComplementFeatures(
1715 FeatureRenderer complementRenderer,
1716 StructureMapping structureMapping, SequenceI seq,
1717 Map<String, Map<Object, AtomSpecModel>> theMap,
1721 * for each sequence residue mapped to a structure position...
1723 for (int seqPos : structureMapping.getMapping().keySet())
1726 * find visible complementary features at mapped position(s)
1728 MappedFeatures mf = complementRenderer
1729 .findComplementFeaturesAtResidue(seq, seqPos);
1732 for (SequenceFeature sf : mf.features)
1734 String type = sf.getType();
1737 * Don't copy features which originated from Chimera
1739 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1740 .equals(sf.getFeatureGroup()))
1746 * record feature 'value' (score/description/type) as at the
1747 * corresponding structure position
1749 List<int[]> mappedRanges = structureMapping
1750 .getPDBResNumRanges(seqPos, seqPos);
1752 if (!mappedRanges.isEmpty())
1754 String value = sf.getDescription();
1755 if (value == null || value.length() == 0)
1759 float score = sf.getScore();
1760 if (score != 0f && !Float.isNaN(score))
1762 value = Float.toString(score);
1764 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1765 if (featureValues == null)
1767 featureValues = new HashMap<>();
1768 theMap.put(type, featureValues);
1770 for (int[] range : mappedRanges)
1772 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1773 range[1], structureMapping.getChain());
1782 * Inspect features on the sequence; for each feature that is visible,
1783 * determine its mapped ranges in the structure (if any) according to the
1784 * given mapping, and add them to the map.
1786 * @param visibleFeatures
1792 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1793 StructureMapping mapping, SequenceI seq,
1794 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1796 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1797 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1798 for (SequenceFeature sf : sfs)
1800 String type = sf.getType();
1803 * Don't copy features which originated from Chimera
1805 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1806 .equals(sf.getFeatureGroup()))
1811 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1814 if (!mappedRanges.isEmpty())
1816 String value = sf.getDescription();
1817 if (value == null || value.length() == 0)
1821 float score = sf.getScore();
1822 if (score != 0f && !Float.isNaN(score))
1824 value = Float.toString(score);
1826 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1827 if (featureValues == null)
1829 featureValues = new HashMap<>();
1830 theMap.put(type, featureValues);
1832 for (int[] range : mappedRanges)
1834 addAtomSpecRange(featureValues, value, modelId, range[0],
1835 range[1], mapping.getChain());
1842 * Returns the number of structure files in the structure viewer and mapped to
1843 * Jalview. This may be zero if the files are still in the process of loading
1848 public int getMappedStructureCount()
1850 String[] files = getStructureFiles();
1851 return files == null ? 0 : files.length;
1855 * Starts a thread that waits for the external viewer program process to
1856 * finish, so that we can then close the associated resources. This avoids
1857 * leaving orphaned viewer panels in Jalview if the user closes the external
1862 protected void startExternalViewerMonitor(Process p)
1864 externalViewerMonitor = new Thread(new Runnable()
1873 JalviewStructureDisplayI display = getViewer();
1874 if (display != null)
1876 display.closeViewer(false);
1878 } catch (InterruptedException e)
1880 // exit thread if Chimera Viewer is closed in Jalview
1884 externalViewerMonitor.start();
1888 * If supported by the external structure viewer, sends it commands to notify
1889 * model or selection changes to the specified URL (where Jalview has started
1894 protected void startListening(String uri)
1896 List<StructureCommandI> commands = getCommandGenerator()
1897 .startNotifications(uri);
1898 if (commands != null)
1900 executeCommands(commands, false, null);
1905 * If supported by the external structure viewer, sends it commands to stop
1906 * notifying model or selection changes
1908 protected void stopListening()
1910 List<StructureCommandI> commands = getCommandGenerator()
1911 .stopNotifications();
1912 if (commands != null)
1914 executeCommands(commands, false, null);
1919 * If supported by the structure viewer, queries it for all residue attributes
1920 * with the given attribute name, and creates features on corresponding
1921 * residues of the alignment. Returns the number of features added.
1924 * @param alignmentPanel
1927 public int copyStructureAttributesToFeatures(String attName,
1928 AlignmentPanel alignmentPanel)
1930 StructureCommandI cmd = getCommandGenerator()
1931 .getResidueAttributes(attName);
1936 List<String> residueAttributes = executeCommand(cmd, true);
1938 int featuresAdded = createFeaturesForAttributes(attName,
1940 if (featuresAdded > 0)
1942 alignmentPanel.getFeatureRenderer().featuresAdded();
1944 return featuresAdded;
1948 * Parses {@code residueAttributes} and creates sequence features on any
1949 * mapped alignment residues. Returns the number of features created.
1951 * {@code residueAttributes} is the reply from the structure viewer to a
1952 * command to list any residue attributes for the given attribute name. Syntax
1953 * and parsing of this is viewer-specific.
1956 * @param residueAttributes
1959 protected int createFeaturesForAttributes(String attName,
1960 List<String> residueAttributes)