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.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.StructureListener;
64 import jalview.structure.StructureMapping;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.Comparison;
67 import jalview.util.MessageManager;
71 * A base class to hold common function for protein structure model binding.
72 * Initial version created by refactoring JMol and Chimera binding models, but
73 * other structure viewers could in principle be accommodated in future.
78 public abstract class AAStructureBindingModel
79 extends SequenceStructureBindingModel
80 implements StructureListener, StructureSelectionManagerProvider
83 * Data bean class to simplify parameterisation in superposeStructures
85 public static class SuperposeData
87 public String filename;
91 public String chain = "";
96 * The pdb residue number (if any) mapped to columns of the alignment
98 public int[] pdbResNo; // or use SparseIntArray?
100 public String modelId;
106 * width of alignment (number of columns that may potentially
107 * participate in superposition)
109 * structure viewer model number
111 public SuperposeData(int width, String model)
113 pdbResNo = new int[width];
118 private static final int MIN_POS_TO_SUPERPOSE = 4;
120 private static final String COLOURING_STRUCTURES = MessageManager
121 .getString("status.colouring_structures");
124 * the Jalview panel through which the user interacts
125 * with the structure viewer
127 private JalviewStructureDisplayI viewer;
130 * helper that generates command syntax
132 private StructureCommandsI commandGenerator;
134 private StructureSelectionManager ssm;
137 * modelled chains, formatted as "pdbid:chainCode"
139 private List<String> chainNames;
142 * lookup of pdb file name by key "pdbid:chainCode"
144 private Map<String, String> chainFile;
147 * distinct PDB entries (pdb files) associated
150 private PDBEntry[] pdbEntry;
153 * sequences mapped to each pdbentry
155 private SequenceI[][] sequence;
158 * array of target chains for sequences - tied to pdbentry and sequence[]
160 private String[][] chains;
163 * datasource protocol for access to PDBEntrylatest
165 DataSourceType protocol = null;
167 protected boolean colourBySequence = true;
169 private boolean nucleotide;
171 private boolean finishedInit = false;
174 * current set of model filenames loaded in the Jmol instance
175 * array index 0, 1, 2... corresponds to Jmol model numbers 1, 2, 3...
177 protected String[] modelFileNames = null;
179 public String fileLoadingError;
181 private boolean showAlignmentOnly;
184 * a list of chains "pdbid:chainid" to hide in the viewer
186 // TODO make private once deprecated JalviewJmolBinding.centerViewer removed
187 protected List<String> chainsToHide;
189 private boolean hideHiddenRegions;
197 public AAStructureBindingModel(StructureSelectionManager ssm,
201 this.sequence = seqs;
202 chainsToHide = new ArrayList<>();
203 chainNames = new ArrayList<>();
204 chainFile = new HashMap<>();
215 public AAStructureBindingModel(StructureSelectionManager ssm,
216 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
217 DataSourceType protocol)
219 this(ssm, sequenceIs);
220 this.nucleotide = Comparison.isNucleotide(sequenceIs);
221 this.pdbEntry = pdbentry;
222 this.protocol = protocol;
223 chainsToHide = new ArrayList<>();
228 private boolean resolveChains()
231 * final count of chain mappings discovered
234 // JBPNote: JAL-2693 - this should be a list of chain mappings per
235 // [pdbentry][sequence]
236 String[][] newchains = new String[pdbEntry.length][];
238 for (PDBEntry pdb : pdbEntry)
240 SequenceI[] seqsForPdb = sequence[pe];
241 if (seqsForPdb != null)
243 newchains[pe] = new String[seqsForPdb.length];
245 for (SequenceI asq : seqsForPdb)
247 String chain = (chains != null && chains[pe] != null)
250 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
251 : asq.getDatasetSequence();
252 if (sq.getAllPDBEntries() != null)
254 for (PDBEntry pdbentry : sq.getAllPDBEntries())
256 if (pdb.getFile() != null && pdbentry.getFile() != null
257 && pdb.getFile().equals(pdbentry.getFile()))
259 String chaincode = pdbentry.getChainCode();
260 if (chaincode != null && chaincode.length() > 0)
269 newchains[pe][se] = chain;
277 return chainmaps > 0;
279 public StructureSelectionManager getSsm()
285 * Returns the i'th PDBEntry (or null)
290 public PDBEntry getPdbEntry(int i)
292 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
296 * Answers true if this binding includes the given PDB id, else false
301 public boolean hasPdbId(String pdbId)
303 if (pdbEntry != null)
305 for (PDBEntry pdb : pdbEntry)
307 if (pdb.getId().equals(pdbId))
317 * Returns the number of modelled PDB file entries.
321 public int getPdbCount()
323 return pdbEntry == null ? 0 : pdbEntry.length;
326 public SequenceI[][] getSequence()
331 public String[][] getChains()
336 public DataSourceType getProtocol()
341 // TODO may remove this if calling methods can be pulled up here
342 protected void setPdbentry(PDBEntry[] pdbentry)
344 this.pdbEntry = pdbentry;
347 protected void setSequence(SequenceI[][] sequence)
349 this.sequence = sequence;
352 protected void setChains(String[][] chains)
354 this.chains = chains;
358 * Construct a title string for the viewer window based on the data Jalview
367 public String getViewerTitle(String viewerName, boolean verbose)
369 if (getSequence() == null || getSequence().length < 1
370 || getPdbCount() < 1 || getSequence()[0].length < 1)
372 return ("Jalview " + viewerName + " Window");
374 // TODO: give a more informative title when multiple structures are
376 StringBuilder title = new StringBuilder(64);
377 final PDBEntry pdbe = getPdbEntry(0);
378 title.append(viewerName + " view for " + getSequence()[0][0].getName()
379 + ":" + pdbe.getId());
383 String method = (String) pdbe.getProperty("method");
386 title.append(" Method: ").append(method);
388 String chain = (String) pdbe.getProperty("chains");
391 title.append(" Chain:").append(chain);
394 return title.toString();
398 * Called by after closeViewer is called, to release any resources and
399 * references so they can be garbage collected. Override if needed.
401 protected void releaseUIResources()
406 public void releaseReferences(Object svl)
410 public boolean isColourBySequence()
412 return colourBySequence;
416 * Called when the binding thinks the UI needs to be refreshed after a
417 * structure viewer state change. This could be because structures were
418 * loaded, or because an error has occurred. Default does nothing, override as
421 public void refreshGUI()
423 getViewer().updateTitleAndMenus();
427 * Instruct the Jalview binding to update the pdbentries vector if necessary
428 * prior to matching the viewer's contents to the list of structure files
429 * Jalview knows about. By default does nothing, override as required.
431 public void refreshPdbEntries()
435 public void setColourBySequence(boolean colourBySequence)
437 this.colourBySequence = colourBySequence;
440 protected void addSequenceAndChain(int pe, SequenceI[] seq,
443 if (pe < 0 || pe >= getPdbCount())
445 throw new Error(MessageManager.formatMessage(
446 "error.implementation_error_no_pdbentry_from_index",
448 { Integer.valueOf(pe).toString() }));
450 final String nullChain = "TheNullChain";
451 List<SequenceI> s = new ArrayList<>();
452 List<String> c = new ArrayList<>();
453 if (getChains() == null)
455 setChains(new String[getPdbCount()][]);
457 if (getSequence()[pe] != null)
459 for (int i = 0; i < getSequence()[pe].length; i++)
461 s.add(getSequence()[pe][i]);
462 if (getChains()[pe] != null)
464 if (i < getChains()[pe].length)
466 c.add(getChains()[pe][i]);
475 if (tchain != null && tchain.length > 0)
482 for (int i = 0; i < seq.length; i++)
484 if (!s.contains(seq[i]))
487 if (tchain != null && i < tchain.length)
489 c.add(tchain[i] == null ? nullChain : tchain[i]);
493 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
494 getSequence()[pe] = tmp;
497 String[] tch = c.toArray(new String[c.size()]);
498 for (int i = 0; i < tch.length; i++)
500 if (tch[i] == nullChain)
505 getChains()[pe] = tch;
509 getChains()[pe] = null;
514 * add structures and any known sequence associations
516 * @returns the pdb entries added to the current set.
518 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
519 SequenceI[][] seq, String[][] chns)
521 List<PDBEntry> v = new ArrayList<>();
522 List<int[]> rtn = new ArrayList<>();
523 for (int i = 0; i < getPdbCount(); i++)
525 v.add(getPdbEntry(i));
527 for (int i = 0; i < pdbe.length; i++)
529 int r = v.indexOf(pdbe[i]);
530 if (r == -1 || r >= getPdbCount())
532 rtn.add(new int[] { v.size(), i });
537 // just make sure the sequence/chain entries are all up to date
538 addSequenceAndChain(r, seq[i], chns[i]);
541 pdbe = v.toArray(new PDBEntry[v.size()]);
545 // expand the tied sequence[] and string[] arrays
546 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
547 String[][] sch = new String[getPdbCount()][];
548 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
549 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
552 pdbe = new PDBEntry[rtn.size()];
553 for (int r = 0; r < pdbe.length; r++)
555 int[] stri = (rtn.get(r));
556 // record the pdb file as a new addition
557 pdbe[r] = getPdbEntry(stri[0]);
558 // and add the new sequence/chain entries
559 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
570 * Add sequences to the pe'th pdbentry's sequence set.
575 public void addSequence(int pe, SequenceI[] seq)
577 addSequenceAndChain(pe, seq, null);
581 * add the given sequences to the mapping scope for the given pdb file handle
584 * - pdbFile identifier
586 * - set of sequences it can be mapped to
588 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
590 for (int pe = 0; pe < getPdbCount(); pe++)
592 if (getPdbEntry(pe).getFile().equals(pdbFile))
594 addSequence(pe, seq);
600 public abstract void highlightAtoms(List<AtomSpec> atoms);
602 protected boolean isNucleotide()
604 return this.nucleotide;
608 * Returns a readable description of all mappings for the wrapped pdbfile to
609 * any mapped sequences
615 public String printMappings()
617 if (pdbEntry == null)
621 StringBuilder sb = new StringBuilder(128);
622 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
624 String pdbfile = getPdbEntry(pdbe).getFile();
625 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
626 sb.append(getSsm().printMappings(pdbfile, seqs));
628 return sb.toString();
632 * Returns the mapped structure position for a given aligned column of a given
633 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
634 * not mapped to structure.
641 protected int getMappedPosition(SequenceI seq, int alignedPos,
642 StructureMapping mapping)
644 if (alignedPos >= seq.getLength())
649 if (Comparison.isGap(seq.getCharAt(alignedPos)))
653 int seqPos = seq.findPosition(alignedPos);
654 int pos = mapping.getPDBResNum(seqPos);
659 * Helper method to identify residues that can participate in a structure
660 * superposition command. For each structure, identify a sequence in the
661 * alignment which is mapped to the structure. Identify non-gapped columns in
662 * the sequence which have a mapping to a residue in the structure. Returns
663 * the index of the first structure that has a mapping to the alignment.
666 * the sequence alignment which is the basis of structure
669 * a BitSet, where bit j is set to indicate that every structure has
670 * a mapped residue present in column j (so the column can
671 * participate in structure alignment)
673 * an array of data beans corresponding to pdb file index
676 protected int findSuperposableResidues(AlignmentI alignment,
677 BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
679 int refStructure = -1;
680 String[] files = getStructureFiles();
685 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
687 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
691 * Find the first mapped sequence (if any) for this PDB entry which is in
694 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
695 for (int s = 0; s < seqCountForPdbFile; s++)
697 for (StructureMapping mapping : mappings)
699 final SequenceI theSequence = getSequence()[pdbfnum][s];
700 if (mapping.getSequence() == theSequence
701 && alignment.findIndex(theSequence) > -1)
703 if (refStructure < 0)
705 refStructure = pdbfnum;
707 for (int r = 0; r < alignment.getWidth(); r++)
713 int pos = getMappedPosition(theSequence, r, mapping);
714 if (pos < 1 || pos == lastPos)
720 structures[pdbfnum].pdbResNo[r] = pos;
722 String chain = mapping.getChain();
723 if (chain != null && chain.trim().length() > 0)
725 structures[pdbfnum].chain = chain;
727 structures[pdbfnum].pdbId = mapping.getPdbId();
728 structures[pdbfnum].isRna = theSequence.getRNA() != null;
731 * move on to next pdb file (ignore sequences for other chains
732 * for the same structure)
734 s = seqCountForPdbFile;
735 break; // fixme break out of two loops here!
744 * Returns true if the structure viewer has loaded all of the files of
745 * interest (identified by the file mapping having been set up), or false if
746 * any are still not loaded after a timeout interval.
750 protected boolean waitForFileLoad(String[] files)
753 * give up after 10 secs plus 1 sec per file
755 long starttime = System.currentTimeMillis();
756 long endTime = 10000 + 1000 * files.length + starttime;
757 String notLoaded = null;
759 boolean waiting = true;
760 while (waiting && System.currentTimeMillis() < endTime)
763 for (String file : files)
772 StructureMapping[] sm = getSsm().getMapping(file);
773 if (sm == null || sm.length == 0)
777 } catch (Throwable x)
787 "Timed out waiting for structure viewer to load file "
795 public boolean isListeningFor(SequenceI seq)
797 if (sequence != null)
799 for (SequenceI[] seqs : sequence)
803 for (SequenceI s : seqs)
805 if (s == seq || (s.getDatasetSequence() != null
806 && s.getDatasetSequence() == seq.getDatasetSequence()))
817 public boolean isFinishedInit()
822 public void setFinishedInit(boolean fi)
824 this.finishedInit = fi;
828 * Returns a list of chains mapped in this viewer, formatted as
833 public List<String> getChainNames()
839 * Returns the Jalview panel hosting the structure viewer (if any)
843 public JalviewStructureDisplayI getViewer()
848 public void setViewer(JalviewStructureDisplayI v)
854 * Constructs and sends a command to align structures against a reference
855 * structure, based on one or more sequence alignments. May optionally return
856 * an error or warning message for the alignment command(s).
859 * an array of one or more alignment views to process
862 public String superposeStructures(List<AlignmentViewPanel> alignWith)
865 String[] files = getStructureFiles();
867 if (!waitForFileLoad(files))
873 for (AlignmentViewPanel view : alignWith)
875 AlignmentI alignment = view.getAlignment();
876 HiddenColumns hiddenCols = alignment.getHiddenColumns();
879 * 'matched' bit i will be set for visible alignment columns i where
880 * all sequences have a residue with a mapping to their PDB structure
882 BitSet matched = new BitSet();
883 final int width = alignment.getWidth();
884 for (int m = 0; m < width; m++)
886 if (hiddenCols == null || hiddenCols.isVisible(m))
892 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
893 for (int f = 0; f < files.length; f++)
895 structures[f] = new AAStructureBindingModel.SuperposeData(width,
896 getModelIdForFile(files[f]));
900 * Calculate the superposable alignment columns ('matched'), and the
901 * corresponding structure residue positions (structures.pdbResNo)
903 int refStructure = findSuperposableResidues(alignment,
904 matched, structures);
907 * require at least 4 positions to be able to execute superposition
909 int nmatched = matched.cardinality();
910 if (nmatched < MIN_POS_TO_SUPERPOSE)
912 String msg = MessageManager.formatMessage("label.insufficient_residues",
914 error += view.getViewName() + ": " + msg + "; ";
919 * get a model of the superposable residues in the reference structure
921 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
925 * Show all as backbone before doing superposition(s)
926 * (residues used for matching will be shown as ribbon)
928 // todo better way to ensure synchronous than setting getReply true!!
929 executeCommands(commandGenerator.showBackbone(), true, null);
932 * superpose each (other) structure to the reference in turn
934 for (int i = 0; i < structures.length; i++)
936 if (i != refStructure)
938 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
939 List<StructureCommandI> commands = commandGenerator
940 .superposeStructures(refAtoms, atomSpec);
941 List<String> replies = executeCommands(commands, true, null);
942 for (String reply : replies)
944 // return this error (Chimera only) to the user
945 if (reply.toLowerCase().contains("unequal numbers of atoms"))
947 error += "; " + reply;
957 private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
960 AtomSpecModel model = new AtomSpecModel();
961 int nextColumnMatch = matched.nextSetBit(0);
962 while (nextColumnMatch != -1)
964 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
965 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
966 superposeData.chain);
967 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
974 * returns the current sequenceRenderer that should be used to colour the
981 public abstract SequenceRenderer getSequenceRenderer(
982 AlignmentViewPanel alignment);
985 * Recolours mapped residues in the structure viewer to match colours in the
986 * given alignment panel, provided colourBySequence is selected. Colours
987 * should also be applied to any hidden mapped residues (so that they are
988 * shown correctly if these get unhidden).
992 protected void colourBySequence(AlignmentViewPanel viewPanel)
995 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
999 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1002 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1003 .colourBySequence(colourMap);
1004 executeCommands(colourBySequenceCommands, false, null);
1009 * Sends a command to the structure viewer to colour each chain with a
1010 * distinct colour (to the extent supported by the viewer)
1012 public void colourByChain()
1014 colourBySequence = false;
1015 // TODO: JAL-628 colour chains distinctly across all visible models
1016 executeCommand(commandGenerator.colourByChain(), false,
1017 COLOURING_STRUCTURES);
1021 * Sends a command to the structure viewer to colour each chain with a
1022 * distinct colour (to the extent supported by the viewer)
1024 public void colourByCharge()
1026 colourBySequence = false;
1028 executeCommands(commandGenerator.colourByCharge(), false,
1029 COLOURING_STRUCTURES);
1033 * Sends a command to the structure to apply a colour scheme (defined in
1034 * Jalview but not necessarily applied to the alignment), which defines a
1035 * colour per residue letter. More complex schemes (e.g. that depend on
1036 * consensus) cannot be used here and are ignored.
1040 public void colourByJalviewColourScheme(ColourSchemeI cs)
1042 colourBySequence = false;
1044 if (cs == null || !cs.isSimple())
1050 * build a map of {Residue3LetterCode, Color}
1052 Map<String, Color> colours = new HashMap<>();
1053 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1055 for (String resName : residues)
1057 char res = resName.length() == 3
1058 ? ResidueProperties.getSingleCharacterCode(resName)
1059 : resName.charAt(0);
1060 Color colour = cs.findColour(res, 0, null, null, 0f);
1061 colours.put(resName, colour);
1065 * pass to the command constructor, and send the command
1067 List<StructureCommandI> cmd = commandGenerator
1068 .colourByResidues(colours);
1069 executeCommands(cmd, false, COLOURING_STRUCTURES);
1072 public void setBackgroundColour(Color col)
1074 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1075 executeCommand(cmd, false, null);
1079 * Sends one command to the structure viewer. If {@code getReply} is true, the
1080 * command is sent synchronously, otherwise in a deferred thread.
1082 * If a progress message is supplied, this is displayed before command
1083 * execution, and removed afterwards.
1090 private List<String> executeCommand(StructureCommandI cmd,
1091 boolean getReply, String msg)
1095 return null; // catch unimplemented commands
1100 * synchronous (same thread) execution so reply can be returned
1102 final JalviewStructureDisplayI theViewer = getViewer();
1103 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1106 return executeCommand(cmd, getReply);
1111 theViewer.stopProgressBar(null, handle);
1118 * asynchronous (new thread) execution if no reply needed
1120 final JalviewStructureDisplayI theViewer = getViewer();
1121 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1123 SwingUtilities.invokeLater(new Runnable()
1130 executeCommand(cmd, false);
1135 theViewer.stopProgressBar(null, handle);
1145 * Execute one structure viewer command. If {@code getReply} is true, may
1146 * optionally return one or more reply messages, else returns null.
1151 protected abstract List<String> executeCommand(StructureCommandI cmd,
1155 * A helper method that converts list of commands to a vararg array
1161 protected List<String> executeCommands(
1162 List<StructureCommandI> commands,
1163 boolean getReply, String msg)
1165 return executeCommands(getReply, msg,
1166 commands.toArray(new StructureCommandI[commands.size()]));
1170 * Executes one or more structure viewer commands. If a progress message is
1171 * provided, it is shown first, and removed after all commands have been run.
1178 protected List<String> executeCommands(boolean getReply, String msg,
1179 StructureCommandI[] commands)
1181 // todo: tidy this up
1184 * show progress message if specified
1186 final JalviewStructureDisplayI theViewer = getViewer();
1187 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1189 List<String> response = getReply ? new ArrayList<>() : null;
1192 for (StructureCommandI cmd : commands)
1194 List<String> replies = executeCommand(cmd, getReply, null);
1195 if (getReply && replies != null)
1197 response.addAll(replies);
1205 theViewer.stopProgressBar(null, handle);
1211 * Recolours the displayed structures, if they are coloured by
1212 * sequence, or 'show only visible alignment' is selected. This supports
1213 * updating structure colours on either change of alignment colours, or change
1214 * to the visible region of the alignment.
1216 public void updateStructureColours(AlignmentViewPanel alignmentv)
1218 if (!isLoadingFinished())
1224 * if structure is not coloured by sequence, but restricted to the alignment,
1225 * then redraw it (but don't recolour it) in case hidden regions have changed
1226 * (todo: specific messaging for change of hidden region only)
1228 if (!colourBySequence)
1230 if (isShowAlignmentOnly())
1232 showStructures(alignmentv.getAlignViewport(), false);
1236 if (getSsm() == null)
1240 colourBySequence(alignmentv);
1244 * Centre the display in the structure viewer
1246 public void focusView()
1248 executeCommand(commandGenerator.focusView(), false, null);
1252 * Answers the structure viewer's model id given a PDB file name. Returns an
1253 * empty string if model id is not found.
1258 protected abstract String getModelIdForFile(String chainId);
1260 public boolean hasFileLoadingError()
1262 return fileLoadingError != null && fileLoadingError.length() > 0;
1266 * Sets the flag for whether only mapped visible residues in the alignment
1267 * should be visible in the structure viewer
1271 public void setShowAlignmentOnly(boolean b)
1273 showAlignmentOnly = b;
1277 * Answers true if only residues mapped to the alignment should be shown in the
1278 * structure viewer, else false
1282 public boolean isShowAlignmentOnly()
1284 return showAlignmentOnly;
1288 * Sets the flag for hiding regions of structure which are hidden in the
1289 * alignment (only applies when the structure viewer is restricted to the
1294 public void setHideHiddenRegions(boolean b)
1296 hideHiddenRegions = b;
1300 * Answers true if regions hidden in the alignment should also be hidden in the
1301 * structure viewer, else false (only applies when the structure viewer is
1302 * restricted to the alignment only)
1306 public boolean isHideHiddenRegions()
1308 return hideHiddenRegions;
1312 * Shows the structures in the viewer, without changing their colouring. This
1313 * is to support toggling of whether the whole structure is shown, or only
1314 * residues mapped to visible regions of the alignment, and/or only selected
1319 * if true, rescale the display to the viewer
1321 public void showStructures(AlignViewportI av, boolean refocus)
1323 if (isShowAlignmentOnly())
1325 StructureCommandI cmd = getCommandGenerator().hideAll();
1326 executeCommand(cmd, false);
1329 AtomSpecModel model = isShowAlignmentOnly() ? getShownResidues(av)
1331 StructureCommandI cmd = getCommandGenerator().showStructures(model);
1332 executeCommand(cmd, false);
1335 * and hide any chains selected _not_ to be shown
1336 * (whether mapped to sequence in the alignment or not)
1338 for (String pdbChain : chainsToHide)
1340 String modelNo = getModelIdForFile(getFileForChain(pdbChain));
1341 if (!"".equals(modelNo))
1343 String chainId = pdbChain.split(":")[1];
1344 cmd = getCommandGenerator().hideChain(modelNo, chainId);
1345 executeCommand(cmd, false);
1356 * Sets the list of chains to hide (as "pdbid:chain")
1360 public void setChainsToHide(List<String> chains)
1362 chainsToHide = chains;
1366 * Answers true if the specified structure and chain are selected to be shown in
1367 * the viewer, else false
1373 public boolean isShowChain(String pdbId, String chainId)
1375 if (chainsToHide.isEmpty())
1379 return !chainsToHide.contains(pdbId + ":" + chainId);
1383 public abstract String[] getStructureFiles();
1386 * Builds a model of residues mapped from sequences to show on structure,
1387 * taking into account user choices of
1389 * <li>whether hidden regions of the alignment are excluded (hidden) or
1390 * included (greyed out)</li>
1391 * <li>which chains are shown</li>
1397 protected AtomSpecModel getShownResidues(AlignViewportI av)
1399 if (!isShowAlignmentOnly())
1402 "getShownResidues only valid for 'show alignment only')");
1406 AlignmentI alignment = av.getAlignment();
1407 final int width = alignment.getWidth();
1409 String[] files = getStructureFiles();
1411 AtomSpecModel model = new AtomSpecModel();
1413 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1415 String fileName = files[pdbfnum];
1416 final String modelId = getModelIdForFile(files[pdbfnum]);
1417 StructureMapping[] mappings = getSsm().getMapping(fileName);
1420 * Find the first mapped sequence (if any) for this PDB entry which is in
1423 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
1424 for (int s = 0; s < seqCountForPdbFile; s++)
1426 for (StructureMapping mapping : mappings)
1428 final SequenceI theSequence = getSequence()[pdbfnum][s];
1429 if (mapping.getSequence() == theSequence
1430 && alignment.findIndex(theSequence) > -1)
1432 String chainCd = mapping.getChain();
1433 if (!isShowChain(mapping.getPdbId(), chainCd))
1436 * chain is not selected to be displayed, so don't
1437 * waste effort computing its structure positions
1441 Iterator<int[]> visible;
1442 if (isHideHiddenRegions())
1445 * traverse visible columns of the alignment only
1447 visible = alignment.getHiddenColumns()
1448 .getVisContigsIterator(0, width, true);
1453 * traverse all columns (including hidden if any)
1455 visible = Collections.singletonList(new int[] { 0, width })
1458 while (visible.hasNext())
1460 int[] visibleRegion = visible.next();
1461 int seqStartPos = theSequence.findPosition(visibleRegion[0]);
1462 int seqEndPos = theSequence.findPosition(visibleRegion[1]);
1463 List<int[]> residueRanges = mapping
1464 .getPDBResNumRanges(seqStartPos, seqEndPos);
1465 if (!residueRanges.isEmpty())
1467 for (int[] range : residueRanges)
1469 model.addRange(modelId, range[0], range[1], chainCd);
1482 * Answers the structure viewer's model number for the given PDB file, or -1 if
1487 * index of the file in the stored array of file names
1490 public int getModelForPdbFile(String fileName, int fileIndex)
1496 * Answers a default structure model specification which is simply the string
1497 * form of the model number. Override if needed to specify submodels.
1502 public String getModelSpec(int model)
1504 return String.valueOf(model);
1508 * Returns the FeatureRenderer for the given alignment view, or null if
1509 * feature display is turned off in the view.
1514 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1516 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1522 return ap.getAlignViewport().isShowSequenceFeatures()
1523 ? ap.getFeatureRenderer()
1527 protected void setStructureCommands(StructureCommandsI cmd)
1529 commandGenerator = cmd;
1533 * Records association of one chain id (formatted as "pdbid:chainCode") with
1534 * the corresponding PDB file name
1539 public void addChainFile(String chainId, String fileName)
1541 chainFile.put(chainId, fileName);
1545 * Returns the PDB filename for the given chain id (formatted as
1546 * "pdbid:chainCode"), or null if not found
1551 protected String getFileForChain(String chainId)
1553 return chainFile.get(chainId);
1557 public void updateColours(Object source)
1559 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1560 // ignore events from panels not used to colour this view
1561 if (!getViewer().isUsedForColourBy(ap))
1565 if (!isLoadingFromArchive())
1567 updateStructureColours(ap);
1571 public StructureCommandsI getCommandGenerator()
1573 return commandGenerator;
1576 protected abstract ViewerType getViewerType();
1579 * Send a structure viewer command asynchronously in a new thread. If the
1580 * progress message is not null, display this message while the command is
1584 * @param progressMsg
1586 protected void sendAsynchronousCommand(StructureCommandI command,
1589 final JalviewStructureDisplayI theViewer = getViewer();
1590 final long handle = progressMsg == null ? 0
1591 : theViewer.startProgressBar(progressMsg);
1592 SwingUtilities.invokeLater(new Runnable()
1599 executeCommand(command, false, null);
1602 if (progressMsg != null)
1604 theViewer.stopProgressBar(null, handle);
1613 * Builds a data structure which records mapped structure residues for each
1614 * colour. From this we can easily generate the viewer commands for colour by
1615 * sequence. Constructs and returns a map of {@code Color} to
1616 * {@code AtomSpecModel}, where the atomspec model holds
1624 * Ordering is by order of addition (for colours), natural ordering (for
1625 * models and chains)
1632 protected Map<Object, AtomSpecModel> buildColoursMap(
1633 StructureSelectionManager ssm, SequenceI[][] sequence,
1634 AlignmentViewPanel viewPanel)
1636 String[] files = getStructureFiles();
1637 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1638 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1639 FeatureColourFinder finder = new FeatureColourFinder(fr);
1640 AlignViewportI viewport = viewPanel.getAlignViewport();
1641 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1642 AlignmentI al = viewport.getAlignment();
1643 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1644 Color lastColour = null;
1646 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1648 final String modelId = getModelIdForFile(files[pdbfnum]);
1649 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1651 if (mapping == null || mapping.length < 1)
1656 int startPos = -1, lastPos = -1;
1657 String lastChain = "";
1658 for (int s = 0; s < sequence[pdbfnum].length; s++)
1660 for (int sp, m = 0; m < mapping.length; m++)
1662 final SequenceI seq = sequence[pdbfnum][s];
1663 if (mapping[m].getSequence() == seq
1664 && (sp = al.findIndex(seq)) > -1)
1666 SequenceI asp = al.getSequenceAt(sp);
1667 for (int r = 0; r < asp.getLength(); r++)
1669 // no mapping to gaps in sequence
1670 if (Comparison.isGap(asp.getCharAt(r)))
1674 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1676 if (pos < 1 || pos == lastPos)
1681 Color colour = sr.getResidueColour(seq, r, finder);
1684 * darker colour for hidden regions
1686 if (!cs.isVisible(r))
1688 colour = Color.GRAY;
1691 final String chain = mapping[m].getChain();
1694 * Just keep incrementing the end position for this colour range
1695 * _unless_ colour, PDB model or chain has changed, or there is a
1696 * gap in the mapped residue sequence
1698 final boolean newColour = !colour.equals(lastColour);
1699 final boolean nonContig = lastPos + 1 != pos;
1700 final boolean newChain = !chain.equals(lastChain);
1701 if (newColour || nonContig || newChain)
1705 addAtomSpecRange(colourMap, lastColour, modelId,
1706 startPos, lastPos, lastChain);
1710 lastColour = colour;
1714 // final colour range
1715 if (lastColour != null)
1717 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1718 lastPos, lastChain);
1729 * todo better refactoring (map lookup or similar to get viewer structure id)
1735 protected String getModelId(int pdbfnum, String file)
1737 return String.valueOf(pdbfnum);
1741 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1742 * full PDB file path
1747 public void stashFoundChains(StructureFile pdb, String file)
1749 for (int i = 0; i < pdb.getChains().size(); i++)
1751 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1752 addChainFile(chid, file);
1753 getChainNames().add(chid);
1758 * Helper method to add one contiguous range to the AtomSpec model for the given
1759 * value (creating the model if necessary). As used by Jalview, {@code value} is
1761 * <li>a colour, when building a 'colour structure by sequence' command</li>
1762 * <li>a feature value, when building a 'set Chimera attributes from features'
1773 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1775 String model, int startPos, int endPos, String chain)
1778 * Get/initialize map of data for the colour
1780 AtomSpecModel atomSpec = map.get(value);
1781 if (atomSpec == null)
1783 atomSpec = new AtomSpecModel();
1784 map.put(value, atomSpec);
1787 atomSpec.addRange(model, startPos, endPos, chain);
1791 * Returns the file extension (including '.' separator) to use for a saved
1792 * viewer session file. Default is to return null (not supported), override as
1797 public String getSessionFileExtension()
1803 * If supported, saves the state of the structure viewer to a temporary file
1804 * and returns the file. Returns null and logs an error on any failure.
1808 public File saveSession()
1810 String prefix = getViewerType().toString();
1811 String suffix = getSessionFileExtension();
1815 f = File.createTempFile(prefix, suffix);
1817 } catch (IOException e)
1819 Cache.log.error(String.format("Error saving %s session: %s",
1820 prefix, e.toString()));
1827 * Saves the structure viewer session to the given file
1831 protected void saveSession(File f)
1833 StructureCommandI cmd = commandGenerator
1834 .saveSession(f.getPath());
1837 executeCommand(cmd, false);
1842 * Returns true if the viewer is an external structure viewer for which the
1843 * process is still alive, else false (for Jmol, or an external viewer which
1844 * the user has independently closed)
1848 public boolean isViewerRunning()
1854 * Closes Jalview's structure viewer panel and releases associated resources.
1855 * If it is managing an external viewer program, and {@code forceClose} is
1856 * true, also shuts down that program.
1860 public void closeViewer(boolean forceClose)
1862 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1863 releaseUIResources();
1865 // add external viewer shutdown in overrides
1866 // todo - or can maybe pull up to here
1870 * Returns the URL of a help page for the structure viewer, or null if none is
1875 public String getHelpURL()
1882 * Helper method to build a map of
1883 * { featureType, { feature value, AtomSpecModel } }
1889 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1890 AlignmentViewPanel viewPanel)
1892 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1893 String[] files = getStructureFiles();
1899 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1905 AlignViewportI viewport = viewPanel.getAlignViewport();
1906 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1909 * if alignment is showing features from complement, we also transfer
1910 * these features to the corresponding mapped structure residues
1912 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1913 List<String> complementFeatures = new ArrayList<>();
1914 FeatureRenderer complementRenderer = null;
1915 if (showLinkedFeatures)
1917 AlignViewportI comp = fr.getViewport().getCodingComplement();
1920 complementRenderer = Desktop.getAlignFrameFor(comp)
1921 .getFeatureRenderer();
1922 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1925 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1930 AlignmentI alignment = viewPanel.getAlignment();
1931 SequenceI[][] seqs = getSequence();
1933 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1935 String modelId = getModelIdForFile(files[pdbfnum]);
1936 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1938 if (mapping == null || mapping.length < 1)
1943 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1945 for (int m = 0; m < mapping.length; m++)
1947 final SequenceI seq = seqs[pdbfnum][seqNo];
1948 int sp = alignment.findIndex(seq);
1949 StructureMapping structureMapping = mapping[m];
1950 if (structureMapping.getSequence() == seq && sp > -1)
1953 * found a sequence with a mapping to a structure;
1954 * now scan its features
1956 if (!visibleFeatures.isEmpty())
1958 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1961 if (showLinkedFeatures)
1963 scanComplementFeatures(complementRenderer, structureMapping,
1964 seq, theMap, modelId);
1974 * Ask the structure viewer to open a session file. Returns true if
1975 * successful, else false (or not supported).
1980 public boolean openSession(String filepath)
1982 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1987 executeCommand(cmd, true);
1988 // todo: test for failure - how?
1993 * Scans visible features in mapped positions of the CDS/peptide complement, and
1994 * adds any found to the map of attribute values/structure positions
1996 * @param complementRenderer
1997 * @param structureMapping
2000 * @param modelNumber
2002 protected static void scanComplementFeatures(
2003 FeatureRenderer complementRenderer,
2004 StructureMapping structureMapping, SequenceI seq,
2005 Map<String, Map<Object, AtomSpecModel>> theMap,
2009 * for each sequence residue mapped to a structure position...
2011 for (int seqPos : structureMapping.getMapping().keySet())
2014 * find visible complementary features at mapped position(s)
2016 MappedFeatures mf = complementRenderer
2017 .findComplementFeaturesAtResidue(seq, seqPos);
2020 for (SequenceFeature sf : mf.features)
2022 String type = sf.getType();
2025 * Don't copy features which originated from Chimera
2027 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
2028 .equals(sf.getFeatureGroup()))
2034 * record feature 'value' (score/description/type) as at the
2035 * corresponding structure position
2037 List<int[]> mappedRanges = structureMapping
2038 .getPDBResNumRanges(seqPos, seqPos);
2040 if (!mappedRanges.isEmpty())
2042 String value = sf.getDescription();
2043 if (value == null || value.length() == 0)
2047 float score = sf.getScore();
2048 if (score != 0f && !Float.isNaN(score))
2050 value = Float.toString(score);
2052 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
2053 if (featureValues == null)
2055 featureValues = new HashMap<>();
2056 theMap.put(type, featureValues);
2058 for (int[] range : mappedRanges)
2060 addAtomSpecRange(featureValues, value, modelNumber, range[0],
2061 range[1], structureMapping.getChain());
2070 * Inspect features on the sequence; for each feature that is visible,
2071 * determine its mapped ranges in the structure (if any) according to the
2072 * given mapping, and add them to the map.
2074 * @param visibleFeatures
2080 protected static void scanSequenceFeatures(List<String> visibleFeatures,
2081 StructureMapping mapping, SequenceI seq,
2082 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
2084 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
2085 visibleFeatures.toArray(new String[visibleFeatures.size()]));
2086 for (SequenceFeature sf : sfs)
2088 String type = sf.getType();
2091 * Don't copy features which originated from Chimera
2093 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
2094 .equals(sf.getFeatureGroup()))
2099 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
2102 if (!mappedRanges.isEmpty())
2104 String value = sf.getDescription();
2105 if (value == null || value.length() == 0)
2109 float score = sf.getScore();
2110 if (score != 0f && !Float.isNaN(score))
2112 value = Float.toString(score);
2114 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
2115 if (featureValues == null)
2117 featureValues = new HashMap<>();
2118 theMap.put(type, featureValues);
2120 for (int[] range : mappedRanges)
2122 addAtomSpecRange(featureValues, value, modelId, range[0],
2123 range[1], mapping.getChain());
2130 * Returns the number of structure files in the structure viewer and mapped to
2131 * Jalview. This may be zero if the files are still in the process of loading
2136 public int getMappedStructureCount()
2138 String[] files = getStructureFiles();
2139 return files == null ? 0 : files.length;