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.AlignmentPanel;
51 import jalview.gui.Desktop;
52 import jalview.gui.StructureViewer.ViewerType;
53 import jalview.io.DataSourceType;
54 import jalview.io.StructureFile;
55 import jalview.renderer.seqfeatures.FeatureColourFinder;
56 import jalview.schemes.ColourSchemeI;
57 import jalview.schemes.ResidueProperties;
58 import jalview.structure.AtomSpec;
59 import jalview.structure.AtomSpecModel;
60 import jalview.structure.StructureCommand;
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 viewer
176 protected String[] modelFileNames = null;
178 public String fileLoadingError;
180 protected Thread externalViewerMonitor;
188 public AAStructureBindingModel(StructureSelectionManager ssm,
192 this.sequence = seqs;
193 chainNames = new ArrayList<>();
194 chainFile = new HashMap<>();
205 public AAStructureBindingModel(StructureSelectionManager ssm,
206 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
207 DataSourceType protocol)
209 this(ssm, sequenceIs);
210 this.nucleotide = Comparison.isNucleotide(sequenceIs);
211 this.pdbEntry = pdbentry;
212 this.protocol = protocol;
216 private boolean resolveChains()
219 * final count of chain mappings discovered
222 // JBPNote: JAL-2693 - this should be a list of chain mappings per
223 // [pdbentry][sequence]
224 String[][] newchains = new String[pdbEntry.length][];
226 for (PDBEntry pdb : pdbEntry)
228 SequenceI[] seqsForPdb = sequence[pe];
229 if (seqsForPdb != null)
231 newchains[pe] = new String[seqsForPdb.length];
233 for (SequenceI asq : seqsForPdb)
235 String chain = (chains != null && chains[pe] != null)
238 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
239 : asq.getDatasetSequence();
240 if (sq.getAllPDBEntries() != null)
242 for (PDBEntry pdbentry : sq.getAllPDBEntries())
244 if (pdb.getFile() != null && pdbentry.getFile() != null
245 && pdb.getFile().equals(pdbentry.getFile()))
247 String chaincode = pdbentry.getChainCode();
248 if (chaincode != null && chaincode.length() > 0)
257 newchains[pe][se] = chain;
265 return chainmaps > 0;
268 public StructureSelectionManager getSsm()
274 * Returns the i'th PDBEntry (or null)
279 public PDBEntry getPdbEntry(int i)
281 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
285 * Answers true if this binding includes the given PDB id, else false
290 public boolean hasPdbId(String pdbId)
292 if (pdbEntry != null)
294 for (PDBEntry pdb : pdbEntry)
296 if (pdb.getId().equals(pdbId))
306 * Returns the number of modelled PDB file entries.
310 public int getPdbCount()
312 return pdbEntry == null ? 0 : pdbEntry.length;
315 public SequenceI[][] getSequence()
320 public String[][] getChains()
325 public DataSourceType getProtocol()
330 // TODO may remove this if calling methods can be pulled up here
331 protected void setPdbentry(PDBEntry[] pdbentry)
333 this.pdbEntry = pdbentry;
336 protected void setSequence(SequenceI[][] sequence)
338 this.sequence = sequence;
341 protected void setChains(String[][] chains)
343 this.chains = chains;
347 * Construct a title string for the viewer window based on the data Jalview
356 public String getViewerTitle(String viewerName, boolean verbose)
358 if (getSequence() == null || getSequence().length < 1
359 || getPdbCount() < 1 || getSequence()[0].length < 1)
361 return ("Jalview " + viewerName + " Window");
363 // TODO: give a more informative title when multiple structures are
365 StringBuilder title = new StringBuilder(64);
366 final PDBEntry pdbe = getPdbEntry(0);
367 title.append(viewerName + " view for " + getSequence()[0][0].getName()
368 + ":" + pdbe.getId());
372 String method = (String) pdbe.getProperty("method");
375 title.append(" Method: ").append(method);
377 String chain = (String) pdbe.getProperty("chains");
380 title.append(" Chain:").append(chain);
383 return title.toString();
387 * Called by after closeViewer is called, to release any resources and
388 * references so they can be garbage collected. Override if needed.
390 protected void releaseUIResources()
395 public void releaseReferences(Object svl)
399 public boolean isColourBySequence()
401 return colourBySequence;
405 * Called when the binding thinks the UI needs to be refreshed after a
406 * structure viewer state change. This could be because structures were
407 * loaded, or because an error has occurred. Default does nothing, override as
410 public void refreshGUI()
415 * Instruct the Jalview binding to update the pdbentries vector if necessary
416 * prior to matching the jmol view's contents to the list of structure files
417 * Jalview knows about. By default does nothing, override as required.
419 public void refreshPdbEntries()
423 public void setColourBySequence(boolean colourBySequence)
425 this.colourBySequence = colourBySequence;
428 protected void addSequenceAndChain(int pe, SequenceI[] seq,
431 if (pe < 0 || pe >= getPdbCount())
433 throw new Error(MessageManager.formatMessage(
434 "error.implementation_error_no_pdbentry_from_index",
436 { Integer.valueOf(pe).toString() }));
438 final String nullChain = "TheNullChain";
439 List<SequenceI> s = new ArrayList<>();
440 List<String> c = new ArrayList<>();
441 if (getChains() == null)
443 setChains(new String[getPdbCount()][]);
445 if (getSequence()[pe] != null)
447 for (int i = 0; i < getSequence()[pe].length; i++)
449 s.add(getSequence()[pe][i]);
450 if (getChains()[pe] != null)
452 if (i < getChains()[pe].length)
454 c.add(getChains()[pe][i]);
463 if (tchain != null && tchain.length > 0)
470 for (int i = 0; i < seq.length; i++)
472 if (!s.contains(seq[i]))
475 if (tchain != null && i < tchain.length)
477 c.add(tchain[i] == null ? nullChain : tchain[i]);
481 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
482 getSequence()[pe] = tmp;
485 String[] tch = c.toArray(new String[c.size()]);
486 for (int i = 0; i < tch.length; i++)
488 if (tch[i] == nullChain)
493 getChains()[pe] = tch;
497 getChains()[pe] = null;
502 * add structures and any known sequence associations
504 * @returns the pdb entries added to the current set.
506 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
507 SequenceI[][] seq, String[][] chns)
509 List<PDBEntry> v = new ArrayList<>();
510 List<int[]> rtn = new ArrayList<>();
511 for (int i = 0; i < getPdbCount(); i++)
513 v.add(getPdbEntry(i));
515 for (int i = 0; i < pdbe.length; i++)
517 int r = v.indexOf(pdbe[i]);
518 if (r == -1 || r >= getPdbCount())
520 rtn.add(new int[] { v.size(), i });
525 // just make sure the sequence/chain entries are all up to date
526 addSequenceAndChain(r, seq[i], chns[i]);
529 pdbe = v.toArray(new PDBEntry[v.size()]);
533 // expand the tied sequence[] and string[] arrays
534 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
535 String[][] sch = new String[getPdbCount()][];
536 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
537 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
540 pdbe = new PDBEntry[rtn.size()];
541 for (int r = 0; r < pdbe.length; r++)
543 int[] stri = (rtn.get(r));
544 // record the pdb file as a new addition
545 pdbe[r] = getPdbEntry(stri[0]);
546 // and add the new sequence/chain entries
547 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
558 * Add sequences to the pe'th pdbentry's sequence set.
563 public void addSequence(int pe, SequenceI[] seq)
565 addSequenceAndChain(pe, seq, null);
569 * add the given sequences to the mapping scope for the given pdb file handle
572 * - pdbFile identifier
574 * - set of sequences it can be mapped to
576 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
578 for (int pe = 0; pe < getPdbCount(); pe++)
580 if (getPdbEntry(pe).getFile().equals(pdbFile))
582 addSequence(pe, seq);
588 public abstract void highlightAtoms(List<AtomSpec> atoms);
590 protected boolean isNucleotide()
592 return this.nucleotide;
596 * Returns a readable description of all mappings for the wrapped pdbfile to
597 * any mapped sequences
603 public String printMappings()
605 if (pdbEntry == null)
609 StringBuilder sb = new StringBuilder(128);
610 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
612 String pdbfile = getPdbEntry(pdbe).getFile();
613 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
614 sb.append(getSsm().printMappings(pdbfile, seqs));
616 return sb.toString();
620 * Returns the mapped structure position for a given aligned column of a given
621 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
622 * not mapped to structure.
629 protected int getMappedPosition(SequenceI seq, int alignedPos,
630 StructureMapping mapping)
632 if (alignedPos >= seq.getLength())
637 if (Comparison.isGap(seq.getCharAt(alignedPos)))
641 int seqPos = seq.findPosition(alignedPos);
642 int pos = mapping.getPDBResNum(seqPos);
647 * Helper method to identify residues that can participate in a structure
648 * superposition command. For each structure, identify a sequence in the
649 * alignment which is mapped to the structure. Identify non-gapped columns in
650 * the sequence which have a mapping to a residue in the structure. Returns
651 * the index of the first structure that has a mapping to the alignment.
654 * the sequence alignment which is the basis of structure
657 * a BitSet, where bit j is set to indicate that every structure has
658 * a mapped residue present in column j (so the column can
659 * participate in structure alignment)
661 * an array of data beans corresponding to pdb file index
664 protected int findSuperposableResidues(AlignmentI alignment,
666 AAStructureBindingModel.SuperposeData[] structures)
668 int refStructure = -1;
669 String[] files = getStructureFiles();
674 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
676 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
680 * Find the first mapped sequence (if any) for this PDB entry which is in
683 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
684 for (int s = 0; s < seqCountForPdbFile; s++)
686 for (StructureMapping mapping : mappings)
688 final SequenceI theSequence = getSequence()[pdbfnum][s];
689 if (mapping.getSequence() == theSequence
690 && alignment.findIndex(theSequence) > -1)
692 if (refStructure < 0)
694 refStructure = pdbfnum;
696 for (int r = 0; r < alignment.getWidth(); r++)
702 int pos = getMappedPosition(theSequence, r, mapping);
703 if (pos < 1 || pos == lastPos)
709 structures[pdbfnum].pdbResNo[r] = pos;
711 String chain = mapping.getChain();
712 if (chain != null && chain.trim().length() > 0)
714 structures[pdbfnum].chain = chain;
716 structures[pdbfnum].pdbId = mapping.getPdbId();
717 structures[pdbfnum].isRna = theSequence.getRNA() != null;
720 * move on to next pdb file (ignore sequences for other chains
721 * for the same structure)
723 s = seqCountForPdbFile;
724 break; // fixme break out of two loops here!
733 * Returns true if the structure viewer has loaded all of the files of
734 * interest (identified by the file mapping having been set up), or false if
735 * any are still not loaded after a timeout interval.
739 protected boolean waitForFileLoad(String[] files)
742 * give up after 10 secs plus 1 sec per file
744 long starttime = System.currentTimeMillis();
745 long endTime = 10000 + 1000 * files.length + starttime;
746 String notLoaded = null;
748 boolean waiting = true;
749 while (waiting && System.currentTimeMillis() < endTime)
752 for (String file : files)
761 StructureMapping[] sm = getSsm().getMapping(file);
762 if (sm == null || sm.length == 0)
766 } catch (Throwable x)
776 "Timed out waiting for structure viewer to load file "
784 public boolean isListeningFor(SequenceI seq)
786 if (sequence != null)
788 for (SequenceI[] seqs : sequence)
792 for (SequenceI s : seqs)
794 if (s == seq || (s.getDatasetSequence() != null
795 && s.getDatasetSequence() == seq.getDatasetSequence()))
806 public boolean isFinishedInit()
811 public void setFinishedInit(boolean fi)
813 this.finishedInit = fi;
817 * Returns a list of chains mapped in this viewer, formatted as
822 public List<String> getChainNames()
828 * Returns the Jalview panel hosting the structure viewer (if any)
832 public JalviewStructureDisplayI getViewer()
837 public void setViewer(JalviewStructureDisplayI v)
843 * Constructs and sends a command to align structures against a reference
844 * structure, based on one or more sequence alignments. May optionally return
845 * an error or warning message for the alignment command(s).
848 * an array of one or more alignment views to process
851 public String superposeStructures(List<AlignmentViewPanel> alignWith)
854 String[] files = getStructureFiles();
856 if (!waitForFileLoad(files))
862 for (AlignmentViewPanel view : alignWith)
864 AlignmentI alignment = view.getAlignment();
865 HiddenColumns hiddenCols = alignment.getHiddenColumns();
868 * 'matched' bit i will be set for visible alignment columns i where
869 * all sequences have a residue with a mapping to their PDB structure
871 BitSet matched = new BitSet();
872 final int width = alignment.getWidth();
873 for (int m = 0; m < width; m++)
875 if (hiddenCols == null || hiddenCols.isVisible(m))
881 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
882 for (int f = 0; f < files.length; f++)
884 structures[f] = new AAStructureBindingModel.SuperposeData(width,
885 getModelIdForFile(files[f]));
889 * Calculate the superposable alignment columns ('matched'), and the
890 * corresponding structure residue positions (structures.pdbResNo)
892 int refStructure = findSuperposableResidues(alignment, matched,
896 * require at least 4 positions to be able to execute superposition
898 int nmatched = matched.cardinality();
899 if (nmatched < MIN_POS_TO_SUPERPOSE)
901 String msg = MessageManager
902 .formatMessage("label.insufficient_residues", nmatched);
903 error += view.getViewName() + ": " + msg + "; ";
908 * get a model of the superposable residues in the reference structure
910 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
914 * Show all as backbone before doing superposition(s)
915 * (residues used for matching will be shown as ribbon)
917 // todo better way to ensure synchronous than setting getReply true!!
918 executeCommands(commandGenerator.showBackbone(), true, null);
921 * superpose each (other) structure to the reference in turn
923 for (int i = 0; i < structures.length; i++)
925 if (i != refStructure)
927 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
928 List<StructureCommandI> commands = commandGenerator
929 .superposeStructures(refAtoms, atomSpec);
930 List<String> replies = executeCommands(commands, true, null);
931 for (String reply : replies)
933 // return this error (Chimera only) to the user
934 if (reply.toLowerCase().contains("unequal numbers of atoms"))
936 error += "; " + reply;
946 private AtomSpecModel getAtomSpec(
947 AAStructureBindingModel.SuperposeData superposeData,
950 AtomSpecModel model = new AtomSpecModel();
951 int nextColumnMatch = matched.nextSetBit(0);
952 while (nextColumnMatch != -1)
954 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
955 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
956 superposeData.chain);
957 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
964 * returns the current sequenceRenderer that should be used to colour the
971 public abstract SequenceRenderer getSequenceRenderer(
972 AlignmentViewPanel alignment);
975 * Sends a command to the structure viewer to colour each chain with a
976 * distinct colour (to the extent supported by the viewer)
978 public void colourByChain()
980 colourBySequence = false;
982 // TODO: JAL-628 colour chains distinctly across all visible models
984 executeCommand(commandGenerator.colourByChain(), false,
985 COLOURING_STRUCTURES);
989 * Sends a command to the structure viewer to colour each chain with a
990 * distinct colour (to the extent supported by the viewer)
992 public void colourByCharge()
994 colourBySequence = false;
996 executeCommands(commandGenerator.colourByCharge(), false,
997 COLOURING_STRUCTURES);
1001 * Sends a command to the structure to apply a colour scheme (defined in
1002 * Jalview but not necessarily applied to the alignment), which defines a
1003 * colour per residue letter. More complex schemes (e.g. that depend on
1004 * consensus) cannot be used here and are ignored.
1008 public void colourByJalviewColourScheme(ColourSchemeI cs)
1010 colourBySequence = false;
1012 if (cs == null || !cs.isSimple())
1018 * build a map of {Residue3LetterCode, Color}
1020 Map<String, Color> colours = new HashMap<>();
1021 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1023 for (String resName : residues)
1025 char res = resName.length() == 3
1026 ? ResidueProperties.getSingleCharacterCode(resName)
1027 : resName.charAt(0);
1028 Color colour = cs.findColour(res, 0, null, null, 0f);
1029 colours.put(resName, colour);
1033 * pass to the command constructor, and send the command
1035 List<StructureCommandI> cmd = commandGenerator
1036 .colourByResidues(colours);
1037 executeCommands(cmd, false, COLOURING_STRUCTURES);
1040 public void setBackgroundColour(Color col)
1042 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1043 executeCommand(cmd, false, null);
1047 * Sends one command to the structure viewer. If {@code getReply} is true, the
1048 * command is sent synchronously, otherwise in a deferred thread.
1050 * If a progress message is supplied, this is displayed before command
1051 * execution, and removed afterwards.
1058 private List<String> executeCommand(StructureCommandI cmd,
1059 boolean getReply, String msg)
1064 * synchronous (same thread) execution so reply can be returned
1066 final JalviewStructureDisplayI theViewer = getViewer();
1067 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1070 return executeCommand(cmd, getReply);
1075 theViewer.stopProgressBar(null, handle);
1082 * asynchronous (new thread) execution if no reply needed
1084 final JalviewStructureDisplayI theViewer = getViewer();
1085 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1087 SwingUtilities.invokeLater(new Runnable()
1094 executeCommand(cmd, false);
1099 theViewer.stopProgressBar(null, handle);
1109 * Execute one structure viewer command. If {@code getReply} is true, may
1110 * optionally return one or more reply messages, else returns null.
1115 protected abstract List<String> executeCommand(StructureCommandI cmd,
1119 * Executes one or more structure viewer commands. If a progress message is
1120 * provided, it is shown first, and removed after all commands have been run.
1126 protected List<String> executeCommands(List<StructureCommandI> commands,
1127 boolean getReply, String msg)
1130 * show progress message if specified
1132 final JalviewStructureDisplayI theViewer = getViewer();
1133 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1135 List<String> response = getReply ? new ArrayList<>() : null;
1138 for (StructureCommandI cmd : commands)
1140 List<String> replies = executeCommand(cmd, getReply, null);
1141 if (getReply && replies != null)
1143 response.addAll(replies);
1151 theViewer.stopProgressBar(null, handle);
1157 * Colours any structures associated with sequences in the given alignment as
1158 * coloured in the alignment view, provided colourBySequence is enabled
1160 public void colourBySequence(AlignmentViewPanel alignmentv)
1162 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1166 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1169 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1170 .colourBySequence(colourMap);
1171 executeCommands(colourBySequenceCommands, false, null);
1175 * Centre the display in the structure viewer
1177 public void focusView()
1179 executeCommand(commandGenerator.focusView(), false, null);
1183 * Generates and executes a command to show only specified chains in the
1184 * structure viewer. The list of chains to show should contain entries
1185 * formatted as "pdbid:chaincode".
1189 public void showChains(List<String> toShow)
1191 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1194 * Reformat the pdbid:chainCode values as modelNo:chainCode
1195 * since this is what is needed to construct the viewer command
1196 * todo: find a less messy way to do this
1198 List<String> showThese = new ArrayList<>();
1199 for (String chainId : toShow)
1201 String[] tokens = chainId.split("\\:");
1202 if (tokens.length == 2)
1204 String pdbFile = getFileForChain(chainId);
1205 String model = getModelIdForFile(pdbFile);
1206 showThese.add(model + ":" + tokens[1]);
1209 executeCommands(commandGenerator.showChains(showThese), false, null);
1213 * Answers the structure viewer's model id given a PDB file name. Returns an
1214 * empty string if model id is not found.
1219 protected abstract String getModelIdForFile(String chainId);
1221 public boolean hasFileLoadingError()
1223 return fileLoadingError != null && fileLoadingError.length() > 0;
1227 * Returns the FeatureRenderer for the given alignment view, or null if
1228 * feature display is turned off in the view.
1233 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1235 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1241 return ap.getAlignViewport().isShowSequenceFeatures()
1242 ? ap.getFeatureRenderer()
1246 protected void setStructureCommands(StructureCommandsI cmd)
1248 commandGenerator = cmd;
1252 * Records association of one chain id (formatted as "pdbid:chainCode") with
1253 * the corresponding PDB file name
1258 public void addChainFile(String chainId, String fileName)
1260 chainFile.put(chainId, fileName);
1264 * Returns the PDB filename for the given chain id (formatted as
1265 * "pdbid:chainCode"), or null if not found
1270 protected String getFileForChain(String chainId)
1272 return chainFile.get(chainId);
1276 public void updateColours(Object source)
1278 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1279 // ignore events from panels not used to colour this view
1280 if (!getViewer().isUsedForColourBy(ap))
1284 if (!isLoadingFromArchive())
1286 colourBySequence(ap);
1290 public StructureCommandsI getCommandGenerator()
1292 return commandGenerator;
1295 protected abstract ViewerType getViewerType();
1298 * Send a structure viewer command asynchronously in a new thread. If the
1299 * progress message is not null, display this message while the command is
1303 * @param progressMsg
1305 protected void sendAsynchronousCommand(StructureCommandI command,
1308 final JalviewStructureDisplayI theViewer = getViewer();
1309 final long handle = progressMsg == null ? 0
1310 : theViewer.startProgressBar(progressMsg);
1311 SwingUtilities.invokeLater(new Runnable()
1318 executeCommand(command, false, null);
1321 if (progressMsg != null)
1323 theViewer.stopProgressBar(null, handle);
1332 * Builds a data structure which records mapped structure residues for each
1333 * colour. From this we can easily generate the viewer commands for colour by
1334 * sequence. Constructs and returns a map of {@code Color} to
1335 * {@code AtomSpecModel}, where the atomspec model holds
1343 * Ordering is by order of addition (for colours), natural ordering (for
1344 * models and chains)
1351 protected Map<Object, AtomSpecModel> buildColoursMap(
1352 StructureSelectionManager ssm, SequenceI[][] sequence,
1353 AlignmentViewPanel viewPanel)
1355 String[] files = getStructureFiles();
1356 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1357 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1358 FeatureColourFinder finder = new FeatureColourFinder(fr);
1359 AlignViewportI viewport = viewPanel.getAlignViewport();
1360 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1361 AlignmentI al = viewport.getAlignment();
1362 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1363 Color lastColour = null;
1365 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1367 final String modelId = getModelIdForFile(files[pdbfnum]);
1368 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1370 if (mapping == null || mapping.length < 1)
1375 int startPos = -1, lastPos = -1;
1376 String lastChain = "";
1377 for (int s = 0; s < sequence[pdbfnum].length; s++)
1379 for (int sp, m = 0; m < mapping.length; m++)
1381 final SequenceI seq = sequence[pdbfnum][s];
1382 if (mapping[m].getSequence() == seq
1383 && (sp = al.findIndex(seq)) > -1)
1385 SequenceI asp = al.getSequenceAt(sp);
1386 for (int r = 0; r < asp.getLength(); r++)
1388 // no mapping to gaps in sequence
1389 if (Comparison.isGap(asp.getCharAt(r)))
1393 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1395 if (pos < 1 || pos == lastPos)
1400 Color colour = sr.getResidueColour(seq, r, finder);
1403 * darker colour for hidden regions
1405 if (!cs.isVisible(r))
1407 colour = Color.GRAY;
1410 final String chain = mapping[m].getChain();
1413 * Just keep incrementing the end position for this colour range
1414 * _unless_ colour, PDB model or chain has changed, or there is a
1415 * gap in the mapped residue sequence
1417 final boolean newColour = !colour.equals(lastColour);
1418 final boolean nonContig = lastPos + 1 != pos;
1419 final boolean newChain = !chain.equals(lastChain);
1420 if (newColour || nonContig || newChain)
1424 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1425 lastPos, lastChain);
1429 lastColour = colour;
1433 // final colour range
1434 if (lastColour != null)
1436 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1437 lastPos, lastChain);
1448 * todo better refactoring (map lookup or similar to get viewer structure id)
1454 protected String getModelId(int pdbfnum, String file)
1456 return String.valueOf(pdbfnum);
1460 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1461 * full PDB file path
1466 public void stashFoundChains(StructureFile pdb, String file)
1468 for (int i = 0; i < pdb.getChains().size(); i++)
1470 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1471 addChainFile(chid, file);
1472 getChainNames().add(chid);
1477 * Helper method to add one contiguous range to the AtomSpec model for the
1478 * given value (creating the model if necessary). As used by Jalview,
1481 * <li>a colour, when building a 'colour structure by sequence' command</li>
1482 * <li>a feature value, when building a 'set Chimera attributes from features'
1493 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1494 Object value, String model, int startPos, int endPos,
1498 * Get/initialize map of data for the colour
1500 AtomSpecModel atomSpec = map.get(value);
1501 if (atomSpec == null)
1503 atomSpec = new AtomSpecModel();
1504 map.put(value, atomSpec);
1507 atomSpec.addRange(model, startPos, endPos, chain);
1511 * Returns the file extension (including '.' separator) to use for a saved
1512 * viewer session file. Default is to return null (not supported), override as
1517 public String getSessionFileExtension()
1523 * If supported, saves the state of the structure viewer to a temporary file
1524 * and returns the file. Returns null and logs an error on any failure.
1528 public File saveSession()
1530 String prefix = getViewerType().toString();
1531 String suffix = getSessionFileExtension();
1535 f = File.createTempFile(prefix, suffix);
1537 } catch (IOException e)
1539 Cache.log.error(String.format("Error saving %s session: %s", prefix,
1547 * Saves the structure viewer session to the given file
1551 protected void saveSession(File f)
1553 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1556 executeCommand(cmd, false);
1561 * Returns true if the viewer is an external structure viewer for which the
1562 * process is still alive, else false (for Jmol, or an external viewer which
1563 * the user has independently closed)
1567 public boolean isViewerRunning()
1573 * Closes Jalview's structure viewer panel and releases associated resources.
1574 * If it is managing an external viewer program, and {@code forceClose} is
1575 * true, also asks that program to close.
1579 public void closeViewer(boolean forceClose)
1581 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1582 releaseUIResources();
1585 * end the thread that closes this panel if the external viewer closes
1587 if (externalViewerMonitor != null)
1589 externalViewerMonitor.interrupt();
1590 externalViewerMonitor = null;
1597 StructureCommandI cmd = getCommandGenerator().closeViewer();
1600 executeCommand(cmd, false);
1606 * Returns the URL of a help page for the structure viewer, or null if none is
1611 public String getHelpURL()
1618 * Helper method to build a map of
1619 * { featureType, { feature value, AtomSpecModel } }
1625 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1626 AlignmentViewPanel viewPanel)
1628 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1629 String[] files = getStructureFiles();
1635 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1641 AlignViewportI viewport = viewPanel.getAlignViewport();
1642 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1645 * if alignment is showing features from complement, we also transfer
1646 * these features to the corresponding mapped structure residues
1648 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1649 List<String> complementFeatures = new ArrayList<>();
1650 FeatureRenderer complementRenderer = null;
1651 if (showLinkedFeatures)
1653 AlignViewportI comp = fr.getViewport().getCodingComplement();
1656 complementRenderer = Desktop.getAlignFrameFor(comp)
1657 .getFeatureRenderer();
1658 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1661 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1666 AlignmentI alignment = viewPanel.getAlignment();
1667 SequenceI[][] seqs = getSequence();
1669 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1671 String modelId = getModelIdForFile(files[pdbfnum]);
1672 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1674 if (mapping == null || mapping.length < 1)
1679 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1681 for (int m = 0; m < mapping.length; m++)
1683 final SequenceI seq = seqs[pdbfnum][seqNo];
1684 int sp = alignment.findIndex(seq);
1685 StructureMapping structureMapping = mapping[m];
1686 if (structureMapping.getSequence() == seq && sp > -1)
1689 * found a sequence with a mapping to a structure;
1690 * now scan its features
1692 if (!visibleFeatures.isEmpty())
1694 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1697 if (showLinkedFeatures)
1699 scanComplementFeatures(complementRenderer, structureMapping,
1700 seq, theMap, modelId);
1710 * Ask the structure viewer to open a session file. Returns true if
1711 * successful, else false (or not supported).
1716 public boolean openSession(String filepath)
1718 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1723 executeCommand(cmd, true);
1724 // todo: test for failure - how?
1729 * Scans visible features in mapped positions of the CDS/peptide complement,
1730 * and adds any found to the map of attribute values/structure positions
1732 * @param complementRenderer
1733 * @param structureMapping
1736 * @param modelNumber
1738 protected static void scanComplementFeatures(
1739 FeatureRenderer complementRenderer,
1740 StructureMapping structureMapping, SequenceI seq,
1741 Map<String, Map<Object, AtomSpecModel>> theMap,
1745 * for each sequence residue mapped to a structure position...
1747 for (int seqPos : structureMapping.getMapping().keySet())
1750 * find visible complementary features at mapped position(s)
1752 MappedFeatures mf = complementRenderer
1753 .findComplementFeaturesAtResidue(seq, seqPos);
1756 for (SequenceFeature sf : mf.features)
1758 String type = sf.getType();
1761 * Don't copy features which originated from Chimera
1763 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1764 .equals(sf.getFeatureGroup()))
1770 * record feature 'value' (score/description/type) as at the
1771 * corresponding structure position
1773 List<int[]> mappedRanges = structureMapping
1774 .getPDBResNumRanges(seqPos, seqPos);
1776 if (!mappedRanges.isEmpty())
1778 String value = sf.getDescription();
1779 if (value == null || value.length() == 0)
1783 float score = sf.getScore();
1784 if (score != 0f && !Float.isNaN(score))
1786 value = Float.toString(score);
1788 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1789 if (featureValues == null)
1791 featureValues = new HashMap<>();
1792 theMap.put(type, featureValues);
1794 for (int[] range : mappedRanges)
1796 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1797 range[1], structureMapping.getChain());
1806 * Inspect features on the sequence; for each feature that is visible,
1807 * determine its mapped ranges in the structure (if any) according to the
1808 * given mapping, and add them to the map.
1810 * @param visibleFeatures
1816 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1817 StructureMapping mapping, SequenceI seq,
1818 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1820 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1821 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1822 for (SequenceFeature sf : sfs)
1824 String type = sf.getType();
1827 * Don't copy features which originated from Chimera
1829 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1830 .equals(sf.getFeatureGroup()))
1835 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1838 if (!mappedRanges.isEmpty())
1840 String value = sf.getDescription();
1841 if (value == null || value.length() == 0)
1845 float score = sf.getScore();
1846 if (score != 0f && !Float.isNaN(score))
1848 value = Float.toString(score);
1850 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1851 if (featureValues == null)
1853 featureValues = new HashMap<>();
1854 theMap.put(type, featureValues);
1856 for (int[] range : mappedRanges)
1858 addAtomSpecRange(featureValues, value, modelId, range[0],
1859 range[1], mapping.getChain());
1866 * Returns the number of structure files in the structure viewer and mapped to
1867 * Jalview. This may be zero if the files are still in the process of loading
1872 public int getMappedStructureCount()
1874 String[] files = getStructureFiles();
1875 return files == null ? 0 : files.length;
1879 * Starts a thread that waits for the external viewer program process to
1880 * finish, so that we can then close the associated resources. This avoids
1881 * leaving orphaned viewer panels in Jalview if the user closes the external
1886 protected void startExternalViewerMonitor(Process p)
1888 externalViewerMonitor = new Thread(new Runnable()
1897 JalviewStructureDisplayI display = getViewer();
1898 if (display != null)
1900 display.closeViewer(false);
1902 } catch (InterruptedException e)
1904 // exit thread if Chimera Viewer is closed in Jalview
1908 externalViewerMonitor.start();
1912 * If supported by the external structure viewer, sends it commands to notify
1913 * model or selection changes to the specified URL (where Jalview has started
1918 protected void startListening(String uri)
1920 List<StructureCommandI> commands = getCommandGenerator()
1921 .startNotifications(uri);
1922 if (commands != null)
1924 executeCommands(commands, false, null);
1929 * If supported by the external structure viewer, sends it commands to stop
1930 * notifying model or selection changes
1932 protected void stopListening()
1934 List<StructureCommandI> commands = getCommandGenerator()
1935 .stopNotifications();
1936 if (commands != null)
1938 executeCommands(commands, false, null);
1943 * If supported by the structure viewer, queries it for all residue attributes
1944 * with the given attribute name, and creates features on corresponding
1945 * residues of the alignment. Returns the number of features added.
1948 * @param alignmentPanel
1951 public int copyStructureAttributesToFeatures(String attName,
1952 AlignmentPanel alignmentPanel)
1954 StructureCommandI cmd = getCommandGenerator()
1955 .getResidueAttributes(attName);
1960 List<String> residueAttributes = executeCommand(cmd, true);
1962 int featuresAdded = createFeaturesForAttributes(attName,
1964 if (featuresAdded > 0)
1966 alignmentPanel.getFeatureRenderer().featuresAdded();
1968 return featuresAdded;
1972 * Parses {@code residueAttributes} and creates sequence features on any
1973 * mapped alignment residues. Returns the number of features created.
1975 * {@code residueAttributes} is the reply from the structure viewer to a
1976 * command to list any residue attributes for the given attribute name. Syntax
1977 * and parsing of this is viewer-specific.
1980 * @param residueAttributes
1983 protected int createFeaturesForAttributes(String attName,
1984 List<String> residueAttributes)