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.StructureCommandI;
61 import jalview.structure.StructureCommandsI;
62 import jalview.structure.StructureListener;
63 import jalview.structure.StructureMapping;
64 import jalview.structure.StructureSelectionManager;
65 import jalview.util.Comparison;
66 import jalview.util.MessageManager;
70 * A base class to hold common function for protein structure model binding.
71 * Initial version created by refactoring JMol and Chimera binding models, but
72 * other structure viewers could in principle be accommodated in future.
77 public abstract class AAStructureBindingModel
78 extends SequenceStructureBindingModel
79 implements StructureListener, StructureSelectionManagerProvider
82 * Data bean class to simplify parameterisation in superposeStructures
84 public static class SuperposeData
86 public String filename;
90 public String chain = "";
95 * The pdb residue number (if any) mapped to columns of the alignment
97 public int[] pdbResNo; // or use SparseIntArray?
99 public String modelId;
105 * width of alignment (number of columns that may potentially
106 * participate in superposition)
108 * structure viewer model number
110 public SuperposeData(int width, String model)
112 pdbResNo = new int[width];
117 private static final int MIN_POS_TO_SUPERPOSE = 4;
119 private static final String COLOURING_STRUCTURES = MessageManager
120 .getString("status.colouring_structures");
123 * the Jalview panel through which the user interacts
124 * with the structure viewer
126 private JalviewStructureDisplayI viewer;
129 * helper that generates command syntax
131 private StructureCommandsI commandGenerator;
133 private StructureSelectionManager ssm;
136 * modelled chains, formatted as "pdbid:chainCode"
138 private List<String> chainNames;
141 * lookup of pdb file name by key "pdbid:chainCode"
143 private Map<String, String> chainFile;
146 * distinct PDB entries (pdb files) associated
149 private PDBEntry[] pdbEntry;
152 * sequences mapped to each pdbentry
154 private SequenceI[][] sequence;
157 * array of target chains for sequences - tied to pdbentry and sequence[]
159 private String[][] chains;
162 * datasource protocol for access to PDBEntrylatest
164 DataSourceType protocol = null;
166 protected boolean colourBySequence = true;
168 private boolean nucleotide;
170 private boolean finishedInit = false;
173 * current set of model filenames loaded in the viewer
175 protected String[] modelFileNames = null;
177 public String fileLoadingError;
179 protected Thread externalViewerMonitor;
187 public AAStructureBindingModel(StructureSelectionManager ssm,
191 this.sequence = seqs;
192 chainNames = new ArrayList<>();
193 chainFile = new HashMap<>();
204 public AAStructureBindingModel(StructureSelectionManager ssm,
205 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
206 DataSourceType protocol)
208 this(ssm, sequenceIs);
209 this.nucleotide = Comparison.isNucleotide(sequenceIs);
210 this.pdbEntry = pdbentry;
211 this.protocol = protocol;
215 private boolean resolveChains()
218 * final count of chain mappings discovered
221 // JBPNote: JAL-2693 - this should be a list of chain mappings per
222 // [pdbentry][sequence]
223 String[][] newchains = new String[pdbEntry.length][];
225 for (PDBEntry pdb : pdbEntry)
227 SequenceI[] seqsForPdb = sequence[pe];
228 if (seqsForPdb != null)
230 newchains[pe] = new String[seqsForPdb.length];
232 for (SequenceI asq : seqsForPdb)
234 String chain = (chains != null && chains[pe] != null)
237 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
238 : asq.getDatasetSequence();
239 if (sq.getAllPDBEntries() != null)
241 for (PDBEntry pdbentry : sq.getAllPDBEntries())
243 if (pdb.getFile() != null && pdbentry.getFile() != null
244 && pdb.getFile().equals(pdbentry.getFile()))
246 String chaincode = pdbentry.getChainCode();
247 if (chaincode != null && chaincode.length() > 0)
256 newchains[pe][se] = chain;
264 return chainmaps > 0;
267 public StructureSelectionManager getSsm()
273 * Returns the i'th PDBEntry (or null)
278 public PDBEntry getPdbEntry(int i)
280 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
284 * Answers true if this binding includes the given PDB id, else false
289 public boolean hasPdbId(String pdbId)
291 if (pdbEntry != null)
293 for (PDBEntry pdb : pdbEntry)
295 if (pdb.getId().equals(pdbId))
305 * Returns the number of modelled PDB file entries.
309 public int getPdbCount()
311 return pdbEntry == null ? 0 : pdbEntry.length;
314 public SequenceI[][] getSequence()
319 public String[][] getChains()
324 public DataSourceType getProtocol()
329 // TODO may remove this if calling methods can be pulled up here
330 protected void setPdbentry(PDBEntry[] pdbentry)
332 this.pdbEntry = pdbentry;
335 protected void setSequence(SequenceI[][] sequence)
337 this.sequence = sequence;
340 protected void setChains(String[][] chains)
342 this.chains = chains;
346 * Construct a title string for the viewer window based on the data Jalview
355 public String getViewerTitle(String viewerName, boolean verbose)
357 if (getSequence() == null || getSequence().length < 1
358 || getPdbCount() < 1 || getSequence()[0].length < 1)
360 return ("Jalview " + viewerName + " Window");
362 // TODO: give a more informative title when multiple structures are
364 StringBuilder title = new StringBuilder(64);
365 final PDBEntry pdbe = getPdbEntry(0);
366 title.append(viewerName + " view for " + getSequence()[0][0].getName()
367 + ":" + pdbe.getId());
371 String method = (String) pdbe.getProperty("method");
374 title.append(" Method: ").append(method);
376 String chain = (String) pdbe.getProperty("chains");
379 title.append(" Chain:").append(chain);
382 return title.toString();
386 * Called by after closeViewer is called, to release any resources and
387 * references so they can be garbage collected. Override if needed.
389 protected void releaseUIResources()
394 public void releaseReferences(Object svl)
398 public boolean isColourBySequence()
400 return colourBySequence;
404 * Called when the binding thinks the UI needs to be refreshed after a
405 * structure viewer state change. This could be because structures were
406 * loaded, or because an error has occurred. Default does nothing, override as
409 public void refreshGUI()
414 * Instruct the Jalview binding to update the pdbentries vector if necessary
415 * prior to matching the jmol view's contents to the list of structure files
416 * Jalview knows about. By default does nothing, override as required.
418 public void refreshPdbEntries()
422 public void setColourBySequence(boolean colourBySequence)
424 this.colourBySequence = colourBySequence;
427 protected void addSequenceAndChain(int pe, SequenceI[] seq,
430 if (pe < 0 || pe >= getPdbCount())
432 throw new Error(MessageManager.formatMessage(
433 "error.implementation_error_no_pdbentry_from_index",
435 { Integer.valueOf(pe).toString() }));
437 final String nullChain = "TheNullChain";
438 List<SequenceI> s = new ArrayList<>();
439 List<String> c = new ArrayList<>();
440 if (getChains() == null)
442 setChains(new String[getPdbCount()][]);
444 if (getSequence()[pe] != null)
446 for (int i = 0; i < getSequence()[pe].length; i++)
448 s.add(getSequence()[pe][i]);
449 if (getChains()[pe] != null)
451 if (i < getChains()[pe].length)
453 c.add(getChains()[pe][i]);
462 if (tchain != null && tchain.length > 0)
469 for (int i = 0; i < seq.length; i++)
471 if (!s.contains(seq[i]))
474 if (tchain != null && i < tchain.length)
476 c.add(tchain[i] == null ? nullChain : tchain[i]);
480 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
481 getSequence()[pe] = tmp;
484 String[] tch = c.toArray(new String[c.size()]);
485 for (int i = 0; i < tch.length; i++)
487 if (tch[i] == nullChain)
492 getChains()[pe] = tch;
496 getChains()[pe] = null;
501 * add structures and any known sequence associations
503 * @returns the pdb entries added to the current set.
505 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
506 SequenceI[][] seq, String[][] chns)
508 List<PDBEntry> v = new ArrayList<>();
509 List<int[]> rtn = new ArrayList<>();
510 for (int i = 0; i < getPdbCount(); i++)
512 v.add(getPdbEntry(i));
514 for (int i = 0; i < pdbe.length; i++)
516 int r = v.indexOf(pdbe[i]);
517 if (r == -1 || r >= getPdbCount())
519 rtn.add(new int[] { v.size(), i });
524 // just make sure the sequence/chain entries are all up to date
525 addSequenceAndChain(r, seq[i], chns[i]);
528 pdbe = v.toArray(new PDBEntry[v.size()]);
532 // expand the tied sequence[] and string[] arrays
533 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
534 String[][] sch = new String[getPdbCount()][];
535 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
536 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
539 pdbe = new PDBEntry[rtn.size()];
540 for (int r = 0; r < pdbe.length; r++)
542 int[] stri = (rtn.get(r));
543 // record the pdb file as a new addition
544 pdbe[r] = getPdbEntry(stri[0]);
545 // and add the new sequence/chain entries
546 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
557 * Add sequences to the pe'th pdbentry's sequence set.
562 public void addSequence(int pe, SequenceI[] seq)
564 addSequenceAndChain(pe, seq, null);
568 * add the given sequences to the mapping scope for the given pdb file handle
571 * - pdbFile identifier
573 * - set of sequences it can be mapped to
575 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
577 for (int pe = 0; pe < getPdbCount(); pe++)
579 if (getPdbEntry(pe).getFile().equals(pdbFile))
581 addSequence(pe, seq);
587 public abstract void highlightAtoms(List<AtomSpec> atoms);
589 protected boolean isNucleotide()
591 return this.nucleotide;
595 * Returns a readable description of all mappings for the wrapped pdbfile to
596 * any mapped sequences
602 public String printMappings()
604 if (pdbEntry == null)
608 StringBuilder sb = new StringBuilder(128);
609 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
611 String pdbfile = getPdbEntry(pdbe).getFile();
612 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
613 sb.append(getSsm().printMappings(pdbfile, seqs));
615 return sb.toString();
619 * Returns the mapped structure position for a given aligned column of a given
620 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
621 * not mapped to structure.
628 protected int getMappedPosition(SequenceI seq, int alignedPos,
629 StructureMapping mapping)
631 if (alignedPos >= seq.getLength())
636 if (Comparison.isGap(seq.getCharAt(alignedPos)))
640 int seqPos = seq.findPosition(alignedPos);
641 int pos = mapping.getPDBResNum(seqPos);
646 * Helper method to identify residues that can participate in a structure
647 * superposition command. For each structure, identify a sequence in the
648 * alignment which is mapped to the structure. Identify non-gapped columns in
649 * the sequence which have a mapping to a residue in the structure. Returns
650 * the index of the first structure that has a mapping to the alignment.
653 * the sequence alignment which is the basis of structure
656 * a BitSet, where bit j is set to indicate that every structure has
657 * a mapped residue present in column j (so the column can
658 * participate in structure alignment)
660 * an array of data beans corresponding to pdb file index
663 protected int findSuperposableResidues(AlignmentI alignment,
665 AAStructureBindingModel.SuperposeData[] structures)
667 int refStructure = -1;
668 String[] files = getStructureFiles();
673 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
675 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
679 * Find the first mapped sequence (if any) for this PDB entry which is in
682 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
683 for (int s = 0; s < seqCountForPdbFile; s++)
685 for (StructureMapping mapping : mappings)
687 final SequenceI theSequence = getSequence()[pdbfnum][s];
688 if (mapping.getSequence() == theSequence
689 && alignment.findIndex(theSequence) > -1)
691 if (refStructure < 0)
693 refStructure = pdbfnum;
695 for (int r = 0; r < alignment.getWidth(); r++)
701 int pos = getMappedPosition(theSequence, r, mapping);
702 if (pos < 1 || pos == lastPos)
708 structures[pdbfnum].pdbResNo[r] = pos;
710 String chain = mapping.getChain();
711 if (chain != null && chain.trim().length() > 0)
713 structures[pdbfnum].chain = chain;
715 structures[pdbfnum].pdbId = mapping.getPdbId();
716 structures[pdbfnum].isRna = theSequence.getRNA() != null;
719 * move on to next pdb file (ignore sequences for other chains
720 * for the same structure)
722 s = seqCountForPdbFile;
723 break; // fixme break out of two loops here!
732 * Returns true if the structure viewer has loaded all of the files of
733 * interest (identified by the file mapping having been set up), or false if
734 * any are still not loaded after a timeout interval.
738 protected boolean waitForFileLoad(String[] files)
741 * give up after 10 secs plus 1 sec per file
743 long starttime = System.currentTimeMillis();
744 long endTime = 10000 + 1000 * files.length + starttime;
745 String notLoaded = null;
747 boolean waiting = true;
748 while (waiting && System.currentTimeMillis() < endTime)
751 for (String file : files)
760 StructureMapping[] sm = getSsm().getMapping(file);
761 if (sm == null || sm.length == 0)
765 } catch (Throwable x)
775 "Timed out waiting for structure viewer to load file "
783 public boolean isListeningFor(SequenceI seq)
785 if (sequence != null)
787 for (SequenceI[] seqs : sequence)
791 for (SequenceI s : seqs)
793 if (s == seq || (s.getDatasetSequence() != null
794 && s.getDatasetSequence() == seq.getDatasetSequence()))
805 public boolean isFinishedInit()
810 public void setFinishedInit(boolean fi)
812 this.finishedInit = fi;
816 * Returns a list of chains mapped in this viewer, formatted as
821 public List<String> getChainNames()
827 * Returns the Jalview panel hosting the structure viewer (if any)
831 public JalviewStructureDisplayI getViewer()
836 public void setViewer(JalviewStructureDisplayI v)
842 * Constructs and sends a command to align structures against a reference
843 * structure, based on one or more sequence alignments. May optionally return
844 * an error or warning message for the alignment command(s).
847 * an array of one or more alignment views to process
850 public String superposeStructures(List<AlignmentViewPanel> alignWith)
853 String[] files = getStructureFiles();
855 if (!waitForFileLoad(files))
861 for (AlignmentViewPanel view : alignWith)
863 AlignmentI alignment = view.getAlignment();
864 HiddenColumns hiddenCols = alignment.getHiddenColumns();
867 * 'matched' bit i will be set for visible alignment columns i where
868 * all sequences have a residue with a mapping to their PDB structure
870 BitSet matched = new BitSet();
871 final int width = alignment.getWidth();
872 for (int m = 0; m < width; m++)
874 if (hiddenCols == null || hiddenCols.isVisible(m))
880 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
881 for (int f = 0; f < files.length; f++)
883 structures[f] = new AAStructureBindingModel.SuperposeData(width,
884 getModelIdForFile(files[f]));
888 * Calculate the superposable alignment columns ('matched'), and the
889 * corresponding structure residue positions (structures.pdbResNo)
891 int refStructure = findSuperposableResidues(alignment, matched,
895 * require at least 4 positions to be able to execute superposition
897 int nmatched = matched.cardinality();
898 if (nmatched < MIN_POS_TO_SUPERPOSE)
900 String msg = MessageManager
901 .formatMessage("label.insufficient_residues", nmatched);
902 error += view.getViewName() + ": " + msg + "; ";
907 * get a model of the superposable residues in the reference structure
909 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
913 * Show all as backbone before doing superposition(s)
914 * (residues used for matching will be shown as ribbon)
916 // todo better way to ensure synchronous than setting getReply true!!
917 executeCommands(commandGenerator.showBackbone(), true, null);
920 * superpose each (other) structure to the reference in turn
922 for (int i = 0; i < structures.length; i++)
924 if (i != refStructure)
926 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
927 List<StructureCommandI> commands = commandGenerator
928 .superposeStructures(refAtoms, atomSpec);
929 List<String> replies = executeCommands(commands, true, null);
930 for (String reply : replies)
932 // return this error (Chimera only) to the user
933 if (reply.toLowerCase().contains("unequal numbers of atoms"))
935 error += "; " + reply;
945 private AtomSpecModel getAtomSpec(
946 AAStructureBindingModel.SuperposeData superposeData,
949 AtomSpecModel model = new AtomSpecModel();
950 int nextColumnMatch = matched.nextSetBit(0);
951 while (nextColumnMatch != -1)
953 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
954 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
955 superposeData.chain);
956 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
963 * returns the current sequenceRenderer that should be used to colour the
970 public abstract SequenceRenderer getSequenceRenderer(
971 AlignmentViewPanel alignment);
974 * Sends a command to the structure viewer to colour each chain with a
975 * distinct colour (to the extent supported by the viewer)
977 public void colourByChain()
979 colourBySequence = false;
981 // TODO: JAL-628 colour chains distinctly across all visible models
983 executeCommand(false, COLOURING_STRUCTURES,
984 commandGenerator.colourByChain());
988 * Sends a command to the structure viewer to colour each chain with a
989 * distinct colour (to the extent supported by the viewer)
991 public void colourByCharge()
993 colourBySequence = false;
995 executeCommands(commandGenerator.colourByCharge(), false,
996 COLOURING_STRUCTURES);
1000 * Sends a command to the structure to apply a colour scheme (defined in
1001 * Jalview but not necessarily applied to the alignment), which defines a
1002 * colour per residue letter. More complex schemes (e.g. that depend on
1003 * consensus) cannot be used here and are ignored.
1007 public void colourByJalviewColourScheme(ColourSchemeI cs)
1009 colourBySequence = false;
1011 if (cs == null || !cs.isSimple())
1017 * build a map of {Residue3LetterCode, Color}
1019 Map<String, Color> colours = new HashMap<>();
1020 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1022 for (String resName : residues)
1024 char res = resName.length() == 3
1025 ? ResidueProperties.getSingleCharacterCode(resName)
1026 : resName.charAt(0);
1027 Color colour = cs.findColour(res, 0, null, null, 0f);
1028 colours.put(resName, colour);
1032 * pass to the command constructor, and send the command
1034 List<StructureCommandI> cmd = commandGenerator
1035 .colourByResidues(colours);
1036 executeCommands(cmd, false, COLOURING_STRUCTURES);
1039 public void setBackgroundColour(Color col)
1041 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1042 executeCommand(false, null, cmd);
1046 * Execute one structure viewer command. If {@code getReply} is true, may
1047 * optionally return one or more reply messages, else returns null.
1052 protected abstract List<String> executeCommand(StructureCommandI cmd,
1056 * Executes one or more structure viewer commands
1062 protected List<String> executeCommands(List<StructureCommandI> commands,
1063 boolean getReply, String msg)
1065 return executeCommand(getReply, msg,
1066 commands.toArray(new StructureCommandI[commands.size()]));
1070 * Executes one or more structure viewer commands, optionally returning the
1071 * reply, and optionally showing a status message while the command is being
1074 * If a reply is wanted, the execution is done synchronously (waits),
1075 * otherwise it is done in a separate thread (doesn't wait).
1082 protected List<String> executeCommand(boolean getReply, String msg,
1083 StructureCommandI... cmds)
1085 JalviewStructureDisplayI theViewer = getViewer();
1086 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1091 * execute and wait for reply
1093 List<String> response = new ArrayList<>();
1096 for (StructureCommandI cmd : cmds)
1098 List<String> replies = executeCommand(cmd, true);
1099 if (replies != null)
1101 response.addAll(replies);
1109 theViewer.stopProgressBar(null, handle);
1117 String threadName = msg == null ? "StructureCommand" : msg;
1118 new Thread(new Runnable()
1125 for (StructureCommandI cmd : cmds)
1127 executeCommand(cmd, false);
1133 SwingUtilities.invokeLater(new Runnable()
1138 theViewer.stopProgressBar(null, handle);
1144 }, threadName).start();
1149 * Colours any structures associated with sequences in the given alignment as
1150 * coloured in the alignment view, provided colourBySequence is enabled
1152 public void colourBySequence(AlignmentViewPanel alignmentv)
1154 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1158 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1161 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1162 .colourBySequence(colourMap);
1163 executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1167 * Centre the display in the structure viewer
1169 public void focusView()
1171 executeCommand(false, null, commandGenerator.focusView());
1175 * Generates and executes a command to show only specified chains in the
1176 * structure viewer. The list of chains to show should contain entries
1177 * formatted as "pdbid:chaincode".
1181 public void showChains(List<String> toShow)
1183 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1186 * Reformat the pdbid:chainCode values as modelNo:chainCode
1187 * since this is what is needed to construct the viewer command
1188 * todo: find a less messy way to do this
1190 List<String> showThese = new ArrayList<>();
1191 for (String chainId : toShow)
1193 String[] tokens = chainId.split("\\:");
1194 if (tokens.length == 2)
1196 String pdbFile = getFileForChain(chainId);
1197 String model = getModelIdForFile(pdbFile);
1198 showThese.add(model + ":" + tokens[1]);
1201 executeCommands(commandGenerator.showChains(showThese), false, null);
1205 * Answers the structure viewer's model id given a PDB file name. Returns an
1206 * empty string if model id is not found.
1211 protected abstract String getModelIdForFile(String chainId);
1213 public boolean hasFileLoadingError()
1215 return fileLoadingError != null && fileLoadingError.length() > 0;
1219 * Returns the FeatureRenderer for the given alignment view, or null if
1220 * feature display is turned off in the view.
1225 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1227 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1233 return ap.getAlignViewport().isShowSequenceFeatures()
1234 ? ap.getFeatureRenderer()
1238 protected void setStructureCommands(StructureCommandsI cmd)
1240 commandGenerator = cmd;
1244 * Records association of one chain id (formatted as "pdbid:chainCode") with
1245 * the corresponding PDB file name
1250 public void addChainFile(String chainId, String fileName)
1252 chainFile.put(chainId, fileName);
1256 * Returns the PDB filename for the given chain id (formatted as
1257 * "pdbid:chainCode"), or null if not found
1262 protected String getFileForChain(String chainId)
1264 return chainFile.get(chainId);
1268 public void updateColours(Object source)
1270 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1271 // ignore events from panels not used to colour this view
1272 if (!getViewer().isUsedForColourBy(ap))
1276 if (!isLoadingFromArchive())
1278 colourBySequence(ap);
1282 public StructureCommandsI getCommandGenerator()
1284 return commandGenerator;
1287 protected abstract ViewerType getViewerType();
1290 * Builds a data structure which records mapped structure residues for each
1291 * colour. From this we can easily generate the viewer commands for colour by
1292 * sequence. Constructs and returns a map of {@code Color} to
1293 * {@code AtomSpecModel}, where the atomspec model holds
1301 * Ordering is by order of addition (for colours), natural ordering (for
1302 * models and chains)
1309 protected Map<Object, AtomSpecModel> buildColoursMap(
1310 StructureSelectionManager ssm, SequenceI[][] sequence,
1311 AlignmentViewPanel viewPanel)
1313 String[] files = getStructureFiles();
1314 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1315 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1316 FeatureColourFinder finder = new FeatureColourFinder(fr);
1317 AlignViewportI viewport = viewPanel.getAlignViewport();
1318 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1319 AlignmentI al = viewport.getAlignment();
1320 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1321 Color lastColour = null;
1323 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1325 final String modelId = getModelIdForFile(files[pdbfnum]);
1326 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1328 if (mapping == null || mapping.length < 1)
1333 int startPos = -1, lastPos = -1;
1334 String lastChain = "";
1335 for (int s = 0; s < sequence[pdbfnum].length; s++)
1337 for (int sp, m = 0; m < mapping.length; m++)
1339 final SequenceI seq = sequence[pdbfnum][s];
1340 if (mapping[m].getSequence() == seq
1341 && (sp = al.findIndex(seq)) > -1)
1343 SequenceI asp = al.getSequenceAt(sp);
1344 for (int r = 0; r < asp.getLength(); r++)
1346 // no mapping to gaps in sequence
1347 if (Comparison.isGap(asp.getCharAt(r)))
1351 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1353 if (pos < 1 || pos == lastPos)
1358 Color colour = sr.getResidueColour(seq, r, finder);
1361 * darker colour for hidden regions
1363 if (!cs.isVisible(r))
1365 colour = Color.GRAY;
1368 final String chain = mapping[m].getChain();
1371 * Just keep incrementing the end position for this colour range
1372 * _unless_ colour, PDB model or chain has changed, or there is a
1373 * gap in the mapped residue sequence
1375 final boolean newColour = !colour.equals(lastColour);
1376 final boolean nonContig = lastPos + 1 != pos;
1377 final boolean newChain = !chain.equals(lastChain);
1378 if (newColour || nonContig || newChain)
1382 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1383 lastPos, lastChain);
1387 lastColour = colour;
1391 // final colour range
1392 if (lastColour != null)
1394 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1395 lastPos, lastChain);
1406 * todo better refactoring (map lookup or similar to get viewer structure id)
1412 protected String getModelId(int pdbfnum, String file)
1414 return String.valueOf(pdbfnum);
1418 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1419 * full PDB file path
1424 public void stashFoundChains(StructureFile pdb, String file)
1426 for (int i = 0; i < pdb.getChains().size(); i++)
1428 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1429 addChainFile(chid, file);
1430 getChainNames().add(chid);
1435 * Helper method to add one contiguous range to the AtomSpec model for the
1436 * given value (creating the model if necessary). As used by Jalview,
1439 * <li>a colour, when building a 'colour structure by sequence' command</li>
1440 * <li>a feature value, when building a 'set Chimera attributes from features'
1451 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1452 Object value, String model, int startPos, int endPos,
1456 * Get/initialize map of data for the colour
1458 AtomSpecModel atomSpec = map.get(value);
1459 if (atomSpec == null)
1461 atomSpec = new AtomSpecModel();
1462 map.put(value, atomSpec);
1465 atomSpec.addRange(model, startPos, endPos, chain);
1469 * Returns the file extension (including '.' separator) to use for a saved
1470 * viewer session file. Default is to return null (not supported), override as
1475 public String getSessionFileExtension()
1481 * If supported, saves the state of the structure viewer to a temporary file
1482 * and returns the file. Returns null and logs an error on any failure.
1486 public File saveSession()
1488 String prefix = getViewerType().toString();
1489 String suffix = getSessionFileExtension();
1493 f = File.createTempFile(prefix, suffix);
1495 } catch (IOException e)
1497 Cache.log.error(String.format("Error saving %s session: %s", prefix,
1505 * Saves the structure viewer session to the given file
1509 protected void saveSession(File f)
1511 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1514 executeCommand(cmd, false);
1519 * Returns true if the viewer is an external structure viewer for which the
1520 * process is still alive, else false (for Jmol, or an external viewer which
1521 * the user has independently closed)
1525 public boolean isViewerRunning()
1531 * Closes Jalview's structure viewer panel and releases associated resources.
1532 * If it is managing an external viewer program, and {@code forceClose} is
1533 * true, also asks that program to close.
1537 public void closeViewer(boolean forceClose)
1539 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1540 releaseUIResources();
1543 * end the thread that closes this panel if the external viewer closes
1545 if (externalViewerMonitor != null)
1547 externalViewerMonitor.interrupt();
1548 externalViewerMonitor = null;
1555 StructureCommandI cmd = getCommandGenerator().closeViewer();
1558 executeCommand(cmd, false);
1564 * Returns the URL of a help page for the structure viewer, or null if none is
1569 public String getHelpURL()
1576 * Helper method to build a map of
1577 * { featureType, { feature value, AtomSpecModel } }
1583 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1584 AlignmentViewPanel viewPanel)
1586 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1587 String[] files = getStructureFiles();
1593 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1599 AlignViewportI viewport = viewPanel.getAlignViewport();
1600 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1603 * if alignment is showing features from complement, we also transfer
1604 * these features to the corresponding mapped structure residues
1606 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1607 List<String> complementFeatures = new ArrayList<>();
1608 FeatureRenderer complementRenderer = null;
1609 if (showLinkedFeatures)
1611 AlignViewportI comp = fr.getViewport().getCodingComplement();
1614 complementRenderer = Desktop.getAlignFrameFor(comp)
1615 .getFeatureRenderer();
1616 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1619 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1624 AlignmentI alignment = viewPanel.getAlignment();
1625 SequenceI[][] seqs = getSequence();
1627 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1629 String modelId = getModelIdForFile(files[pdbfnum]);
1630 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1632 if (mapping == null || mapping.length < 1)
1637 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1639 for (int m = 0; m < mapping.length; m++)
1641 final SequenceI seq = seqs[pdbfnum][seqNo];
1642 int sp = alignment.findIndex(seq);
1643 StructureMapping structureMapping = mapping[m];
1644 if (structureMapping.getSequence() == seq && sp > -1)
1647 * found a sequence with a mapping to a structure;
1648 * now scan its features
1650 if (!visibleFeatures.isEmpty())
1652 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1655 if (showLinkedFeatures)
1657 scanComplementFeatures(complementRenderer, structureMapping,
1658 seq, theMap, modelId);
1668 * Ask the structure viewer to open a session file. Returns true if
1669 * successful, else false (or not supported).
1674 public boolean openSession(String filepath)
1676 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1681 executeCommand(cmd, true);
1682 // todo: test for failure - how?
1687 * Scans visible features in mapped positions of the CDS/peptide complement,
1688 * and adds any found to the map of attribute values/structure positions
1690 * @param complementRenderer
1691 * @param structureMapping
1694 * @param modelNumber
1696 protected static void scanComplementFeatures(
1697 FeatureRenderer complementRenderer,
1698 StructureMapping structureMapping, SequenceI seq,
1699 Map<String, Map<Object, AtomSpecModel>> theMap,
1703 * for each sequence residue mapped to a structure position...
1705 for (int seqPos : structureMapping.getMapping().keySet())
1708 * find visible complementary features at mapped position(s)
1710 MappedFeatures mf = complementRenderer
1711 .findComplementFeaturesAtResidue(seq, seqPos);
1714 for (SequenceFeature sf : mf.features)
1716 String type = sf.getType();
1719 * Don't copy features which originated from Chimera
1721 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1722 .equals(sf.getFeatureGroup()))
1728 * record feature 'value' (score/description/type) as at the
1729 * corresponding structure position
1731 List<int[]> mappedRanges = structureMapping
1732 .getPDBResNumRanges(seqPos, seqPos);
1734 if (!mappedRanges.isEmpty())
1736 String value = sf.getDescription();
1737 if (value == null || value.length() == 0)
1741 float score = sf.getScore();
1742 if (score != 0f && !Float.isNaN(score))
1744 value = Float.toString(score);
1746 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1747 if (featureValues == null)
1749 featureValues = new HashMap<>();
1750 theMap.put(type, featureValues);
1752 for (int[] range : mappedRanges)
1754 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1755 range[1], structureMapping.getChain());
1764 * Inspect features on the sequence; for each feature that is visible,
1765 * determine its mapped ranges in the structure (if any) according to the
1766 * given mapping, and add them to the map.
1768 * @param visibleFeatures
1774 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1775 StructureMapping mapping, SequenceI seq,
1776 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1778 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1779 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1780 for (SequenceFeature sf : sfs)
1782 String type = sf.getType();
1785 * Don't copy features which originated from Chimera
1787 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1788 .equals(sf.getFeatureGroup()))
1793 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1796 if (!mappedRanges.isEmpty())
1798 String value = sf.getDescription();
1799 if (value == null || value.length() == 0)
1803 float score = sf.getScore();
1804 if (score != 0f && !Float.isNaN(score))
1806 value = Float.toString(score);
1808 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1809 if (featureValues == null)
1811 featureValues = new HashMap<>();
1812 theMap.put(type, featureValues);
1814 for (int[] range : mappedRanges)
1816 addAtomSpecRange(featureValues, value, modelId, range[0],
1817 range[1], mapping.getChain());
1824 * Returns the number of structure files in the structure viewer and mapped to
1825 * Jalview. This may be zero if the files are still in the process of loading
1830 public int getMappedStructureCount()
1832 String[] files = getStructureFiles();
1833 return files == null ? 0 : files.length;
1837 * Starts a thread that waits for the external viewer program process to
1838 * finish, so that we can then close the associated resources. This avoids
1839 * leaving orphaned viewer panels in Jalview if the user closes the external
1844 protected void startExternalViewerMonitor(Process p)
1846 externalViewerMonitor = new Thread(new Runnable()
1855 JalviewStructureDisplayI display = getViewer();
1856 if (display != null)
1858 display.closeViewer(false);
1860 } catch (InterruptedException e)
1862 // exit thread if Chimera Viewer is closed in Jalview
1866 externalViewerMonitor.start();
1870 * If supported by the external structure viewer, sends it commands to notify
1871 * model or selection changes to the specified URL (where Jalview has started
1876 protected void startListening(String uri)
1878 List<StructureCommandI> commands = getCommandGenerator()
1879 .startNotifications(uri);
1880 if (commands != null)
1882 executeCommands(commands, false, null);
1887 * If supported by the external structure viewer, sends it commands to stop
1888 * notifying model or selection changes
1890 protected void stopListening()
1892 List<StructureCommandI> commands = getCommandGenerator()
1893 .stopNotifications();
1894 if (commands != null)
1896 executeCommands(commands, false, null);
1901 * If supported by the structure viewer, queries it for all residue attributes
1902 * with the given attribute name, and creates features on corresponding
1903 * residues of the alignment. Returns the number of features added.
1906 * @param alignmentPanel
1909 public int copyStructureAttributesToFeatures(String attName,
1910 AlignmentPanel alignmentPanel)
1912 StructureCommandI cmd = getCommandGenerator()
1913 .getResidueAttributes(attName);
1918 List<String> residueAttributes = executeCommand(cmd, true);
1920 int featuresAdded = createFeaturesForAttributes(attName,
1922 if (featuresAdded > 0)
1924 alignmentPanel.getFeatureRenderer().featuresAdded();
1926 return featuresAdded;
1930 * Parses {@code residueAttributes} and creates sequence features on any
1931 * mapped alignment residues. Returns the number of features created.
1933 * {@code residueAttributes} is the reply from the structure viewer to a
1934 * command to list any residue attributes for the given attribute name. Syntax
1935 * and parsing of this is viewer-specific.
1938 * @param residueAttributes
1941 protected int createFeaturesForAttributes(String attName,
1942 List<String> residueAttributes)