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.Collections;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.LinkedHashMap;
33 import java.util.List;
36 import javax.swing.SwingUtilities;
38 import jalview.api.AlignViewportI;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.api.FeatureRenderer;
41 import jalview.api.SequenceRenderer;
42 import jalview.api.StructureSelectionManagerProvider;
43 import jalview.api.structures.JalviewStructureDisplayI;
44 import jalview.bin.Cache;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.HiddenColumns;
47 import jalview.datamodel.MappedFeatures;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceFeature;
50 import jalview.datamodel.SequenceI;
51 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
52 import jalview.gui.AlignmentPanel;
53 import jalview.gui.Desktop;
54 import jalview.gui.StructureViewer.ViewerType;
55 import jalview.io.DataSourceType;
56 import jalview.io.StructureFile;
57 import jalview.renderer.seqfeatures.FeatureColourFinder;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.schemes.ResidueProperties;
60 import jalview.structure.AtomSpec;
61 import jalview.structure.AtomSpecModel;
62 import jalview.structure.StructureCommandI;
63 import jalview.structure.StructureCommandsI;
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 protein structure model binding.
73 * Initial version created by refactoring JMol and Chimera binding models, but
74 * other 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 = "";
97 * The pdb residue number (if any) mapped to columns of the alignment
99 public int[] pdbResNo; // or use SparseIntArray?
101 public String modelId;
107 * width of alignment (number of columns that may potentially
108 * participate in superposition)
110 * structure viewer model number
112 public SuperposeData(int width, String model)
114 pdbResNo = new int[width];
119 private static final int MIN_POS_TO_SUPERPOSE = 4;
121 private static final String COLOURING_STRUCTURES = MessageManager
122 .getString("status.colouring_structures");
125 * the Jalview panel through which the user interacts
126 * with the structure viewer
128 private JalviewStructureDisplayI viewer;
131 * helper that generates command syntax
133 private StructureCommandsI commandGenerator;
135 private StructureSelectionManager ssm;
138 * modelled chains, formatted as "pdbid:chainCode"
140 private List<String> chainNames;
143 * lookup of pdb file name by key "pdbid:chainCode"
145 private Map<String, String> chainFile;
148 * distinct PDB entries (pdb files) associated
151 private PDBEntry[] pdbEntry;
154 * sequences mapped to each pdbentry
156 private SequenceI[][] sequence;
159 * array of target chains for sequences - tied to pdbentry and sequence[]
161 private String[][] chains;
164 * datasource protocol for access to PDBEntrylatest
166 DataSourceType protocol = null;
168 protected boolean colourBySequence = true;
170 private boolean nucleotide;
172 private boolean finishedInit = false;
175 * current set of model filenames loaded in the Jmol instance
176 * array index 0, 1, 2... corresponds to Jmol model numbers 1, 2, 3...
178 protected String[] modelFileNames = null;
180 public String fileLoadingError;
182 private boolean showAlignmentOnly;
185 * a list of chains "pdbid:chainid" to hide in the viewer
187 // TODO make private once deprecated JalviewJmolBinding.centerViewer removed
188 protected List<String> chainsToHide;
190 private boolean hideHiddenRegions;
192 protected Thread externalViewerMonitor;
200 public AAStructureBindingModel(StructureSelectionManager ssm,
204 this.sequence = seqs;
205 chainsToHide = new ArrayList<>();
206 chainNames = new ArrayList<>();
207 chainFile = new HashMap<>();
218 public AAStructureBindingModel(StructureSelectionManager ssm,
219 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
220 DataSourceType protocol)
222 this(ssm, sequenceIs);
223 this.nucleotide = Comparison.isNucleotide(sequenceIs);
224 this.pdbEntry = pdbentry;
225 this.protocol = protocol;
226 chainsToHide = new ArrayList<>();
231 private boolean resolveChains()
234 * final count of chain mappings discovered
237 // JBPNote: JAL-2693 - this should be a list of chain mappings per
238 // [pdbentry][sequence]
239 String[][] newchains = new String[pdbEntry.length][];
241 for (PDBEntry pdb : pdbEntry)
243 SequenceI[] seqsForPdb = sequence[pe];
244 if (seqsForPdb != null)
246 newchains[pe] = new String[seqsForPdb.length];
248 for (SequenceI asq : seqsForPdb)
250 String chain = (chains != null && chains[pe] != null)
253 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
254 : asq.getDatasetSequence();
255 if (sq.getAllPDBEntries() != null)
257 for (PDBEntry pdbentry : sq.getAllPDBEntries())
259 if (pdb.getFile() != null && pdbentry.getFile() != null
260 && pdb.getFile().equals(pdbentry.getFile()))
262 String chaincode = pdbentry.getChainCode();
263 if (chaincode != null && chaincode.length() > 0)
272 newchains[pe][se] = chain;
280 return chainmaps > 0;
283 public StructureSelectionManager getSsm()
289 * Returns the i'th PDBEntry (or null)
294 public PDBEntry getPdbEntry(int i)
296 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
300 * Answers true if this binding includes the given PDB id, else false
305 public boolean hasPdbId(String pdbId)
307 if (pdbEntry != null)
309 for (PDBEntry pdb : pdbEntry)
311 if (pdb.getId().equals(pdbId))
321 * Returns the number of modelled PDB file entries.
325 public int getPdbCount()
327 return pdbEntry == null ? 0 : pdbEntry.length;
330 public SequenceI[][] getSequence()
335 public String[][] getChains()
340 public DataSourceType getProtocol()
345 // TODO may remove this if calling methods can be pulled up here
346 protected void setPdbentry(PDBEntry[] pdbentry)
348 this.pdbEntry = pdbentry;
351 protected void setSequence(SequenceI[][] sequence)
353 this.sequence = sequence;
356 protected void setChains(String[][] chains)
358 this.chains = chains;
362 * Construct a title string for the viewer window based on the data Jalview
371 public String getViewerTitle(String viewerName, boolean verbose)
373 if (getSequence() == null || getSequence().length < 1
374 || getPdbCount() < 1 || getSequence()[0].length < 1)
376 return ("Jalview " + viewerName + " Window");
378 // TODO: give a more informative title when multiple structures are
380 StringBuilder title = new StringBuilder(64);
381 final PDBEntry pdbe = getPdbEntry(0);
382 title.append(viewerName + " view for " + getSequence()[0][0].getName()
383 + ":" + pdbe.getId());
387 String method = (String) pdbe.getProperty("method");
390 title.append(" Method: ").append(method);
392 String chain = (String) pdbe.getProperty("chains");
395 title.append(" Chain:").append(chain);
398 return title.toString();
402 * Called by after closeViewer is called, to release any resources and
403 * references so they can be garbage collected. Override if needed.
405 protected void releaseUIResources()
410 public void releaseReferences(Object svl)
414 public boolean isColourBySequence()
416 return colourBySequence;
420 * Called when the binding thinks the UI needs to be refreshed after a
421 * structure viewer state change. This could be because structures were
422 * loaded, or because an error has occurred. Default does nothing, override as
425 public void refreshGUI()
427 getViewer().updateTitleAndMenus();
431 * Instruct the Jalview binding to update the pdbentries vector if necessary
432 * prior to matching the viewer's contents to the list of structure files
433 * Jalview knows about. By default does nothing, override as required.
435 public void refreshPdbEntries()
439 public void setColourBySequence(boolean colourBySequence)
441 this.colourBySequence = colourBySequence;
444 protected void addSequenceAndChain(int pe, SequenceI[] seq,
447 if (pe < 0 || pe >= getPdbCount())
449 throw new Error(MessageManager.formatMessage(
450 "error.implementation_error_no_pdbentry_from_index",
452 { Integer.valueOf(pe).toString() }));
454 final String nullChain = "TheNullChain";
455 List<SequenceI> s = new ArrayList<>();
456 List<String> c = new ArrayList<>();
457 if (getChains() == null)
459 setChains(new String[getPdbCount()][]);
461 if (getSequence()[pe] != null)
463 for (int i = 0; i < getSequence()[pe].length; i++)
465 s.add(getSequence()[pe][i]);
466 if (getChains()[pe] != null)
468 if (i < getChains()[pe].length)
470 c.add(getChains()[pe][i]);
479 if (tchain != null && tchain.length > 0)
486 for (int i = 0; i < seq.length; i++)
488 if (!s.contains(seq[i]))
491 if (tchain != null && i < tchain.length)
493 c.add(tchain[i] == null ? nullChain : tchain[i]);
497 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
498 getSequence()[pe] = tmp;
501 String[] tch = c.toArray(new String[c.size()]);
502 for (int i = 0; i < tch.length; i++)
504 if (tch[i] == nullChain)
509 getChains()[pe] = tch;
513 getChains()[pe] = null;
518 * add structures and any known sequence associations
520 * @returns the pdb entries added to the current set.
522 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
523 SequenceI[][] seq, String[][] chns)
525 List<PDBEntry> v = new ArrayList<>();
526 List<int[]> rtn = new ArrayList<>();
527 for (int i = 0; i < getPdbCount(); i++)
529 v.add(getPdbEntry(i));
531 for (int i = 0; i < pdbe.length; i++)
533 int r = v.indexOf(pdbe[i]);
534 if (r == -1 || r >= getPdbCount())
536 rtn.add(new int[] { v.size(), i });
541 // just make sure the sequence/chain entries are all up to date
542 addSequenceAndChain(r, seq[i], chns[i]);
545 pdbe = v.toArray(new PDBEntry[v.size()]);
549 // expand the tied sequence[] and string[] arrays
550 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
551 String[][] sch = new String[getPdbCount()][];
552 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
553 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
556 pdbe = new PDBEntry[rtn.size()];
557 for (int r = 0; r < pdbe.length; r++)
559 int[] stri = (rtn.get(r));
560 // record the pdb file as a new addition
561 pdbe[r] = getPdbEntry(stri[0]);
562 // and add the new sequence/chain entries
563 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
574 * Add sequences to the pe'th pdbentry's sequence set.
579 public void addSequence(int pe, SequenceI[] seq)
581 addSequenceAndChain(pe, seq, null);
585 * add the given sequences to the mapping scope for the given pdb file handle
588 * - pdbFile identifier
590 * - set of sequences it can be mapped to
592 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
594 for (int pe = 0; pe < getPdbCount(); pe++)
596 if (getPdbEntry(pe).getFile().equals(pdbFile))
598 addSequence(pe, seq);
604 public abstract void highlightAtoms(List<AtomSpec> atoms);
606 protected boolean isNucleotide()
608 return this.nucleotide;
612 * Returns a readable description of all mappings for the wrapped pdbfile to
613 * any mapped sequences
619 public String printMappings()
621 if (pdbEntry == null)
625 StringBuilder sb = new StringBuilder(128);
626 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
628 String pdbfile = getPdbEntry(pdbe).getFile();
629 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
630 sb.append(getSsm().printMappings(pdbfile, seqs));
632 return sb.toString();
636 * Returns the mapped structure position for a given aligned column of a given
637 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
638 * not mapped to structure.
645 protected int getMappedPosition(SequenceI seq, int alignedPos,
646 StructureMapping mapping)
648 if (alignedPos >= seq.getLength())
653 if (Comparison.isGap(seq.getCharAt(alignedPos)))
657 int seqPos = seq.findPosition(alignedPos);
658 int pos = mapping.getPDBResNum(seqPos);
663 * Helper method to identify residues that can participate in a structure
664 * superposition command. For each structure, identify a sequence in the
665 * alignment which is mapped to the structure. Identify non-gapped columns in
666 * the sequence which have a mapping to a residue in the structure. Returns
667 * the index of the first structure that has a mapping to the alignment.
670 * the sequence alignment which is the basis of structure
673 * a BitSet, where bit j is set to indicate that every structure has
674 * a mapped residue present in column j (so the column can
675 * participate in structure alignment)
677 * an array of data beans corresponding to pdb file index
680 protected int findSuperposableResidues(AlignmentI alignment,
682 AAStructureBindingModel.SuperposeData[] structures)
684 int refStructure = -1;
685 String[] files = getStructureFiles();
690 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
692 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
696 * Find the first mapped sequence (if any) for this PDB entry which is in
699 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
700 for (int s = 0; s < seqCountForPdbFile; s++)
702 for (StructureMapping mapping : mappings)
704 final SequenceI theSequence = getSequence()[pdbfnum][s];
705 if (mapping.getSequence() == theSequence
706 && alignment.findIndex(theSequence) > -1)
708 if (refStructure < 0)
710 refStructure = pdbfnum;
712 for (int r = 0; r < alignment.getWidth(); r++)
718 int pos = getMappedPosition(theSequence, r, mapping);
719 if (pos < 1 || pos == lastPos)
725 structures[pdbfnum].pdbResNo[r] = pos;
727 String chain = mapping.getChain();
728 if (chain != null && chain.trim().length() > 0)
730 structures[pdbfnum].chain = chain;
732 structures[pdbfnum].pdbId = mapping.getPdbId();
733 structures[pdbfnum].isRna = theSequence.getRNA() != null;
736 * move on to next pdb file (ignore sequences for other chains
737 * for the same structure)
739 s = seqCountForPdbFile;
740 break; // fixme break out of two loops here!
749 * Returns true if the structure viewer has loaded all of the files of
750 * interest (identified by the file mapping having been set up), or false if
751 * any are still not loaded after a timeout interval.
755 protected boolean waitForFileLoad(String[] files)
758 * give up after 10 secs plus 1 sec per file
760 long starttime = System.currentTimeMillis();
761 long endTime = 10000 + 1000 * files.length + starttime;
762 String notLoaded = null;
764 boolean waiting = true;
765 while (waiting && System.currentTimeMillis() < endTime)
768 for (String file : files)
777 StructureMapping[] sm = getSsm().getMapping(file);
778 if (sm == null || sm.length == 0)
782 } catch (Throwable x)
792 "Timed out waiting for structure viewer to load file "
800 public boolean isListeningFor(SequenceI seq)
802 if (sequence != null)
804 for (SequenceI[] seqs : sequence)
808 for (SequenceI s : seqs)
810 if (s == seq || (s.getDatasetSequence() != null
811 && s.getDatasetSequence() == seq.getDatasetSequence()))
822 public boolean isFinishedInit()
827 public void setFinishedInit(boolean fi)
829 this.finishedInit = fi;
833 * Returns a list of chains mapped in this viewer, formatted as
838 public List<String> getChainNames()
844 * Returns the Jalview panel hosting the structure viewer (if any)
848 public JalviewStructureDisplayI getViewer()
853 public void setViewer(JalviewStructureDisplayI v)
859 * Constructs and sends a command to align structures against a reference
860 * structure, based on one or more sequence alignments. May optionally return
861 * an error or warning message for the alignment command(s).
864 * an array of one or more alignment views to process
867 public String superposeStructures(List<AlignmentViewPanel> alignWith)
870 String[] files = getStructureFiles();
872 if (!waitForFileLoad(files))
878 for (AlignmentViewPanel view : alignWith)
880 AlignmentI alignment = view.getAlignment();
881 HiddenColumns hiddenCols = alignment.getHiddenColumns();
884 * 'matched' bit i will be set for visible alignment columns i where
885 * all sequences have a residue with a mapping to their PDB structure
887 BitSet matched = new BitSet();
888 final int width = alignment.getWidth();
889 for (int m = 0; m < width; m++)
891 if (hiddenCols == null || hiddenCols.isVisible(m))
897 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
898 for (int f = 0; f < files.length; f++)
900 structures[f] = new AAStructureBindingModel.SuperposeData(width,
901 getModelIdForFile(files[f]));
905 * Calculate the superposable alignment columns ('matched'), and the
906 * corresponding structure residue positions (structures.pdbResNo)
908 int refStructure = findSuperposableResidues(alignment, matched,
912 * require at least 4 positions to be able to execute superposition
914 int nmatched = matched.cardinality();
915 if (nmatched < MIN_POS_TO_SUPERPOSE)
917 String msg = MessageManager
918 .formatMessage("label.insufficient_residues", nmatched);
919 error += view.getViewName() + ": " + msg + "; ";
924 * get a model of the superposable residues in the reference structure
926 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
930 * Show all as backbone before doing superposition(s)
931 * (residues used for matching will be shown as ribbon)
932 * while remembering to hide any chains unselected for display
934 // todo better way to ensure synchronous than setting getReply true!!
935 executeCommands(commandGenerator.showBackbone(), true, null);
939 * superpose each (other) structure to the reference in turn
941 for (int i = 0; i < structures.length; i++)
943 if (i != refStructure)
945 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
946 List<StructureCommandI> commands = commandGenerator
947 .superposeStructures(refAtoms, atomSpec);
948 List<String> replies = executeCommands(commands, true, null);
949 for (String reply : replies)
951 // return this error (Chimera only) to the user
952 if (reply.toLowerCase().contains("unequal numbers of atoms"))
954 error += "; " + reply;
964 private AtomSpecModel getAtomSpec(
965 AAStructureBindingModel.SuperposeData superposeData,
968 AtomSpecModel model = new AtomSpecModel();
969 int nextColumnMatch = matched.nextSetBit(0);
970 while (nextColumnMatch != -1)
972 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
973 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
974 superposeData.chain);
975 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
982 * returns the current sequenceRenderer that should be used to colour the
989 public abstract SequenceRenderer getSequenceRenderer(
990 AlignmentViewPanel alignment);
993 * Recolours mapped residues in the structure viewer to match colours in the
994 * given alignment panel, provided colourBySequence is selected. Colours
995 * should also be applied to any hidden mapped residues (so that they are
996 * shown correctly if these get unhidden).
1000 protected void colourBySequence(AlignmentViewPanel viewPanel)
1003 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1007 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1010 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1011 .colourBySequence(colourMap);
1012 executeCommands(colourBySequenceCommands, false, null);
1017 * Sends a command to the structure viewer to colour each chain with a
1018 * distinct colour (to the extent supported by the viewer)
1020 public void colourByChain()
1022 colourBySequence = false;
1023 // TODO: JAL-628 colour chains distinctly across all visible models
1024 executeCommand(commandGenerator.colourByChain(), false,
1025 COLOURING_STRUCTURES);
1029 * Sends a command to the structure viewer to colour each chain with a
1030 * distinct colour (to the extent supported by the viewer)
1032 public void colourByCharge()
1034 colourBySequence = false;
1036 executeCommands(commandGenerator.colourByCharge(), false,
1037 COLOURING_STRUCTURES);
1041 * Sends a command to the structure to apply a colour scheme (defined in
1042 * Jalview but not necessarily applied to the alignment), which defines a
1043 * colour per residue letter. More complex schemes (e.g. that depend on
1044 * consensus) cannot be used here and are ignored.
1048 public void colourByJalviewColourScheme(ColourSchemeI cs)
1050 colourBySequence = false;
1052 if (cs == null || !cs.isSimple())
1058 * build a map of {Residue3LetterCode, Color}
1060 Map<String, Color> colours = new HashMap<>();
1061 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1063 for (String resName : residues)
1065 char res = resName.length() == 3
1066 ? ResidueProperties.getSingleCharacterCode(resName)
1067 : resName.charAt(0);
1068 Color colour = cs.findColour(res, 0, null, null, 0f);
1069 colours.put(resName, colour);
1073 * pass to the command constructor, and send the command
1075 List<StructureCommandI> cmd = commandGenerator
1076 .colourByResidues(colours);
1077 executeCommands(cmd, false, COLOURING_STRUCTURES);
1080 public void setBackgroundColour(Color col)
1082 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1083 executeCommand(cmd, false, null);
1087 * Sends one command to the structure viewer. If {@code getReply} is true, the
1088 * command is sent synchronously, otherwise in a deferred thread.
1090 * If a progress message is supplied, this is displayed before command
1091 * execution, and removed afterwards.
1098 private List<String> executeCommand(StructureCommandI cmd,
1099 boolean getReply, String msg)
1103 return null; // catch unimplemented commands
1105 final JalviewStructureDisplayI theViewer = getViewer();
1106 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1110 * synchronous (same thread) execution so reply can be returned
1114 return executeCommand(cmd, true);
1119 theViewer.stopProgressBar(null, handle);
1126 * asynchronous (new thread) execution if no reply needed
1128 SwingUtilities.invokeLater(new Runnable()
1135 executeCommand(cmd, false);
1140 theViewer.stopProgressBar(null, handle);
1150 * Execute one structure viewer command. If {@code getReply} is true, may
1151 * optionally return one or more reply messages, else returns null.
1156 protected abstract List<String> executeCommand(StructureCommandI cmd,
1160 * Executes one or more structure viewer commands
1166 protected List<String> executeCommands(List<StructureCommandI> commands,
1167 boolean getReply, String msg)
1169 List<String> response = getReply ? new ArrayList<>() : null;
1170 for (StructureCommandI cmd : commands)
1172 List<String> replies = executeCommand(cmd, getReply, msg);
1173 if (replies != null)
1175 response.addAll(replies);
1182 * Recolours the displayed structures, if they are coloured by
1183 * sequence, or 'show only visible alignment' is selected. This supports
1184 * updating structure colours on either change of alignment colours, or change
1185 * to the visible region of the alignment.
1187 public void updateStructureColours(AlignmentViewPanel alignmentv)
1189 if (!isLoadingFinished())
1195 * if structure is not coloured by sequence, but restricted to the alignment,
1196 * then redraw it (but don't recolour it) in case hidden regions have changed
1197 * (todo: specific messaging for change of hidden region only)
1199 if (!colourBySequence)
1201 if (isShowAlignmentOnly())
1203 showStructures(alignmentv.getAlignViewport(), false);
1207 if (getSsm() == null)
1211 colourBySequence(alignmentv);
1215 * Centre the display in the structure viewer
1217 public void focusView()
1219 executeCommand(commandGenerator.focusView(), false, null);
1223 * Answers the structure viewer's model id given a PDB file name. Returns an
1224 * empty string if model id is not found.
1229 protected abstract String getModelIdForFile(String chainId);
1231 public boolean hasFileLoadingError()
1233 return fileLoadingError != null && fileLoadingError.length() > 0;
1237 * Sets the flag for whether only mapped visible residues in the alignment
1238 * should be visible in the structure viewer
1242 public void setShowAlignmentOnly(boolean b)
1244 showAlignmentOnly = b;
1248 * Answers true if only residues mapped to the alignment should be shown in the
1249 * structure viewer, else false
1253 public boolean isShowAlignmentOnly()
1255 return showAlignmentOnly;
1259 * Sets the flag for hiding regions of structure which are hidden in the
1260 * alignment (only applies when the structure viewer is restricted to the
1265 public void setHideHiddenRegions(boolean b)
1267 hideHiddenRegions = b;
1271 * Answers true if regions hidden in the alignment should also be hidden in the
1272 * structure viewer, else false (only applies when the structure viewer is
1273 * restricted to the alignment only)
1277 public boolean isHideHiddenRegions()
1279 return hideHiddenRegions;
1283 * Shows the structures in the viewer, without changing their colouring. This
1284 * is to support toggling of whether the whole structure is shown, or only
1285 * residues mapped to visible regions of the alignment, and/or only selected
1290 * if true, rescale the display to the viewer
1292 public void showStructures(AlignViewportI av, boolean refocus)
1294 if (isShowAlignmentOnly())
1296 StructureCommandI cmd = getCommandGenerator().hideAll();
1297 executeCommand(cmd, false);
1300 AtomSpecModel model = isShowAlignmentOnly() ? getShownResidues(av)
1302 StructureCommandI cmd = getCommandGenerator().showStructures(model);
1303 executeCommand(cmd, false);
1314 * Hides any chains selected _not_ to be shown
1315 * (whether mapped to sequence in the alignment or not)
1317 protected void hideHiddenChains()
1319 StructureCommandI cmd;
1320 for (String pdbChain : chainsToHide)
1322 String modelNo = getModelIdForFile(getFileForChain(pdbChain));
1323 if (!"".equals(modelNo))
1325 String chainId = pdbChain.split(":")[1];
1326 cmd = getCommandGenerator().hideChain(modelNo, chainId);
1327 executeCommand(cmd, false);
1333 * Sets the list of chains to hide (as "pdbid:chain")
1337 public void setChainsToHide(List<String> chains)
1339 chainsToHide = chains;
1343 * Answers true if the specified structure and chain are selected to be shown in
1344 * the viewer, else false
1350 public boolean isShowChain(String pdbId, String chainId)
1352 if (chainsToHide.isEmpty())
1356 return !chainsToHide.contains(pdbId + ":" + chainId);
1360 public abstract String[] getStructureFiles();
1363 * Builds a model of residues mapped from sequences to show on structure,
1364 * taking into account user choices of
1366 * <li>whether hidden regions of the alignment are excluded (hidden) or
1367 * included (greyed out)</li>
1368 * <li>which chains are shown</li>
1374 protected AtomSpecModel getShownResidues(AlignViewportI av)
1376 if (!isShowAlignmentOnly())
1379 "getShownResidues only valid for 'show alignment only')");
1383 AlignmentI alignment = av.getAlignment();
1384 final int width = alignment.getWidth();
1386 String[] files = getStructureFiles();
1388 AtomSpecModel model = new AtomSpecModel();
1390 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1392 String fileName = files[pdbfnum];
1393 final String modelId = getModelIdForFile(files[pdbfnum]);
1394 StructureMapping[] mappings = getSsm().getMapping(fileName);
1397 * Find the first mapped sequence (if any) for this PDB entry which is in
1400 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
1401 for (int s = 0; s < seqCountForPdbFile; s++)
1403 for (StructureMapping mapping : mappings)
1405 final SequenceI theSequence = getSequence()[pdbfnum][s];
1406 if (mapping.getSequence() == theSequence
1407 && alignment.findIndex(theSequence) > -1)
1409 String chainCd = mapping.getChain();
1410 if (!isShowChain(mapping.getPdbId(), chainCd))
1413 * chain is not selected to be displayed, so don't
1414 * waste effort computing its structure positions
1418 Iterator<int[]> visible;
1419 if (isHideHiddenRegions())
1422 * traverse visible columns of the alignment only
1424 visible = alignment.getHiddenColumns()
1425 .getVisContigsIterator(0, width, true);
1430 * traverse all columns (including hidden if any)
1432 visible = Collections.singletonList(new int[] { 0, width })
1435 while (visible.hasNext())
1437 int[] visibleRegion = visible.next();
1438 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1439 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1440 List<int[]> residueRanges = mapping
1441 .getPDBResNumRanges(seqStartPos, seqEndPos);
1442 if (!residueRanges.isEmpty())
1444 for (int[] range : residueRanges)
1446 model.addRange(modelId, range[0], range[1], chainCd);
1459 * Answers the structure viewer's model number for the given PDB file, or -1 if
1464 * index of the file in the stored array of file names
1467 public int getModelForPdbFile(String fileName, int fileIndex)
1473 * Answers a default structure model specification which is simply the string
1474 * form of the model number. Override if needed to specify submodels.
1479 public String getModelSpec(int model)
1481 return String.valueOf(model);
1485 * Returns the FeatureRenderer for the given alignment view, or null if
1486 * feature display is turned off in the view.
1491 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1493 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1499 return ap.getAlignViewport().isShowSequenceFeatures()
1500 ? ap.getFeatureRenderer()
1504 protected void setStructureCommands(StructureCommandsI cmd)
1506 commandGenerator = cmd;
1510 * Records association of one chain id (formatted as "pdbid:chainCode") with
1511 * the corresponding PDB file name
1516 public void addChainFile(String chainId, String fileName)
1518 chainFile.put(chainId, fileName);
1522 * Returns the PDB filename for the given chain id (formatted as
1523 * "pdbid:chainCode"), or null if not found
1528 protected String getFileForChain(String chainId)
1530 return chainFile.get(chainId);
1534 public void updateColours(Object source)
1536 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1537 // ignore events from panels not used to colour this view
1538 if (!getViewer().isUsedForColourBy(ap))
1542 if (!isLoadingFromArchive())
1544 updateStructureColours(ap);
1548 public StructureCommandsI getCommandGenerator()
1550 return commandGenerator;
1553 protected abstract ViewerType getViewerType();
1556 * Send a structure viewer command asynchronously in a new thread. If the
1557 * progress message is not null, display this message while the command is
1561 * @param progressMsg
1563 protected void sendAsynchronousCommand(StructureCommandI command,
1566 final JalviewStructureDisplayI theViewer = getViewer();
1567 final long handle = progressMsg == null ? 0
1568 : theViewer.startProgressBar(progressMsg);
1569 SwingUtilities.invokeLater(new Runnable()
1576 executeCommand(command, false, null);
1579 if (progressMsg != null)
1581 theViewer.stopProgressBar(null, handle);
1590 * Builds a data structure which records mapped structure residues for each
1591 * colour. From this we can easily generate the viewer commands for colour by
1592 * sequence. Constructs and returns a map of {@code Color} to
1593 * {@code AtomSpecModel}, where the atomspec model holds
1601 * Ordering is by order of addition (for colours), natural ordering (for
1602 * models and chains)
1609 protected Map<Object, AtomSpecModel> buildColoursMap(
1610 StructureSelectionManager ssm, SequenceI[][] sequence,
1611 AlignmentViewPanel viewPanel)
1613 String[] files = getStructureFiles();
1614 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1615 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1616 FeatureColourFinder finder = new FeatureColourFinder(fr);
1617 AlignViewportI viewport = viewPanel.getAlignViewport();
1618 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1619 AlignmentI al = viewport.getAlignment();
1620 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1621 Color lastColour = null;
1623 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1625 final String modelId = getModelIdForFile(files[pdbfnum]);
1626 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1628 if (mapping == null || mapping.length < 1)
1633 int startPos = -1, lastPos = -1;
1634 String lastChain = "";
1635 for (int s = 0; s < sequence[pdbfnum].length; s++)
1637 for (int sp, m = 0; m < mapping.length; m++)
1639 final SequenceI seq = sequence[pdbfnum][s];
1640 if (mapping[m].getSequence() == seq
1641 && (sp = al.findIndex(seq)) > -1)
1643 SequenceI asp = al.getSequenceAt(sp);
1644 for (int r = 0; r < asp.getLength(); r++)
1646 // no mapping to gaps in sequence
1647 if (Comparison.isGap(asp.getCharAt(r)))
1651 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1653 if (pos < 1 || pos == lastPos)
1658 Color colour = sr.getResidueColour(seq, r, finder);
1661 * darker colour for hidden regions
1663 if (!cs.isVisible(r))
1665 colour = Color.GRAY;
1668 final String chain = mapping[m].getChain();
1671 * Just keep incrementing the end position for this colour range
1672 * _unless_ colour, PDB model or chain has changed, or there is a
1673 * gap in the mapped residue sequence
1675 final boolean newColour = !colour.equals(lastColour);
1676 final boolean nonContig = lastPos + 1 != pos;
1677 final boolean newChain = !chain.equals(lastChain);
1678 if (newColour || nonContig || newChain)
1682 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1683 lastPos, lastChain);
1687 lastColour = colour;
1691 // final colour range
1692 if (lastColour != null)
1694 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1695 lastPos, lastChain);
1706 * todo better refactoring (map lookup or similar to get viewer structure id)
1712 protected String getModelId(int pdbfnum, String file)
1714 return String.valueOf(pdbfnum);
1718 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1719 * full PDB file path
1724 public void stashFoundChains(StructureFile pdb, String file)
1726 for (int i = 0; i < pdb.getChains().size(); i++)
1728 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1729 addChainFile(chid, file);
1730 getChainNames().add(chid);
1735 * Helper method to add one contiguous range to the AtomSpec model for the
1736 * given value (creating the model if necessary). As used by Jalview,
1739 * <li>a colour, when building a 'colour structure by sequence' command</li>
1740 * <li>a feature value, when building a 'set Chimera attributes from features'
1751 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1752 Object value, String model, int startPos, int endPos,
1756 * Get/initialize map of data for the colour
1758 AtomSpecModel atomSpec = map.get(value);
1759 if (atomSpec == null)
1761 atomSpec = new AtomSpecModel();
1762 map.put(value, atomSpec);
1765 atomSpec.addRange(model, startPos, endPos, chain);
1769 * Returns the file extension (including '.' separator) to use for a saved
1770 * viewer session file. Default is to return null (not supported), override as
1775 public String getSessionFileExtension()
1781 * If supported, saves the state of the structure viewer to a temporary file
1782 * and returns the file. Returns null and logs an error on any failure.
1786 public File saveSession()
1788 String prefix = getViewerType().toString();
1789 String suffix = getSessionFileExtension();
1793 f = File.createTempFile(prefix, suffix);
1795 } catch (IOException e)
1797 Cache.log.error(String.format("Error saving %s session: %s", prefix,
1805 * Saves the structure viewer session to the given file
1809 protected void saveSession(File f)
1811 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1814 executeCommand(cmd, false);
1819 * Returns true if the viewer is an external structure viewer for which the
1820 * process is still alive, else false (for Jmol, or an external viewer which
1821 * the user has independently closed)
1825 public boolean isViewerRunning()
1831 * Closes Jalview's structure viewer panel and releases associated resources.
1832 * If it is managing an external viewer program, and {@code forceClose} is
1833 * true, also asks that program to close.
1837 public void closeViewer(boolean forceClose)
1839 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1840 releaseUIResources();
1843 * end the thread that closes this panel if the external viewer closes
1845 if (externalViewerMonitor != null)
1847 externalViewerMonitor.interrupt();
1848 externalViewerMonitor = null;
1855 StructureCommandI cmd = getCommandGenerator().closeViewer();
1858 executeCommand(cmd, false);
1864 * Returns the URL of a help page for the structure viewer, or null if none is
1869 public String getHelpURL()
1876 * Helper method to build a map of
1877 * { featureType, { feature value, AtomSpecModel } }
1883 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1884 AlignmentViewPanel viewPanel)
1886 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1887 String[] files = getStructureFiles();
1893 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1899 AlignViewportI viewport = viewPanel.getAlignViewport();
1900 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1903 * if alignment is showing features from complement, we also transfer
1904 * these features to the corresponding mapped structure residues
1906 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1907 List<String> complementFeatures = new ArrayList<>();
1908 FeatureRenderer complementRenderer = null;
1909 if (showLinkedFeatures)
1911 AlignViewportI comp = fr.getViewport().getCodingComplement();
1914 complementRenderer = Desktop.getAlignFrameFor(comp)
1915 .getFeatureRenderer();
1916 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1919 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1924 AlignmentI alignment = viewPanel.getAlignment();
1925 SequenceI[][] seqs = getSequence();
1927 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1929 String modelId = getModelIdForFile(files[pdbfnum]);
1930 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1932 if (mapping == null || mapping.length < 1)
1937 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1939 for (int m = 0; m < mapping.length; m++)
1941 final SequenceI seq = seqs[pdbfnum][seqNo];
1942 int sp = alignment.findIndex(seq);
1943 StructureMapping structureMapping = mapping[m];
1944 if (structureMapping.getSequence() == seq && sp > -1)
1947 * found a sequence with a mapping to a structure;
1948 * now scan its features
1950 if (!visibleFeatures.isEmpty())
1952 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1955 if (showLinkedFeatures)
1957 scanComplementFeatures(complementRenderer, structureMapping,
1958 seq, theMap, modelId);
1968 * Ask the structure viewer to open a session file. Returns true if
1969 * successful, else false (or not supported).
1974 public boolean openSession(String filepath)
1976 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1981 executeCommand(cmd, true);
1982 // todo: test for failure - how?
1987 * Scans visible features in mapped positions of the CDS/peptide complement,
1988 * and adds any found to the map of attribute values/structure positions
1990 * @param complementRenderer
1991 * @param structureMapping
1994 * @param modelNumber
1996 protected static void scanComplementFeatures(
1997 FeatureRenderer complementRenderer,
1998 StructureMapping structureMapping, SequenceI seq,
1999 Map<String, Map<Object, AtomSpecModel>> theMap,
2003 * for each sequence residue mapped to a structure position...
2005 for (int seqPos : structureMapping.getMapping().keySet())
2008 * find visible complementary features at mapped position(s)
2010 MappedFeatures mf = complementRenderer
2011 .findComplementFeaturesAtResidue(seq, seqPos);
2014 for (SequenceFeature sf : mf.features)
2016 String type = sf.getType();
2019 * Don't copy features which originated from Chimera
2021 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
2022 .equals(sf.getFeatureGroup()))
2028 * record feature 'value' (score/description/type) as at the
2029 * corresponding structure position
2031 List<int[]> mappedRanges = structureMapping
2032 .getPDBResNumRanges(seqPos, seqPos);
2034 if (!mappedRanges.isEmpty())
2036 String value = sf.getDescription();
2037 if (value == null || value.length() == 0)
2041 float score = sf.getScore();
2042 if (score != 0f && !Float.isNaN(score))
2044 value = Float.toString(score);
2046 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
2047 if (featureValues == null)
2049 featureValues = new HashMap<>();
2050 theMap.put(type, featureValues);
2052 for (int[] range : mappedRanges)
2054 addAtomSpecRange(featureValues, value, modelNumber, range[0],
2055 range[1], structureMapping.getChain());
2064 * Inspect features on the sequence; for each feature that is visible,
2065 * determine its mapped ranges in the structure (if any) according to the
2066 * given mapping, and add them to the map.
2068 * @param visibleFeatures
2074 protected static void scanSequenceFeatures(List<String> visibleFeatures,
2075 StructureMapping mapping, SequenceI seq,
2076 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
2078 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
2079 visibleFeatures.toArray(new String[visibleFeatures.size()]));
2080 for (SequenceFeature sf : sfs)
2082 String type = sf.getType();
2085 * Don't copy features which originated from Chimera
2087 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
2088 .equals(sf.getFeatureGroup()))
2093 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
2096 if (!mappedRanges.isEmpty())
2098 String value = sf.getDescription();
2099 if (value == null || value.length() == 0)
2103 float score = sf.getScore();
2104 if (score != 0f && !Float.isNaN(score))
2106 value = Float.toString(score);
2108 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
2109 if (featureValues == null)
2111 featureValues = new HashMap<>();
2112 theMap.put(type, featureValues);
2114 for (int[] range : mappedRanges)
2116 addAtomSpecRange(featureValues, value, modelId, range[0],
2117 range[1], mapping.getChain());
2124 * Returns the number of structure files in the structure viewer and mapped to
2125 * Jalview. This may be zero if the files are still in the process of loading
2130 public int getMappedStructureCount()
2132 String[] files = getStructureFiles();
2133 return files == null ? 0 : files.length;
2137 * Starts a thread that waits for the external viewer program process to
2138 * finish, so that we can then close the associated resources. This avoids
2139 * leaving orphaned viewer panels in Jalview if the user closes the external
2144 protected void startExternalViewerMonitor(Process p)
2146 externalViewerMonitor = new Thread(new Runnable()
2155 JalviewStructureDisplayI display = getViewer();
2156 if (display != null)
2158 display.closeViewer(false);
2160 } catch (InterruptedException e)
2162 // exit thread if Chimera Viewer is closed in Jalview
2166 externalViewerMonitor.start();
2170 * If supported by the external structure viewer, sends it commands to notify
2171 * model or selection changes to the specified URL (where Jalview has started
2176 protected void startListening(String uri)
2178 List<StructureCommandI> commands = getCommandGenerator()
2179 .startNotifications(uri);
2180 if (commands != null)
2182 executeCommands(commands, false, null);
2187 * If supported by the external structure viewer, sends it commands to stop
2188 * notifying model or selection changes
2190 protected void stopListening()
2192 List<StructureCommandI> commands = getCommandGenerator()
2193 .stopNotifications();
2194 if (commands != null)
2196 executeCommands(commands, false, null);
2201 * If supported by the structure viewer, queries it for all residue attributes
2202 * with the given attribute name, and creates features on corresponding
2203 * residues of the alignment. Returns the number of features added.
2206 * @param alignmentPanel
2209 public int copyStructureAttributesToFeatures(String attName,
2210 AlignmentPanel alignmentPanel)
2212 StructureCommandI cmd = getCommandGenerator()
2213 .getResidueAttributes(attName);
2218 List<String> residueAttributes = executeCommand(cmd, true);
2220 int featuresAdded = createFeaturesForAttributes(attName,
2222 if (featuresAdded > 0)
2224 alignmentPanel.getFeatureRenderer().featuresAdded();
2226 return featuresAdded;
2230 * Parses {@code residueAttributes} and creates sequence features on any
2231 * mapped alignment residues. Returns the number of features created.
2233 * {@code residueAttributes} is the reply from the structure viewer to a
2234 * command to list any residue attributes for the given attribute name. Syntax
2235 * and parsing of this is viewer-specific.
2238 * @param residueAttributes
2241 protected int createFeaturesForAttributes(String attName,
2242 List<String> residueAttributes)