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;
34 import javax.swing.SwingUtilities;
36 import jalview.api.AlignViewportI;
37 import jalview.api.AlignmentViewPanel;
38 import jalview.api.FeatureRenderer;
39 import jalview.api.SequenceRenderer;
40 import jalview.api.StructureSelectionManagerProvider;
41 import jalview.api.structures.JalviewStructureDisplayI;
42 import jalview.bin.Cache;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.HiddenColumns;
45 import jalview.datamodel.MappedFeatures;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.SequenceFeature;
48 import jalview.datamodel.SequenceI;
49 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
50 import jalview.gui.Desktop;
51 import jalview.gui.StructureViewer.ViewerType;
52 import jalview.io.DataSourceType;
53 import jalview.io.StructureFile;
54 import jalview.renderer.seqfeatures.FeatureColourFinder;
55 import jalview.schemes.ColourSchemeI;
56 import jalview.schemes.ResidueProperties;
57 import jalview.structure.AtomSpec;
58 import jalview.structure.AtomSpecModel;
59 import jalview.structure.StructureCommandI;
60 import jalview.structure.StructureCommandsI;
61 import jalview.structure.StructureListener;
62 import jalview.structure.StructureMapping;
63 import jalview.structure.StructureSelectionManager;
64 import jalview.util.Comparison;
65 import jalview.util.MessageManager;
69 * A base class to hold common function for protein structure model binding.
70 * Initial version created by refactoring JMol and Chimera binding models, but
71 * other structure viewers could in principle be accommodated in future.
76 public abstract class AAStructureBindingModel
77 extends SequenceStructureBindingModel
78 implements StructureListener, StructureSelectionManagerProvider
81 * Data bean class to simplify parameterisation in superposeStructures
83 public static class SuperposeData
85 public String filename;
89 public String chain = "";
94 * The pdb residue number (if any) mapped to columns of the alignment
96 public int[] pdbResNo; // or use SparseIntArray?
98 public String modelId;
104 * width of alignment (number of columns that may potentially
105 * participate in superposition)
107 * structure viewer model number
109 public SuperposeData(int width, String model)
111 pdbResNo = new int[width];
116 private static final int MIN_POS_TO_SUPERPOSE = 4;
118 private static final String COLOURING_STRUCTURES = MessageManager
119 .getString("status.colouring_structures");
122 * the Jalview panel through which the user interacts
123 * with the structure viewer
125 private JalviewStructureDisplayI viewer;
128 * helper that generates command syntax
130 private StructureCommandsI commandGenerator;
132 private StructureSelectionManager ssm;
135 * modelled chains, formatted as "pdbid:chainCode"
137 private List<String> chainNames;
140 * lookup of pdb file name by key "pdbid:chainCode"
142 private Map<String, String> chainFile;
145 * distinct PDB entries (pdb files) associated
148 private PDBEntry[] pdbEntry;
151 * sequences mapped to each pdbentry
153 private SequenceI[][] sequence;
156 * array of target chains for sequences - tied to pdbentry and sequence[]
158 private String[][] chains;
161 * datasource protocol for access to PDBEntrylatest
163 DataSourceType protocol = null;
165 protected boolean colourBySequence = true;
167 private boolean nucleotide;
169 private boolean finishedInit = false;
172 * current set of model filenames loaded in the viewer
174 protected String[] modelFileNames = null;
176 public String fileLoadingError;
184 public AAStructureBindingModel(StructureSelectionManager ssm,
188 this.sequence = seqs;
189 chainNames = new ArrayList<>();
190 chainFile = new HashMap<>();
201 public AAStructureBindingModel(StructureSelectionManager ssm,
202 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
203 DataSourceType protocol)
205 this(ssm, sequenceIs);
206 this.nucleotide = Comparison.isNucleotide(sequenceIs);
207 this.pdbEntry = pdbentry;
208 this.protocol = protocol;
212 private boolean resolveChains()
215 * final count of chain mappings discovered
218 // JBPNote: JAL-2693 - this should be a list of chain mappings per
219 // [pdbentry][sequence]
220 String[][] newchains = new String[pdbEntry.length][];
222 for (PDBEntry pdb : pdbEntry)
224 SequenceI[] seqsForPdb = sequence[pe];
225 if (seqsForPdb != null)
227 newchains[pe] = new String[seqsForPdb.length];
229 for (SequenceI asq : seqsForPdb)
231 String chain = (chains != null && chains[pe] != null)
234 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
235 : asq.getDatasetSequence();
236 if (sq.getAllPDBEntries() != null)
238 for (PDBEntry pdbentry : sq.getAllPDBEntries())
240 if (pdb.getFile() != null && pdbentry.getFile() != null
241 && pdb.getFile().equals(pdbentry.getFile()))
243 String chaincode = pdbentry.getChainCode();
244 if (chaincode != null && chaincode.length() > 0)
253 newchains[pe][se] = chain;
261 return chainmaps > 0;
263 public StructureSelectionManager getSsm()
269 * Returns the i'th PDBEntry (or null)
274 public PDBEntry getPdbEntry(int i)
276 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
280 * Answers true if this binding includes the given PDB id, else false
285 public boolean hasPdbId(String pdbId)
287 if (pdbEntry != null)
289 for (PDBEntry pdb : pdbEntry)
291 if (pdb.getId().equals(pdbId))
301 * Returns the number of modelled PDB file entries.
305 public int getPdbCount()
307 return pdbEntry == null ? 0 : pdbEntry.length;
310 public SequenceI[][] getSequence()
315 public String[][] getChains()
320 public DataSourceType getProtocol()
325 // TODO may remove this if calling methods can be pulled up here
326 protected void setPdbentry(PDBEntry[] pdbentry)
328 this.pdbEntry = pdbentry;
331 protected void setSequence(SequenceI[][] sequence)
333 this.sequence = sequence;
336 protected void setChains(String[][] chains)
338 this.chains = chains;
342 * Construct a title string for the viewer window based on the data Jalview
351 public String getViewerTitle(String viewerName, boolean verbose)
353 if (getSequence() == null || getSequence().length < 1
354 || getPdbCount() < 1 || getSequence()[0].length < 1)
356 return ("Jalview " + viewerName + " Window");
358 // TODO: give a more informative title when multiple structures are
360 StringBuilder title = new StringBuilder(64);
361 final PDBEntry pdbe = getPdbEntry(0);
362 title.append(viewerName + " view for " + getSequence()[0][0].getName()
363 + ":" + pdbe.getId());
367 String method = (String) pdbe.getProperty("method");
370 title.append(" Method: ").append(method);
372 String chain = (String) pdbe.getProperty("chains");
375 title.append(" Chain:").append(chain);
378 return title.toString();
382 * Called by after closeViewer is called, to release any resources and
383 * references so they can be garbage collected. Override if needed.
385 protected void releaseUIResources()
390 public void releaseReferences(Object svl)
394 public boolean isColourBySequence()
396 return colourBySequence;
400 * Called when the binding thinks the UI needs to be refreshed after a
401 * structure viewer state change. This could be because structures were
402 * loaded, or because an error has occurred. Default does nothing, override as
405 public void refreshGUI()
410 * Instruct the Jalview binding to update the pdbentries vector if necessary
411 * prior to matching the jmol view's contents to the list of structure files
412 * Jalview knows about. By default does nothing, override as required.
414 public void refreshPdbEntries()
418 public void setColourBySequence(boolean colourBySequence)
420 this.colourBySequence = colourBySequence;
423 protected void addSequenceAndChain(int pe, SequenceI[] seq,
426 if (pe < 0 || pe >= getPdbCount())
428 throw new Error(MessageManager.formatMessage(
429 "error.implementation_error_no_pdbentry_from_index",
431 { Integer.valueOf(pe).toString() }));
433 final String nullChain = "TheNullChain";
434 List<SequenceI> s = new ArrayList<>();
435 List<String> c = new ArrayList<>();
436 if (getChains() == null)
438 setChains(new String[getPdbCount()][]);
440 if (getSequence()[pe] != null)
442 for (int i = 0; i < getSequence()[pe].length; i++)
444 s.add(getSequence()[pe][i]);
445 if (getChains()[pe] != null)
447 if (i < getChains()[pe].length)
449 c.add(getChains()[pe][i]);
458 if (tchain != null && tchain.length > 0)
465 for (int i = 0; i < seq.length; i++)
467 if (!s.contains(seq[i]))
470 if (tchain != null && i < tchain.length)
472 c.add(tchain[i] == null ? nullChain : tchain[i]);
476 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
477 getSequence()[pe] = tmp;
480 String[] tch = c.toArray(new String[c.size()]);
481 for (int i = 0; i < tch.length; i++)
483 if (tch[i] == nullChain)
488 getChains()[pe] = tch;
492 getChains()[pe] = null;
497 * add structures and any known sequence associations
499 * @returns the pdb entries added to the current set.
501 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
502 SequenceI[][] seq, String[][] chns)
504 List<PDBEntry> v = new ArrayList<>();
505 List<int[]> rtn = new ArrayList<>();
506 for (int i = 0; i < getPdbCount(); i++)
508 v.add(getPdbEntry(i));
510 for (int i = 0; i < pdbe.length; i++)
512 int r = v.indexOf(pdbe[i]);
513 if (r == -1 || r >= getPdbCount())
515 rtn.add(new int[] { v.size(), i });
520 // just make sure the sequence/chain entries are all up to date
521 addSequenceAndChain(r, seq[i], chns[i]);
524 pdbe = v.toArray(new PDBEntry[v.size()]);
528 // expand the tied sequence[] and string[] arrays
529 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
530 String[][] sch = new String[getPdbCount()][];
531 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
532 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
535 pdbe = new PDBEntry[rtn.size()];
536 for (int r = 0; r < pdbe.length; r++)
538 int[] stri = (rtn.get(r));
539 // record the pdb file as a new addition
540 pdbe[r] = getPdbEntry(stri[0]);
541 // and add the new sequence/chain entries
542 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
553 * Add sequences to the pe'th pdbentry's sequence set.
558 public void addSequence(int pe, SequenceI[] seq)
560 addSequenceAndChain(pe, seq, null);
564 * add the given sequences to the mapping scope for the given pdb file handle
567 * - pdbFile identifier
569 * - set of sequences it can be mapped to
571 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
573 for (int pe = 0; pe < getPdbCount(); pe++)
575 if (getPdbEntry(pe).getFile().equals(pdbFile))
577 addSequence(pe, seq);
583 public abstract void highlightAtoms(List<AtomSpec> atoms);
585 protected boolean isNucleotide()
587 return this.nucleotide;
591 * Returns a readable description of all mappings for the wrapped pdbfile to
592 * any mapped sequences
598 public String printMappings()
600 if (pdbEntry == null)
604 StringBuilder sb = new StringBuilder(128);
605 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
607 String pdbfile = getPdbEntry(pdbe).getFile();
608 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
609 sb.append(getSsm().printMappings(pdbfile, seqs));
611 return sb.toString();
615 * Returns the mapped structure position for a given aligned column of a given
616 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
617 * not mapped to structure.
624 protected int getMappedPosition(SequenceI seq, int alignedPos,
625 StructureMapping mapping)
627 if (alignedPos >= seq.getLength())
632 if (Comparison.isGap(seq.getCharAt(alignedPos)))
636 int seqPos = seq.findPosition(alignedPos);
637 int pos = mapping.getPDBResNum(seqPos);
642 * Helper method to identify residues that can participate in a structure
643 * superposition command. For each structure, identify a sequence in the
644 * alignment which is mapped to the structure. Identify non-gapped columns in
645 * the sequence which have a mapping to a residue in the structure. Returns
646 * the index of the first structure that has a mapping to the alignment.
649 * the sequence alignment which is the basis of structure
652 * a BitSet, where bit j is set to indicate that every structure has
653 * a mapped residue present in column j (so the column can
654 * participate in structure alignment)
656 * an array of data beans corresponding to pdb file index
659 protected int findSuperposableResidues(AlignmentI alignment,
660 BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
662 int refStructure = -1;
663 String[] files = getStructureFiles();
668 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
670 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
674 * Find the first mapped sequence (if any) for this PDB entry which is in
677 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
678 for (int s = 0; s < seqCountForPdbFile; s++)
680 for (StructureMapping mapping : mappings)
682 final SequenceI theSequence = getSequence()[pdbfnum][s];
683 if (mapping.getSequence() == theSequence
684 && alignment.findIndex(theSequence) > -1)
686 if (refStructure < 0)
688 refStructure = pdbfnum;
690 for (int r = 0; r < alignment.getWidth(); r++)
696 int pos = getMappedPosition(theSequence, r, mapping);
697 if (pos < 1 || pos == lastPos)
703 structures[pdbfnum].pdbResNo[r] = pos;
705 String chain = mapping.getChain();
706 if (chain != null && chain.trim().length() > 0)
708 structures[pdbfnum].chain = chain;
710 structures[pdbfnum].pdbId = mapping.getPdbId();
711 structures[pdbfnum].isRna = theSequence.getRNA() != null;
714 * move on to next pdb file (ignore sequences for other chains
715 * for the same structure)
717 s = seqCountForPdbFile;
718 break; // fixme break out of two loops here!
727 * Returns true if the structure viewer has loaded all of the files of
728 * interest (identified by the file mapping having been set up), or false if
729 * any are still not loaded after a timeout interval.
733 protected boolean waitForFileLoad(String[] files)
736 * give up after 10 secs plus 1 sec per file
738 long starttime = System.currentTimeMillis();
739 long endTime = 10000 + 1000 * files.length + starttime;
740 String notLoaded = null;
742 boolean waiting = true;
743 while (waiting && System.currentTimeMillis() < endTime)
746 for (String file : files)
755 StructureMapping[] sm = getSsm().getMapping(file);
756 if (sm == null || sm.length == 0)
760 } catch (Throwable x)
770 "Timed out waiting for structure viewer to load file "
778 public boolean isListeningFor(SequenceI seq)
780 if (sequence != null)
782 for (SequenceI[] seqs : sequence)
786 for (SequenceI s : seqs)
788 if (s == seq || (s.getDatasetSequence() != null
789 && s.getDatasetSequence() == seq.getDatasetSequence()))
800 public boolean isFinishedInit()
805 public void setFinishedInit(boolean fi)
807 this.finishedInit = fi;
811 * Returns a list of chains mapped in this viewer, formatted as
816 public List<String> getChainNames()
822 * Returns the Jalview panel hosting the structure viewer (if any)
826 public JalviewStructureDisplayI getViewer()
831 public void setViewer(JalviewStructureDisplayI v)
837 * Constructs and sends a command to align structures against a reference
838 * structure, based on one or more sequence alignments. May optionally return
839 * an error or warning message for the alignment command(s).
842 * an array of one or more alignment views to process
845 public String superposeStructures(List<AlignmentViewPanel> alignWith)
848 String[] files = getStructureFiles();
850 if (!waitForFileLoad(files))
856 for (AlignmentViewPanel view : alignWith)
858 AlignmentI alignment = view.getAlignment();
859 HiddenColumns hiddenCols = alignment.getHiddenColumns();
862 * 'matched' bit i will be set for visible alignment columns i where
863 * all sequences have a residue with a mapping to their PDB structure
865 BitSet matched = new BitSet();
866 final int width = alignment.getWidth();
867 for (int m = 0; m < width; m++)
869 if (hiddenCols == null || hiddenCols.isVisible(m))
875 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
876 for (int f = 0; f < files.length; f++)
878 structures[f] = new AAStructureBindingModel.SuperposeData(width,
879 getModelIdForFile(files[f]));
883 * Calculate the superposable alignment columns ('matched'), and the
884 * corresponding structure residue positions (structures.pdbResNo)
886 int refStructure = findSuperposableResidues(alignment,
887 matched, structures);
890 * require at least 4 positions to be able to execute superposition
892 int nmatched = matched.cardinality();
893 if (nmatched < MIN_POS_TO_SUPERPOSE)
895 String msg = MessageManager.formatMessage("label.insufficient_residues",
897 error += view.getViewName() + ": " + msg + "; ";
902 * get a model of the superposable residues in the reference structure
904 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
908 * Show all as backbone before doing superposition(s)
909 * (residues used for matching will be shown as ribbon)
911 // todo better way to ensure synchronous than setting getReply true!!
912 executeCommands(commandGenerator.showBackbone(), true, null);
915 * superpose each (other) structure to the reference in turn
917 for (int i = 0; i < structures.length; i++)
919 if (i != refStructure)
921 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
922 List<StructureCommandI> commands = commandGenerator
923 .superposeStructures(refAtoms, atomSpec);
924 List<String> replies = executeCommands(commands, true, null);
925 for (String reply : replies)
927 // return this error (Chimera only) to the user
928 if (reply.toLowerCase().contains("unequal numbers of atoms"))
930 error += "; " + reply;
940 private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
943 AtomSpecModel model = new AtomSpecModel();
944 int nextColumnMatch = matched.nextSetBit(0);
945 while (nextColumnMatch != -1)
947 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
948 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
949 superposeData.chain);
950 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
957 * returns the current sequenceRenderer that should be used to colour the
964 public abstract SequenceRenderer getSequenceRenderer(
965 AlignmentViewPanel alignment);
968 * Sends a command to the structure viewer to colour each chain with a
969 * distinct colour (to the extent supported by the viewer)
971 public void colourByChain()
973 colourBySequence = false;
975 // TODO: JAL-628 colour chains distinctly across all visible models
977 executeCommand(commandGenerator.colourByChain(), false,
978 COLOURING_STRUCTURES);
982 * Sends a command to the structure viewer to colour each chain with a
983 * distinct colour (to the extent supported by the viewer)
985 public void colourByCharge()
987 colourBySequence = false;
989 executeCommands(commandGenerator.colourByCharge(), false,
990 COLOURING_STRUCTURES);
994 * Sends a command to the structure to apply a colour scheme (defined in
995 * Jalview but not necessarily applied to the alignment), which defines a
996 * colour per residue letter. More complex schemes (e.g. that depend on
997 * consensus) cannot be used here and are ignored.
1001 public void colourByJalviewColourScheme(ColourSchemeI cs)
1003 colourBySequence = false;
1005 if (cs == null || !cs.isSimple())
1011 * build a map of {Residue3LetterCode, Color}
1013 Map<String, Color> colours = new HashMap<>();
1014 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1016 for (String resName : residues)
1018 char res = resName.length() == 3
1019 ? ResidueProperties.getSingleCharacterCode(resName)
1020 : resName.charAt(0);
1021 Color colour = cs.findColour(res, 0, null, null, 0f);
1022 colours.put(resName, colour);
1026 * pass to the command constructor, and send the command
1028 List<StructureCommandI> cmd = commandGenerator
1029 .colourByResidues(colours);
1030 executeCommands(cmd, false, COLOURING_STRUCTURES);
1033 public void setBackgroundColour(Color col)
1035 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1036 executeCommand(cmd, false, null);
1040 * Sends one command to the structure viewer. If {@code getReply} is true, the
1041 * command is sent synchronously, otherwise in a deferred thread.
1043 * If a progress message is supplied, this is displayed before command
1044 * execution, and removed afterwards.
1051 private List<String> executeCommand(StructureCommandI cmd,
1052 boolean getReply, String msg)
1057 * synchronous (same thread) execution so reply can be returned
1059 final JalviewStructureDisplayI theViewer = getViewer();
1060 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1063 return executeCommand(cmd, getReply);
1068 theViewer.stopProgressBar(null, handle);
1075 * asynchronous (new thread) execution if no reply needed
1077 final JalviewStructureDisplayI theViewer = getViewer();
1078 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1080 SwingUtilities.invokeLater(new Runnable()
1087 executeCommand(cmd, false);
1092 theViewer.stopProgressBar(null, handle);
1102 * Execute one structure viewer command. If {@code getReply} is true, may
1103 * optionally return one or more reply messages, else returns null.
1108 protected abstract List<String> executeCommand(StructureCommandI cmd,
1112 * A helper method that converts list of commands to a vararg array
1118 protected List<String> executeCommands(
1119 List<StructureCommandI> commands,
1120 boolean getReply, String msg)
1122 return executeCommands(getReply, msg,
1123 commands.toArray(new StructureCommandI[commands.size()]));
1127 * Executes one or more structure viewer commands. If a progress message is
1128 * provided, it is shown first, and removed after all commands have been run.
1135 protected List<String> executeCommands(boolean getReply, String msg,
1136 StructureCommandI[] commands)
1138 // todo: tidy this up
1141 * show progress message if specified
1143 final JalviewStructureDisplayI theViewer = getViewer();
1144 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1146 List<String> response = getReply ? new ArrayList<>() : null;
1149 for (StructureCommandI cmd : commands)
1151 List<String> replies = executeCommand(cmd, getReply, null);
1152 if (getReply && replies != null)
1154 response.addAll(replies);
1162 theViewer.stopProgressBar(null, handle);
1168 * Colours any structures associated with sequences in the given alignment as
1169 * coloured in the alignment view, provided colourBySequence is enabled
1171 public void colourBySequence(AlignmentViewPanel alignmentv)
1173 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1177 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1180 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1181 .colourBySequence(colourMap);
1182 executeCommands(colourBySequenceCommands, false, null);
1186 * Centre the display in the structure viewer
1188 public void focusView()
1190 executeCommand(commandGenerator.focusView(), false, null);
1194 * Generates and executes a command to show only specified chains in the
1195 * structure viewer. The list of chains to show should contain entries
1196 * formatted as "pdbid:chaincode".
1200 public void showChains(List<String> toShow)
1202 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1205 * Reformat the pdbid:chainCode values as modelNo:chainCode
1206 * since this is what is needed to construct the viewer command
1207 * todo: find a less messy way to do this
1209 List<String> showThese = new ArrayList<>();
1210 for (String chainId : toShow)
1212 String[] tokens = chainId.split("\\:");
1213 if (tokens.length == 2)
1215 String pdbFile = getFileForChain(chainId);
1216 String model = getModelIdForFile(pdbFile);
1217 showThese.add(model + ":" + tokens[1]);
1220 executeCommands(commandGenerator.showChains(showThese), false, null);
1224 * Answers the structure viewer's model id given a PDB file name. Returns an
1225 * empty string if model id is not found.
1230 protected abstract String getModelIdForFile(String chainId);
1232 public boolean hasFileLoadingError()
1234 return fileLoadingError != null && fileLoadingError.length() > 0;
1238 * Returns the FeatureRenderer for the given alignment view, or null if
1239 * feature display is turned off in the view.
1244 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1246 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1252 return ap.getAlignViewport().isShowSequenceFeatures()
1253 ? ap.getFeatureRenderer()
1257 protected void setStructureCommands(StructureCommandsI cmd)
1259 commandGenerator = cmd;
1263 * Records association of one chain id (formatted as "pdbid:chainCode") with
1264 * the corresponding PDB file name
1269 public void addChainFile(String chainId, String fileName)
1271 chainFile.put(chainId, fileName);
1275 * Returns the PDB filename for the given chain id (formatted as
1276 * "pdbid:chainCode"), or null if not found
1281 protected String getFileForChain(String chainId)
1283 return chainFile.get(chainId);
1287 public void updateColours(Object source)
1289 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1290 // ignore events from panels not used to colour this view
1291 if (!getViewer().isUsedForColourBy(ap))
1295 if (!isLoadingFromArchive())
1297 colourBySequence(ap);
1301 public StructureCommandsI getCommandGenerator()
1303 return commandGenerator;
1306 protected abstract ViewerType getViewerType();
1309 * Send a structure viewer command asynchronously in a new thread. If the
1310 * progress message is not null, display this message while the command is
1314 * @param progressMsg
1316 protected void sendAsynchronousCommand(StructureCommandI command,
1319 final JalviewStructureDisplayI theViewer = getViewer();
1320 final long handle = progressMsg == null ? 0
1321 : theViewer.startProgressBar(progressMsg);
1322 SwingUtilities.invokeLater(new Runnable()
1329 executeCommand(command, false, null);
1332 if (progressMsg != null)
1334 theViewer.stopProgressBar(null, handle);
1343 * Builds a data structure which records mapped structure residues for each
1344 * colour. From this we can easily generate the viewer commands for colour by
1345 * sequence. Constructs and returns a map of {@code Color} to
1346 * {@code AtomSpecModel}, where the atomspec model holds
1354 * Ordering is by order of addition (for colours), natural ordering (for
1355 * models and chains)
1362 protected Map<Object, AtomSpecModel> buildColoursMap(
1363 StructureSelectionManager ssm, SequenceI[][] sequence,
1364 AlignmentViewPanel viewPanel)
1366 String[] files = getStructureFiles();
1367 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1368 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1369 FeatureColourFinder finder = new FeatureColourFinder(fr);
1370 AlignViewportI viewport = viewPanel.getAlignViewport();
1371 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1372 AlignmentI al = viewport.getAlignment();
1373 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1374 Color lastColour = null;
1376 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1378 final String modelId = getModelIdForFile(files[pdbfnum]);
1379 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1381 if (mapping == null || mapping.length < 1)
1386 int startPos = -1, lastPos = -1;
1387 String lastChain = "";
1388 for (int s = 0; s < sequence[pdbfnum].length; s++)
1390 for (int sp, m = 0; m < mapping.length; m++)
1392 final SequenceI seq = sequence[pdbfnum][s];
1393 if (mapping[m].getSequence() == seq
1394 && (sp = al.findIndex(seq)) > -1)
1396 SequenceI asp = al.getSequenceAt(sp);
1397 for (int r = 0; r < asp.getLength(); r++)
1399 // no mapping to gaps in sequence
1400 if (Comparison.isGap(asp.getCharAt(r)))
1404 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1406 if (pos < 1 || pos == lastPos)
1411 Color colour = sr.getResidueColour(seq, r, finder);
1414 * darker colour for hidden regions
1416 if (!cs.isVisible(r))
1418 colour = Color.GRAY;
1421 final String chain = mapping[m].getChain();
1424 * Just keep incrementing the end position for this colour range
1425 * _unless_ colour, PDB model or chain has changed, or there is a
1426 * gap in the mapped residue sequence
1428 final boolean newColour = !colour.equals(lastColour);
1429 final boolean nonContig = lastPos + 1 != pos;
1430 final boolean newChain = !chain.equals(lastChain);
1431 if (newColour || nonContig || newChain)
1435 addAtomSpecRange(colourMap, lastColour, modelId,
1436 startPos, lastPos, lastChain);
1440 lastColour = colour;
1444 // final colour range
1445 if (lastColour != null)
1447 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1448 lastPos, lastChain);
1459 * todo better refactoring (map lookup or similar to get viewer structure id)
1465 protected String getModelId(int pdbfnum, String file)
1467 return String.valueOf(pdbfnum);
1471 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1472 * full PDB file path
1477 public void stashFoundChains(StructureFile pdb, String file)
1479 for (int i = 0; i < pdb.getChains().size(); i++)
1481 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1482 addChainFile(chid, file);
1483 getChainNames().add(chid);
1488 * Helper method to add one contiguous range to the AtomSpec model for the given
1489 * value (creating the model if necessary). As used by Jalview, {@code value} is
1491 * <li>a colour, when building a 'colour structure by sequence' command</li>
1492 * <li>a feature value, when building a 'set Chimera attributes from features'
1503 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1505 String model, int startPos, int endPos, String chain)
1508 * Get/initialize map of data for the colour
1510 AtomSpecModel atomSpec = map.get(value);
1511 if (atomSpec == null)
1513 atomSpec = new AtomSpecModel();
1514 map.put(value, atomSpec);
1517 atomSpec.addRange(model, startPos, endPos, chain);
1521 * Returns the file extension (including '.' separator) to use for a saved
1522 * viewer session file. Default is to return null (not supported), override as
1527 public String getSessionFileExtension()
1533 * If supported, saves the state of the structure viewer to a temporary file
1534 * and returns the file. Returns null and logs an error on any failure.
1538 public File saveSession()
1540 String prefix = getViewerType().toString();
1541 String suffix = getSessionFileExtension();
1545 f = File.createTempFile(prefix, suffix);
1547 } catch (IOException e)
1549 Cache.log.error(String.format("Error saving %s session: %s",
1550 prefix, e.toString()));
1557 * Saves the structure viewer session to the given file
1561 protected void saveSession(File f)
1563 StructureCommandI cmd = commandGenerator
1564 .saveSession(f.getPath());
1567 executeCommand(cmd, false);
1572 * Returns true if the viewer is an external structure viewer for which the
1573 * process is still alive, else false (for Jmol, or an external viewer which
1574 * the user has independently closed)
1578 public boolean isViewerRunning()
1584 * Closes Jalview's structure viewer panel and releases associated resources.
1585 * If it is managing an external viewer program, and {@code forceClose} is
1586 * true, also shuts down that program.
1590 public void closeViewer(boolean forceClose)
1592 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1593 releaseUIResources();
1595 // add external viewer shutdown in overrides
1596 // todo - or can maybe pull up to here
1600 * Returns the URL of a help page for the structure viewer, or null if none is
1605 public String getHelpURL()
1612 * Helper method to build a map of
1613 * { featureType, { feature value, AtomSpecModel } }
1619 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1620 AlignmentViewPanel viewPanel)
1622 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1623 String[] files = getStructureFiles();
1629 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1635 AlignViewportI viewport = viewPanel.getAlignViewport();
1636 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1639 * if alignment is showing features from complement, we also transfer
1640 * these features to the corresponding mapped structure residues
1642 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1643 List<String> complementFeatures = new ArrayList<>();
1644 FeatureRenderer complementRenderer = null;
1645 if (showLinkedFeatures)
1647 AlignViewportI comp = fr.getViewport().getCodingComplement();
1650 complementRenderer = Desktop.getAlignFrameFor(comp)
1651 .getFeatureRenderer();
1652 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1655 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1660 AlignmentI alignment = viewPanel.getAlignment();
1661 SequenceI[][] seqs = getSequence();
1663 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1665 String modelId = getModelIdForFile(files[pdbfnum]);
1666 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1668 if (mapping == null || mapping.length < 1)
1673 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1675 for (int m = 0; m < mapping.length; m++)
1677 final SequenceI seq = seqs[pdbfnum][seqNo];
1678 int sp = alignment.findIndex(seq);
1679 StructureMapping structureMapping = mapping[m];
1680 if (structureMapping.getSequence() == seq && sp > -1)
1683 * found a sequence with a mapping to a structure;
1684 * now scan its features
1686 if (!visibleFeatures.isEmpty())
1688 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1691 if (showLinkedFeatures)
1693 scanComplementFeatures(complementRenderer, structureMapping,
1694 seq, theMap, modelId);
1704 * Ask the structure viewer to open a session file. Returns true if
1705 * successful, else false (or not supported).
1710 public boolean openSession(String filepath)
1712 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1717 executeCommand(cmd, true);
1718 // todo: test for failure - how?
1723 * Scans visible features in mapped positions of the CDS/peptide complement, and
1724 * adds any found to the map of attribute values/structure positions
1726 * @param complementRenderer
1727 * @param structureMapping
1730 * @param modelNumber
1732 protected static void scanComplementFeatures(
1733 FeatureRenderer complementRenderer,
1734 StructureMapping structureMapping, SequenceI seq,
1735 Map<String, Map<Object, AtomSpecModel>> theMap,
1739 * for each sequence residue mapped to a structure position...
1741 for (int seqPos : structureMapping.getMapping().keySet())
1744 * find visible complementary features at mapped position(s)
1746 MappedFeatures mf = complementRenderer
1747 .findComplementFeaturesAtResidue(seq, seqPos);
1750 for (SequenceFeature sf : mf.features)
1752 String type = sf.getType();
1755 * Don't copy features which originated from Chimera
1757 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1758 .equals(sf.getFeatureGroup()))
1764 * record feature 'value' (score/description/type) as at the
1765 * corresponding structure position
1767 List<int[]> mappedRanges = structureMapping
1768 .getPDBResNumRanges(seqPos, seqPos);
1770 if (!mappedRanges.isEmpty())
1772 String value = sf.getDescription();
1773 if (value == null || value.length() == 0)
1777 float score = sf.getScore();
1778 if (score != 0f && !Float.isNaN(score))
1780 value = Float.toString(score);
1782 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1783 if (featureValues == null)
1785 featureValues = new HashMap<>();
1786 theMap.put(type, featureValues);
1788 for (int[] range : mappedRanges)
1790 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1791 range[1], structureMapping.getChain());
1800 * Inspect features on the sequence; for each feature that is visible,
1801 * determine its mapped ranges in the structure (if any) according to the
1802 * given mapping, and add them to the map.
1804 * @param visibleFeatures
1810 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1811 StructureMapping mapping, SequenceI seq,
1812 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1814 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1815 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1816 for (SequenceFeature sf : sfs)
1818 String type = sf.getType();
1821 * Don't copy features which originated from Chimera
1823 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1824 .equals(sf.getFeatureGroup()))
1829 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1832 if (!mappedRanges.isEmpty())
1834 String value = sf.getDescription();
1835 if (value == null || value.length() == 0)
1839 float score = sf.getScore();
1840 if (score != 0f && !Float.isNaN(score))
1842 value = Float.toString(score);
1844 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1845 if (featureValues == null)
1847 featureValues = new HashMap<>();
1848 theMap.put(type, featureValues);
1850 for (int[] range : mappedRanges)
1852 addAtomSpecRange(featureValues, value, modelId, range[0],
1853 range[1], mapping.getChain());
1860 * Returns the number of structure files in the structure viewer and mapped to
1861 * Jalview. This may be zero if the files are still in the process of loading
1866 public int getMappedStructureCount()
1868 String[] files = getStructureFiles();
1869 return files == null ? 0 : files.length;