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.util.Locale;
25 import java.awt.Color;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.BitSet;
31 import java.util.HashMap;
32 import java.util.LinkedHashMap;
33 import java.util.List;
36 import javax.swing.SwingUtilities;
38 import jalview.api.AlignViewportI;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.api.FeatureRenderer;
41 import jalview.api.SequenceRenderer;
42 import jalview.api.StructureSelectionManagerProvider;
43 import jalview.api.structures.JalviewStructureDisplayI;
44 import jalview.bin.Cache;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.HiddenColumns;
47 import jalview.datamodel.MappedFeatures;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceFeature;
50 import jalview.datamodel.SequenceI;
51 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
52 import jalview.gui.AlignmentPanel;
53 import jalview.gui.Desktop;
54 import jalview.gui.StructureViewer.ViewerType;
55 import jalview.io.DataSourceType;
56 import jalview.io.StructureFile;
57 import jalview.renderer.seqfeatures.FeatureColourFinder;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.schemes.ResidueProperties;
60 import jalview.structure.AtomSpec;
61 import jalview.structure.AtomSpecModel;
62 import jalview.structure.StructureCommandI;
63 import jalview.structure.StructureCommandsI;
64 import jalview.structure.StructureListener;
65 import jalview.structure.StructureMapping;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.Comparison;
68 import jalview.util.MessageManager;
72 * A base class to hold common function for 3D structure model binding.
73 * Initial version created by refactoring JMol and Chimera binding models, but
74 * other structure viewers could in principle be accommodated in future.
79 public abstract class AAStructureBindingModel
80 extends SequenceStructureBindingModel
81 implements StructureListener, StructureSelectionManagerProvider
84 * Data bean class to simplify parameterisation in superposeStructures
86 public static class SuperposeData
88 public String filename;
92 public String chain = "";
97 * The pdb residue number (if any) mapped to columns of the alignment
99 public int[] pdbResNo; // or use SparseIntArray?
101 public String modelId;
107 * width of alignment (number of columns that may potentially
108 * participate in superposition)
110 * structure viewer model number
112 public SuperposeData(int width, String model)
114 pdbResNo = new int[width];
119 private static final int MIN_POS_TO_SUPERPOSE = 4;
121 private static final String COLOURING_STRUCTURES = MessageManager
122 .getString("status.colouring_structures");
125 * the Jalview panel through which the user interacts
126 * with the structure viewer
128 private JalviewStructureDisplayI viewer;
131 * helper that generates command syntax
133 private StructureCommandsI commandGenerator;
135 private StructureSelectionManager ssm;
138 * modelled chains, formatted as "pdbid:chainCode"
140 private List<String> chainNames;
143 * lookup of pdb file name by key "pdbid:chainCode"
145 private Map<String, String> chainFile;
148 * distinct PDB entries (pdb files) associated
151 private PDBEntry[] pdbEntry;
154 * sequences mapped to each pdbentry
156 private SequenceI[][] sequence;
159 * array of target chains for sequences - tied to pdbentry and sequence[]
161 private String[][] chains;
164 * datasource protocol for access to PDBEntrylatest
166 DataSourceType protocol = null;
168 protected boolean colourBySequence = true;
170 private boolean nucleotide;
172 private boolean finishedInit = false;
175 * current set of model filenames loaded in the viewer
177 protected String[] modelFileNames = null;
179 public String fileLoadingError;
181 protected Thread externalViewerMonitor;
189 public AAStructureBindingModel(StructureSelectionManager ssm,
193 this.sequence = seqs;
194 chainNames = new ArrayList<>();
195 chainFile = new HashMap<>();
206 public AAStructureBindingModel(StructureSelectionManager ssm,
207 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
208 DataSourceType protocol)
210 this(ssm, sequenceIs);
211 this.nucleotide = Comparison.isNucleotide(sequenceIs);
212 this.pdbEntry = pdbentry;
213 this.protocol = protocol;
217 private boolean resolveChains()
220 * final count of chain mappings discovered
223 // JBPNote: JAL-2693 - this should be a list of chain mappings per
224 // [pdbentry][sequence]
225 String[][] newchains = new String[pdbEntry.length][];
227 for (PDBEntry pdb : pdbEntry)
229 SequenceI[] seqsForPdb = sequence[pe];
230 if (seqsForPdb != null)
232 newchains[pe] = new String[seqsForPdb.length];
234 for (SequenceI asq : seqsForPdb)
236 String chain = (chains != null && chains[pe] != null)
239 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
240 : asq.getDatasetSequence();
241 if (sq.getAllPDBEntries() != null)
243 for (PDBEntry pdbentry : sq.getAllPDBEntries())
245 if (pdb.getFile() != null && pdbentry.getFile() != null
246 && pdb.getFile().equals(pdbentry.getFile()))
248 String chaincode = pdbentry.getChainCode();
249 if (chaincode != null && chaincode.length() > 0)
258 newchains[pe][se] = chain;
266 return chainmaps > 0;
269 public StructureSelectionManager getSsm()
275 * Returns the i'th PDBEntry (or null)
280 public PDBEntry getPdbEntry(int i)
282 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
286 * Answers true if this binding includes the given PDB id, else false
291 public boolean hasPdbId(String pdbId)
293 if (pdbEntry != null)
295 for (PDBEntry pdb : pdbEntry)
297 if (pdb.getId().equals(pdbId))
307 * Returns the number of modelled PDB file entries.
311 public int getPdbCount()
313 return pdbEntry == null ? 0 : pdbEntry.length;
316 public SequenceI[][] getSequence()
321 public String[][] getChains()
326 public DataSourceType getProtocol()
331 // TODO may remove this if calling methods can be pulled up here
332 protected void setPdbentry(PDBEntry[] pdbentry)
334 this.pdbEntry = pdbentry;
337 protected void setSequence(SequenceI[][] sequence)
339 this.sequence = sequence;
342 protected void setChains(String[][] chains)
344 this.chains = chains;
348 * Construct a title string for the viewer window based on the data Jalview
357 public String getViewerTitle(String viewerName, boolean verbose)
359 if (getSequence() == null || getSequence().length < 1
360 || getPdbCount() < 1 || getSequence()[0].length < 1)
362 return ("Jalview " + viewerName + " Window");
364 // TODO: give a more informative title when multiple structures are
366 StringBuilder title = new StringBuilder(64);
367 final PDBEntry pdbe = getPdbEntry(0);
368 title.append(viewerName + " view for " + getSequence()[0][0].getName()
369 + ":" + pdbe.getId());
373 String method = (String) pdbe.getProperty("method");
376 title.append(" Method: ").append(method);
378 String chain = (String) pdbe.getProperty("chains");
381 title.append(" Chain:").append(chain);
384 return title.toString();
388 * Called by after closeViewer is called, to release any resources and
389 * references so they can be garbage collected. Override if needed.
391 protected void releaseUIResources()
396 public void releaseReferences(Object svl)
400 public boolean isColourBySequence()
402 return colourBySequence;
406 * Called when the binding thinks the UI needs to be refreshed after a
407 * structure viewer state change. This could be because structures were
408 * loaded, or because an error has occurred. Default does nothing, override as
411 public void refreshGUI()
416 * Instruct the Jalview binding to update the pdbentries vector if necessary
417 * prior to matching the jmol view's contents to the list of structure files
418 * Jalview knows about. By default does nothing, override as required.
420 public void refreshPdbEntries()
424 public void setColourBySequence(boolean colourBySequence)
426 this.colourBySequence = colourBySequence;
429 protected void addSequenceAndChain(int pe, SequenceI[] seq,
432 if (pe < 0 || pe >= getPdbCount())
434 throw new Error(MessageManager.formatMessage(
435 "error.implementation_error_no_pdbentry_from_index",
437 { Integer.valueOf(pe).toString() }));
439 final String nullChain = "TheNullChain";
440 List<SequenceI> s = new ArrayList<>();
441 List<String> c = new ArrayList<>();
442 if (getChains() == null)
444 setChains(new String[getPdbCount()][]);
446 if (getSequence()[pe] != null)
448 for (int i = 0; i < getSequence()[pe].length; i++)
450 s.add(getSequence()[pe][i]);
451 if (getChains()[pe] != null)
453 if (i < getChains()[pe].length)
455 c.add(getChains()[pe][i]);
464 if (tchain != null && tchain.length > 0)
471 for (int i = 0; i < seq.length; i++)
473 if (!s.contains(seq[i]))
476 if (tchain != null && i < tchain.length)
478 c.add(tchain[i] == null ? nullChain : tchain[i]);
482 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
483 getSequence()[pe] = tmp;
486 String[] tch = c.toArray(new String[c.size()]);
487 for (int i = 0; i < tch.length; i++)
489 if (tch[i] == nullChain)
494 getChains()[pe] = tch;
498 getChains()[pe] = null;
503 * add structures and any known sequence associations
505 * @returns the pdb entries added to the current set.
507 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
508 SequenceI[][] seq, String[][] chns)
510 List<PDBEntry> v = new ArrayList<>();
511 List<int[]> rtn = new ArrayList<>();
512 for (int i = 0; i < getPdbCount(); i++)
514 v.add(getPdbEntry(i));
516 for (int i = 0; i < pdbe.length; i++)
518 int r = v.indexOf(pdbe[i]);
519 if (r == -1 || r >= getPdbCount())
521 rtn.add(new int[] { v.size(), i });
526 // just make sure the sequence/chain entries are all up to date
527 addSequenceAndChain(r, seq[i], chns[i]);
530 pdbe = v.toArray(new PDBEntry[v.size()]);
534 // expand the tied sequence[] and string[] arrays
535 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
536 String[][] sch = new String[getPdbCount()][];
537 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
538 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
541 pdbe = new PDBEntry[rtn.size()];
542 for (int r = 0; r < pdbe.length; r++)
544 int[] stri = (rtn.get(r));
545 // record the pdb file as a new addition
546 pdbe[r] = getPdbEntry(stri[0]);
547 // and add the new sequence/chain entries
548 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
559 * Add sequences to the pe'th pdbentry's sequence set.
564 public void addSequence(int pe, SequenceI[] seq)
566 addSequenceAndChain(pe, seq, null);
570 * add the given sequences to the mapping scope for the given pdb file handle
573 * - pdbFile identifier
575 * - set of sequences it can be mapped to
577 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
579 for (int pe = 0; pe < getPdbCount(); pe++)
581 if (getPdbEntry(pe).getFile().equals(pdbFile))
583 addSequence(pe, seq);
590 public abstract void highlightAtoms(List<AtomSpec> atoms);
592 protected boolean isNucleotide()
594 return this.nucleotide;
598 * Returns a readable description of all mappings for the wrapped pdbfile to
599 * any mapped sequences
605 public String printMappings()
607 if (pdbEntry == null)
611 StringBuilder sb = new StringBuilder(128);
612 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
614 String pdbfile = getPdbEntry(pdbe).getFile();
615 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
616 sb.append(getSsm().printMappings(pdbfile, seqs));
618 return sb.toString();
622 * Returns the mapped structure position for a given aligned column of a given
623 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
624 * not mapped to structure.
631 protected int getMappedPosition(SequenceI seq, int alignedPos,
632 StructureMapping mapping)
634 if (alignedPos >= seq.getLength())
639 if (Comparison.isGap(seq.getCharAt(alignedPos)))
643 int seqPos = seq.findPosition(alignedPos);
644 int pos = mapping.getPDBResNum(seqPos);
649 * Helper method to identify residues that can participate in a structure
650 * superposition command. For each structure, identify a sequence in the
651 * alignment which is mapped to the structure. Identify non-gapped columns in
652 * the sequence which have a mapping to a residue in the structure. Returns
653 * the index of the first structure that has a mapping to the alignment.
656 * the sequence alignment which is the basis of structure
659 * a BitSet, where bit j is set to indicate that every structure has
660 * a mapped residue present in column j (so the column can
661 * participate in structure alignment)
663 * an array of data beans corresponding to pdb file index
666 protected int findSuperposableResidues(AlignmentI alignment,
668 AAStructureBindingModel.SuperposeData[] structures)
670 int refStructure = -1;
671 String[] files = getStructureFiles();
676 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
678 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
682 * Find the first mapped sequence (if any) for this PDB entry which is in
685 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
686 for (int s = 0; s < seqCountForPdbFile; s++)
688 for (StructureMapping mapping : mappings)
690 final SequenceI theSequence = getSequence()[pdbfnum][s];
691 if (mapping.getSequence() == theSequence
692 && alignment.findIndex(theSequence) > -1)
694 if (refStructure < 0)
696 refStructure = pdbfnum;
698 for (int r = 0; r < alignment.getWidth(); r++)
704 int pos = getMappedPosition(theSequence, r, mapping);
705 if (pos < 1 || pos == lastPos)
711 structures[pdbfnum].pdbResNo[r] = pos;
713 String chain = mapping.getChain();
714 if (chain != null && chain.trim().length() > 0)
716 structures[pdbfnum].chain = chain;
718 structures[pdbfnum].pdbId = mapping.getPdbId();
719 structures[pdbfnum].isRna = theSequence.getRNA() != null;
722 * move on to next pdb file (ignore sequences for other chains
723 * for the same structure)
725 s = seqCountForPdbFile;
726 break; // fixme break out of two loops here!
735 * Returns true if the structure viewer has loaded all of the files of
736 * interest (identified by the file mapping having been set up), or false if
737 * any are still not loaded after a timeout interval.
741 protected boolean waitForFileLoad(String[] files)
744 * give up after 10 secs plus 1 sec per file
746 long starttime = System.currentTimeMillis();
747 long endTime = 10000 + 1000 * files.length + starttime;
748 String notLoaded = null;
750 boolean waiting = true;
751 while (waiting && System.currentTimeMillis() < endTime)
754 for (String file : files)
763 StructureMapping[] sm = getSsm().getMapping(file);
764 if (sm == null || sm.length == 0)
768 } catch (Throwable x)
778 "Timed out waiting for structure viewer to load file "
786 public boolean isListeningFor(SequenceI seq)
788 if (sequence != null)
790 for (SequenceI[] seqs : sequence)
794 for (SequenceI s : seqs)
796 if (s == seq || (s.getDatasetSequence() != null
797 && s.getDatasetSequence() == seq.getDatasetSequence()))
808 public boolean isFinishedInit()
813 public void setFinishedInit(boolean fi)
815 this.finishedInit = fi;
819 * Returns a list of chains mapped in this viewer, formatted as
824 public List<String> getChainNames()
830 * Returns the Jalview panel hosting the structure viewer (if any)
834 public JalviewStructureDisplayI getViewer()
839 public void setViewer(JalviewStructureDisplayI v)
845 * Constructs and sends a command to align structures against a reference
846 * structure, based on one or more sequence alignments. May optionally return
847 * an error or warning message for the alignment command(s).
850 * an array of one or more alignment views to process
853 public String superposeStructures(List<AlignmentViewPanel> alignWith)
856 String[] files = getStructureFiles();
858 if (!waitForFileLoad(files))
864 for (AlignmentViewPanel view : alignWith)
866 AlignmentI alignment = view.getAlignment();
867 HiddenColumns hiddenCols = alignment.getHiddenColumns();
870 * 'matched' bit i will be set for visible alignment columns i where
871 * all sequences have a residue with a mapping to their PDB structure
873 BitSet matched = new BitSet();
874 final int width = alignment.getWidth();
875 for (int m = 0; m < width; m++)
877 if (hiddenCols == null || hiddenCols.isVisible(m))
883 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
884 for (int f = 0; f < files.length; f++)
886 structures[f] = new AAStructureBindingModel.SuperposeData(width,
887 getModelIdForFile(files[f]));
891 * Calculate the superposable alignment columns ('matched'), and the
892 * corresponding structure residue positions (structures.pdbResNo)
894 int refStructure = findSuperposableResidues(alignment, matched,
898 * require at least 4 positions to be able to execute superposition
900 int nmatched = matched.cardinality();
901 if (nmatched < MIN_POS_TO_SUPERPOSE)
903 String msg = MessageManager
904 .formatMessage("label.insufficient_residues", nmatched);
905 error += view.getViewName() + ": " + msg + "; ";
910 * get a model of the superposable residues in the reference structure
912 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
916 * Show all as backbone before doing superposition(s)
917 * (residues used for matching will be shown as ribbon)
919 // todo better way to ensure synchronous than setting getReply true!!
920 executeCommands(commandGenerator.showBackbone(), true, null);
923 * superpose each (other) structure to the reference in turn
925 for (int i = 0; i < structures.length; i++)
927 if (i != refStructure)
929 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
930 List<StructureCommandI> commands = commandGenerator
931 .superposeStructures(refAtoms, atomSpec);
932 List<String> replies = executeCommands(commands, true, null);
933 for (String reply : replies)
935 // return this error (Chimera only) to the user
936 if (reply.toLowerCase(Locale.ROOT).contains("unequal numbers of atoms"))
938 error += "; " + reply;
948 private AtomSpecModel getAtomSpec(
949 AAStructureBindingModel.SuperposeData superposeData,
952 AtomSpecModel model = new AtomSpecModel();
953 int nextColumnMatch = matched.nextSetBit(0);
954 while (nextColumnMatch != -1)
956 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
957 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
958 superposeData.chain);
959 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
966 * returns the current sequenceRenderer that should be used to colour the
973 public abstract SequenceRenderer getSequenceRenderer(
974 AlignmentViewPanel alignment);
977 * Sends a command to the structure viewer to colour each chain with a
978 * distinct colour (to the extent supported by the viewer)
980 public void colourByChain()
982 colourBySequence = false;
984 // TODO: JAL-628 colour chains distinctly across all visible models
986 executeCommand(false, COLOURING_STRUCTURES,
987 commandGenerator.colourByChain());
991 * Sends a command to the structure viewer to colour each chain with a
992 * distinct colour (to the extent supported by the viewer)
994 public void colourByCharge()
996 colourBySequence = false;
998 executeCommands(commandGenerator.colourByCharge(), false,
999 COLOURING_STRUCTURES);
1003 * Sends a command to the structure to apply a colour scheme (defined in
1004 * Jalview but not necessarily applied to the alignment), which defines a
1005 * colour per residue letter. More complex schemes (e.g. that depend on
1006 * consensus) cannot be used here and are ignored.
1010 public void colourByJalviewColourScheme(ColourSchemeI cs)
1012 colourBySequence = false;
1014 if (cs == null || !cs.isSimple())
1020 * build a map of {Residue3LetterCode, Color}
1022 Map<String, Color> colours = new HashMap<>();
1023 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1025 for (String resName : residues)
1027 char res = resName.length() == 3
1028 ? ResidueProperties.getSingleCharacterCode(resName)
1029 : resName.charAt(0);
1030 Color colour = cs.findColour(res, 0, null, null, 0f);
1031 colours.put(resName, colour);
1035 * pass to the command constructor, and send the command
1037 List<StructureCommandI> cmd = commandGenerator
1038 .colourByResidues(colours);
1039 executeCommands(cmd, false, COLOURING_STRUCTURES);
1042 public void setBackgroundColour(Color col)
1044 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1045 executeCommand(false, null, cmd);
1049 * Execute one structure viewer command. If {@code getReply} is true, may
1050 * optionally return one or more reply messages, else returns null.
1055 protected abstract List<String> executeCommand(StructureCommandI cmd,
1059 * Executes one or more structure viewer commands
1065 protected List<String> executeCommands(List<StructureCommandI> commands,
1066 boolean getReply, String msg)
1068 return executeCommand(getReply, msg,
1069 commands.toArray(new StructureCommandI[commands.size()]));
1073 * Executes one or more structure viewer commands, optionally returning the
1074 * reply, and optionally showing a status message while the command is being
1077 * If a reply is wanted, the execution is done synchronously (waits),
1078 * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1079 * are sending commands that need to execute before later calls to
1080 * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1081 * set getReply true to ensure that commands are not executed out of order.
1088 protected List<String> executeCommand(boolean getReply, String msg,
1089 StructureCommandI... cmds)
1091 JalviewStructureDisplayI theViewer = getViewer();
1092 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1097 * execute and wait for reply
1099 List<String> response = new ArrayList<>();
1102 for (StructureCommandI cmd : cmds)
1104 List<String> replies = executeCommand(cmd, true);
1105 if (replies != null)
1107 response.addAll(replies);
1115 theViewer.stopProgressBar(null, handle);
1123 String threadName = msg == null ? "StructureCommand" : msg;
1124 new Thread(new Runnable()
1131 for (StructureCommandI cmd : cmds)
1133 executeCommand(cmd, false);
1139 SwingUtilities.invokeLater(new Runnable()
1144 theViewer.stopProgressBar(null, handle);
1150 }, threadName).start();
1155 * Colours any structures associated with sequences in the given alignment as
1156 * coloured in the alignment view, provided colourBySequence is enabled
1158 public void colourBySequence(AlignmentViewPanel alignmentv)
1160 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1164 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1167 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1168 .colourBySequence(colourMap);
1169 executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1173 * Centre the display in the structure viewer
1175 public void focusView()
1177 executeCommand(false, null, commandGenerator.focusView());
1181 * Generates and executes a command to show only specified chains in the
1182 * structure viewer. The list of chains to show should contain entries
1183 * formatted as "pdbid:chaincode".
1187 public void showChains(List<String> toShow)
1189 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1192 * Reformat the pdbid:chainCode values as modelNo:chainCode
1193 * since this is what is needed to construct the viewer command
1194 * todo: find a less messy way to do this
1196 List<String> showThese = new ArrayList<>();
1197 for (String chainId : toShow)
1199 String[] tokens = chainId.split("\\:");
1200 if (tokens.length == 2)
1202 String pdbFile = getFileForChain(chainId);
1203 String model = getModelIdForFile(pdbFile);
1204 showThese.add(model + ":" + tokens[1]);
1207 executeCommands(commandGenerator.showChains(showThese), false, null);
1211 * Answers the structure viewer's model id given a PDB file name. Returns an
1212 * empty string if model id is not found.
1217 protected abstract String getModelIdForFile(String chainId);
1219 public boolean hasFileLoadingError()
1221 return fileLoadingError != null && fileLoadingError.length() > 0;
1225 * Returns the FeatureRenderer for the given alignment view
1230 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1232 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1238 return ap.getFeatureRenderer();
1241 protected void setStructureCommands(StructureCommandsI cmd)
1243 commandGenerator = cmd;
1247 * Records association of one chain id (formatted as "pdbid:chainCode") with
1248 * the corresponding PDB file name
1253 public void addChainFile(String chainId, String fileName)
1255 chainFile.put(chainId, fileName);
1259 * Returns the PDB filename for the given chain id (formatted as
1260 * "pdbid:chainCode"), or null if not found
1265 protected String getFileForChain(String chainId)
1267 return chainFile.get(chainId);
1271 public void updateColours(Object source)
1273 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1274 // ignore events from panels not used to colour this view
1275 if (!getViewer().isUsedForColourBy(ap))
1279 if (!isLoadingFromArchive())
1281 colourBySequence(ap);
1285 public StructureCommandsI getCommandGenerator()
1287 return commandGenerator;
1290 protected abstract ViewerType getViewerType();
1293 * Builds a data structure which records mapped structure residues for each
1294 * colour. From this we can easily generate the viewer commands for colour by
1295 * sequence. Constructs and returns a map of {@code Color} to
1296 * {@code AtomSpecModel}, where the atomspec model holds
1304 * Ordering is by order of addition (for colours), natural ordering (for
1305 * models and chains)
1312 protected Map<Object, AtomSpecModel> buildColoursMap(
1313 StructureSelectionManager ssm, SequenceI[][] sequence,
1314 AlignmentViewPanel viewPanel)
1316 String[] files = getStructureFiles();
1317 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1318 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1319 FeatureColourFinder finder = new FeatureColourFinder(fr);
1320 AlignViewportI viewport = viewPanel.getAlignViewport();
1321 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1322 AlignmentI al = viewport.getAlignment();
1323 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1324 Color lastColour = null;
1326 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1328 final String modelId = getModelIdForFile(files[pdbfnum]);
1329 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1331 if (mapping == null || mapping.length < 1)
1336 int startPos = -1, lastPos = -1;
1337 String lastChain = "";
1338 for (int s = 0; s < sequence[pdbfnum].length; s++)
1340 for (int sp, m = 0; m < mapping.length; m++)
1342 final SequenceI seq = sequence[pdbfnum][s];
1343 if (mapping[m].getSequence() == seq
1344 && (sp = al.findIndex(seq)) > -1)
1346 SequenceI asp = al.getSequenceAt(sp);
1347 for (int r = 0; r < asp.getLength(); r++)
1349 // no mapping to gaps in sequence
1350 if (Comparison.isGap(asp.getCharAt(r)))
1354 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1356 if (pos < 1 || pos == lastPos)
1361 Color colour = sr.getResidueColour(seq, r, finder);
1364 * darker colour for hidden regions
1366 if (!cs.isVisible(r))
1368 colour = Color.GRAY;
1371 final String chain = mapping[m].getChain();
1374 * Just keep incrementing the end position for this colour range
1375 * _unless_ colour, PDB model or chain has changed, or there is a
1376 * gap in the mapped residue sequence
1378 final boolean newColour = !colour.equals(lastColour);
1379 final boolean nonContig = lastPos + 1 != pos;
1380 final boolean newChain = !chain.equals(lastChain);
1381 if (newColour || nonContig || newChain)
1385 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1386 lastPos, lastChain);
1390 lastColour = colour;
1394 // final colour range
1395 if (lastColour != null)
1397 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1398 lastPos, lastChain);
1409 * todo better refactoring (map lookup or similar to get viewer structure id)
1415 protected String getModelId(int pdbfnum, String file)
1417 return String.valueOf(pdbfnum);
1421 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1422 * full PDB file path
1427 public void stashFoundChains(StructureFile pdb, String file)
1429 for (int i = 0; i < pdb.getChains().size(); i++)
1431 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1432 addChainFile(chid, file);
1433 getChainNames().add(chid);
1438 * Helper method to add one contiguous range to the AtomSpec model for the
1439 * given value (creating the model if necessary). As used by Jalview,
1442 * <li>a colour, when building a 'colour structure by sequence' command</li>
1443 * <li>a feature value, when building a 'set Chimera attributes from features'
1454 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1455 Object value, String model, int startPos, int endPos,
1459 * Get/initialize map of data for the colour
1461 AtomSpecModel atomSpec = map.get(value);
1462 if (atomSpec == null)
1464 atomSpec = new AtomSpecModel();
1465 map.put(value, atomSpec);
1468 atomSpec.addRange(model, startPos, endPos, chain);
1472 * Returns the file extension (including '.' separator) to use for a saved
1473 * viewer session file. Default is to return null (not supported), override as
1478 public String getSessionFileExtension()
1484 * If supported, saves the state of the structure viewer to a temporary file
1485 * and returns the file. Returns null and logs an error on any failure.
1489 public File saveSession()
1491 String prefix = getViewerType().toString();
1492 String suffix = getSessionFileExtension();
1496 f = File.createTempFile(prefix, suffix);
1498 } catch (IOException e)
1500 Cache.log.error(String.format("Error saving %s session: %s", prefix,
1508 * Saves the structure viewer session to the given file
1512 protected void saveSession(File f)
1514 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1517 executeCommand(cmd, false);
1522 * Returns true if the viewer is an external structure viewer for which the
1523 * process is still alive, else false (for Jmol, or an external viewer which
1524 * the user has independently closed)
1528 public boolean isViewerRunning()
1534 * Closes Jalview's structure viewer panel and releases associated resources.
1535 * If it is managing an external viewer program, and {@code forceClose} is
1536 * true, also asks that program to close.
1540 public void closeViewer(boolean forceClose)
1542 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1543 releaseUIResources();
1546 * end the thread that closes this panel if the external viewer closes
1548 if (externalViewerMonitor != null)
1550 externalViewerMonitor.interrupt();
1551 externalViewerMonitor = null;
1558 StructureCommandI cmd = getCommandGenerator().closeViewer();
1561 executeCommand(cmd, false);
1567 * Returns the URL of a help page for the structure viewer, or null if none is
1572 public String getHelpURL()
1579 * Helper method to build a map of
1580 * { featureType, { feature value, AtomSpecModel } }
1586 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1587 AlignmentViewPanel viewPanel)
1589 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1590 String[] files = getStructureFiles();
1596 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1602 AlignViewportI viewport = viewPanel.getAlignViewport();
1603 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1606 * if alignment is showing features from complement, we also transfer
1607 * these features to the corresponding mapped structure residues
1609 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1610 List<String> complementFeatures = new ArrayList<>();
1611 FeatureRenderer complementRenderer = null;
1612 if (showLinkedFeatures)
1614 AlignViewportI comp = fr.getViewport().getCodingComplement();
1617 complementRenderer = Desktop.getAlignFrameFor(comp)
1618 .getFeatureRenderer();
1619 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1622 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1627 AlignmentI alignment = viewPanel.getAlignment();
1628 SequenceI[][] seqs = getSequence();
1630 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1632 String modelId = getModelIdForFile(files[pdbfnum]);
1633 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1635 if (mapping == null || mapping.length < 1)
1640 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1642 for (int m = 0; m < mapping.length; m++)
1644 final SequenceI seq = seqs[pdbfnum][seqNo];
1645 int sp = alignment.findIndex(seq);
1646 StructureMapping structureMapping = mapping[m];
1647 if (structureMapping.getSequence() == seq && sp > -1)
1650 * found a sequence with a mapping to a structure;
1651 * now scan its features
1653 if (!visibleFeatures.isEmpty())
1655 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1658 if (showLinkedFeatures)
1660 scanComplementFeatures(complementRenderer, structureMapping,
1661 seq, theMap, modelId);
1671 * Ask the structure viewer to open a session file. Returns true if
1672 * successful, else false (or not supported).
1677 public boolean openSession(String filepath)
1679 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1684 executeCommand(cmd, true);
1685 // todo: test for failure - how?
1690 * Scans visible features in mapped positions of the CDS/peptide complement,
1691 * and adds any found to the map of attribute values/structure positions
1693 * @param complementRenderer
1694 * @param structureMapping
1697 * @param modelNumber
1699 protected static void scanComplementFeatures(
1700 FeatureRenderer complementRenderer,
1701 StructureMapping structureMapping, SequenceI seq,
1702 Map<String, Map<Object, AtomSpecModel>> theMap,
1706 * for each sequence residue mapped to a structure position...
1708 for (int seqPos : structureMapping.getMapping().keySet())
1711 * find visible complementary features at mapped position(s)
1713 MappedFeatures mf = complementRenderer
1714 .findComplementFeaturesAtResidue(seq, seqPos);
1717 for (SequenceFeature sf : mf.features)
1719 String type = sf.getType();
1722 * Don't copy features which originated from Chimera
1724 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1725 .equals(sf.getFeatureGroup()))
1731 * record feature 'value' (score/description/type) as at the
1732 * corresponding structure position
1734 List<int[]> mappedRanges = structureMapping
1735 .getPDBResNumRanges(seqPos, seqPos);
1737 if (!mappedRanges.isEmpty())
1739 String value = sf.getDescription();
1740 if (value == null || value.length() == 0)
1744 float score = sf.getScore();
1745 if (score != 0f && !Float.isNaN(score))
1747 value = Float.toString(score);
1749 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1750 if (featureValues == null)
1752 featureValues = new HashMap<>();
1753 theMap.put(type, featureValues);
1755 for (int[] range : mappedRanges)
1757 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1758 range[1], structureMapping.getChain());
1767 * Inspect features on the sequence; for each feature that is visible,
1768 * determine its mapped ranges in the structure (if any) according to the
1769 * given mapping, and add them to the map.
1771 * @param visibleFeatures
1777 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1778 StructureMapping mapping, SequenceI seq,
1779 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1781 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1782 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1783 for (SequenceFeature sf : sfs)
1785 String type = sf.getType();
1788 * Don't copy features which originated from Chimera
1790 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1791 .equals(sf.getFeatureGroup()))
1796 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1799 if (!mappedRanges.isEmpty())
1801 String value = sf.getDescription();
1802 if (value == null || value.length() == 0)
1806 float score = sf.getScore();
1807 if (score != 0f && !Float.isNaN(score))
1809 value = Float.toString(score);
1811 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1812 if (featureValues == null)
1814 featureValues = new HashMap<>();
1815 theMap.put(type, featureValues);
1817 for (int[] range : mappedRanges)
1819 addAtomSpecRange(featureValues, value, modelId, range[0],
1820 range[1], mapping.getChain());
1827 * Returns the number of structure files in the structure viewer and mapped to
1828 * Jalview. This may be zero if the files are still in the process of loading
1833 public int getMappedStructureCount()
1835 String[] files = getStructureFiles();
1836 return files == null ? 0 : files.length;
1840 * Starts a thread that waits for the external viewer program process to
1841 * finish, so that we can then close the associated resources. This avoids
1842 * leaving orphaned viewer panels in Jalview if the user closes the external
1847 protected void startExternalViewerMonitor(Process p)
1849 externalViewerMonitor = new Thread(new Runnable()
1858 JalviewStructureDisplayI display = getViewer();
1859 if (display != null)
1861 display.closeViewer(false);
1863 } catch (InterruptedException e)
1865 // exit thread if Chimera Viewer is closed in Jalview
1869 externalViewerMonitor.start();
1873 * If supported by the external structure viewer, sends it commands to notify
1874 * model or selection changes to the specified URL (where Jalview has started
1879 protected void startListening(String uri)
1881 List<StructureCommandI> commands = getCommandGenerator()
1882 .startNotifications(uri);
1883 if (commands != null)
1885 executeCommands(commands, false, null);
1890 * If supported by the external structure viewer, sends it commands to stop
1891 * notifying model or selection changes
1893 protected void stopListening()
1895 List<StructureCommandI> commands = getCommandGenerator()
1896 .stopNotifications();
1897 if (commands != null)
1899 executeCommands(commands, false, null);
1904 * If supported by the structure viewer, queries it for all residue attributes
1905 * with the given attribute name, and creates features on corresponding
1906 * residues of the alignment. Returns the number of features added.
1909 * @param alignmentPanel
1912 public int copyStructureAttributesToFeatures(String attName,
1913 AlignmentPanel alignmentPanel)
1915 StructureCommandI cmd = getCommandGenerator()
1916 .getResidueAttributes(attName);
1921 List<String> residueAttributes = executeCommand(cmd, true);
1923 int featuresAdded = createFeaturesForAttributes(attName,
1925 if (featuresAdded > 0)
1927 alignmentPanel.getFeatureRenderer().featuresAdded();
1929 return featuresAdded;
1933 * Parses {@code residueAttributes} and creates sequence features on any
1934 * mapped alignment residues. Returns the number of features created.
1936 * {@code residueAttributes} is the reply from the structure viewer to a
1937 * command to list any residue attributes for the given attribute name. Syntax
1938 * and parsing of this is viewer-specific.
1941 * @param residueAttributes
1944 protected int createFeaturesForAttributes(String attName,
1945 List<String> residueAttributes)