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.PDBEntry;
46 import jalview.datamodel.SequenceI;
47 import jalview.gui.StructureViewer.ViewerType;
48 import jalview.io.DataSourceType;
49 import jalview.io.StructureFile;
50 import jalview.renderer.seqfeatures.FeatureColourFinder;
51 import jalview.schemes.ColourSchemeI;
52 import jalview.schemes.ResidueProperties;
53 import jalview.structure.AtomSpec;
54 import jalview.structure.AtomSpecModel;
55 import jalview.structure.StructureCommandI;
56 import jalview.structure.StructureCommandsI;
57 import jalview.structure.StructureListener;
58 import jalview.structure.StructureMapping;
59 import jalview.structure.StructureSelectionManager;
60 import jalview.util.Comparison;
61 import jalview.util.MessageManager;
65 * A base class to hold common function for protein structure model binding.
66 * Initial version created by refactoring JMol and Chimera binding models, but
67 * other structure viewers could in principle be accommodated in future.
72 public abstract class AAStructureBindingModel
73 extends SequenceStructureBindingModel
74 implements StructureListener, StructureSelectionManagerProvider
77 * Data bean class to simplify parameterisation in superposeStructures
79 public static class SuperposeData
81 public String filename;
85 public String chain = "";
90 * The pdb residue number (if any) mapped to columns of the alignment
92 public int[] pdbResNo; // or use SparseIntArray?
94 public String modelId;
100 * width of alignment (number of columns that may potentially
101 * participate in superposition)
103 * structure viewer model number
105 public SuperposeData(int width, String model)
107 pdbResNo = new int[width];
112 private static final int MIN_POS_TO_SUPERPOSE = 4;
114 private static final String COLOURING_STRUCTURES = MessageManager
115 .getString("status.colouring_structures");
118 * the Jalview panel through which the user interacts
119 * with the structure viewer
121 private JalviewStructureDisplayI viewer;
124 * helper that generates command syntax
126 private StructureCommandsI commandGenerator;
128 private StructureSelectionManager ssm;
131 * modelled chains, formatted as "pdbid:chainCode"
133 private List<String> chainNames;
136 * lookup of pdb file name by key "pdbid:chainCode"
138 private Map<String, String> chainFile;
141 * distinct PDB entries (pdb files) associated
144 private PDBEntry[] pdbEntry;
147 * sequences mapped to each pdbentry
149 private SequenceI[][] sequence;
152 * array of target chains for sequences - tied to pdbentry and sequence[]
154 private String[][] chains;
157 * datasource protocol for access to PDBEntrylatest
159 DataSourceType protocol = null;
161 protected boolean colourBySequence = true;
163 private boolean nucleotide;
165 private boolean finishedInit = false;
168 * current set of model filenames loaded in the viewer
170 protected String[] modelFileNames = null;
172 public String fileLoadingError;
180 public AAStructureBindingModel(StructureSelectionManager ssm,
184 this.sequence = seqs;
185 chainNames = new ArrayList<>();
186 chainFile = new HashMap<>();
197 public AAStructureBindingModel(StructureSelectionManager ssm,
198 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
199 DataSourceType protocol)
201 this(ssm, sequenceIs);
202 this.nucleotide = Comparison.isNucleotide(sequenceIs);
203 this.pdbEntry = pdbentry;
204 this.protocol = protocol;
208 private boolean resolveChains()
211 * final count of chain mappings discovered
214 // JBPNote: JAL-2693 - this should be a list of chain mappings per
215 // [pdbentry][sequence]
216 String[][] newchains = new String[pdbEntry.length][];
218 for (PDBEntry pdb : pdbEntry)
220 SequenceI[] seqsForPdb = sequence[pe];
221 if (seqsForPdb != null)
223 newchains[pe] = new String[seqsForPdb.length];
225 for (SequenceI asq : seqsForPdb)
227 String chain = (chains != null && chains[pe] != null)
230 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
231 : asq.getDatasetSequence();
232 if (sq.getAllPDBEntries() != null)
234 for (PDBEntry pdbentry : sq.getAllPDBEntries())
236 if (pdb.getFile() != null && pdbentry.getFile() != null
237 && pdb.getFile().equals(pdbentry.getFile()))
239 String chaincode = pdbentry.getChainCode();
240 if (chaincode != null && chaincode.length() > 0)
249 newchains[pe][se] = chain;
257 return chainmaps > 0;
259 public StructureSelectionManager getSsm()
265 * Returns the i'th PDBEntry (or null)
270 public PDBEntry getPdbEntry(int i)
272 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
276 * Answers true if this binding includes the given PDB id, else false
281 public boolean hasPdbId(String pdbId)
283 if (pdbEntry != null)
285 for (PDBEntry pdb : pdbEntry)
287 if (pdb.getId().equals(pdbId))
297 * Returns the number of modelled PDB file entries.
301 public int getPdbCount()
303 return pdbEntry == null ? 0 : pdbEntry.length;
306 public SequenceI[][] getSequence()
311 public String[][] getChains()
316 public DataSourceType getProtocol()
321 // TODO may remove this if calling methods can be pulled up here
322 protected void setPdbentry(PDBEntry[] pdbentry)
324 this.pdbEntry = pdbentry;
327 protected void setSequence(SequenceI[][] sequence)
329 this.sequence = sequence;
332 protected void setChains(String[][] chains)
334 this.chains = chains;
338 * Construct a title string for the viewer window based on the data Jalview
347 public String getViewerTitle(String viewerName, boolean verbose)
349 if (getSequence() == null || getSequence().length < 1
350 || getPdbCount() < 1 || getSequence()[0].length < 1)
352 return ("Jalview " + viewerName + " Window");
354 // TODO: give a more informative title when multiple structures are
356 StringBuilder title = new StringBuilder(64);
357 final PDBEntry pdbe = getPdbEntry(0);
358 title.append(viewerName + " view for " + getSequence()[0][0].getName()
359 + ":" + pdbe.getId());
363 String method = (String) pdbe.getProperty("method");
366 title.append(" Method: ").append(method);
368 String chain = (String) pdbe.getProperty("chains");
371 title.append(" Chain:").append(chain);
374 return title.toString();
378 * Called by after closeViewer is called, to release any resources and
379 * references so they can be garbage collected. Override if needed.
381 protected void releaseUIResources()
386 public void releaseReferences(Object svl)
390 public boolean isColourBySequence()
392 return colourBySequence;
396 * Called when the binding thinks the UI needs to be refreshed after a
397 * structure viewer state change. This could be because structures were
398 * loaded, or because an error has occurred. Default does nothing, override as
401 public void refreshGUI()
406 * Instruct the Jalview binding to update the pdbentries vector if necessary
407 * prior to matching the jmol view's contents to the list of structure files
408 * Jalview knows about. By default does nothing, override as required.
410 public void refreshPdbEntries()
414 public void setColourBySequence(boolean colourBySequence)
416 this.colourBySequence = colourBySequence;
419 protected void addSequenceAndChain(int pe, SequenceI[] seq,
422 if (pe < 0 || pe >= getPdbCount())
424 throw new Error(MessageManager.formatMessage(
425 "error.implementation_error_no_pdbentry_from_index",
427 { Integer.valueOf(pe).toString() }));
429 final String nullChain = "TheNullChain";
430 List<SequenceI> s = new ArrayList<>();
431 List<String> c = new ArrayList<>();
432 if (getChains() == null)
434 setChains(new String[getPdbCount()][]);
436 if (getSequence()[pe] != null)
438 for (int i = 0; i < getSequence()[pe].length; i++)
440 s.add(getSequence()[pe][i]);
441 if (getChains()[pe] != null)
443 if (i < getChains()[pe].length)
445 c.add(getChains()[pe][i]);
454 if (tchain != null && tchain.length > 0)
461 for (int i = 0; i < seq.length; i++)
463 if (!s.contains(seq[i]))
466 if (tchain != null && i < tchain.length)
468 c.add(tchain[i] == null ? nullChain : tchain[i]);
472 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
473 getSequence()[pe] = tmp;
476 String[] tch = c.toArray(new String[c.size()]);
477 for (int i = 0; i < tch.length; i++)
479 if (tch[i] == nullChain)
484 getChains()[pe] = tch;
488 getChains()[pe] = null;
493 * add structures and any known sequence associations
495 * @returns the pdb entries added to the current set.
497 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
498 SequenceI[][] seq, String[][] chns)
500 List<PDBEntry> v = new ArrayList<>();
501 List<int[]> rtn = new ArrayList<>();
502 for (int i = 0; i < getPdbCount(); i++)
504 v.add(getPdbEntry(i));
506 for (int i = 0; i < pdbe.length; i++)
508 int r = v.indexOf(pdbe[i]);
509 if (r == -1 || r >= getPdbCount())
511 rtn.add(new int[] { v.size(), i });
516 // just make sure the sequence/chain entries are all up to date
517 addSequenceAndChain(r, seq[i], chns[i]);
520 pdbe = v.toArray(new PDBEntry[v.size()]);
524 // expand the tied sequence[] and string[] arrays
525 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
526 String[][] sch = new String[getPdbCount()][];
527 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
528 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
531 pdbe = new PDBEntry[rtn.size()];
532 for (int r = 0; r < pdbe.length; r++)
534 int[] stri = (rtn.get(r));
535 // record the pdb file as a new addition
536 pdbe[r] = getPdbEntry(stri[0]);
537 // and add the new sequence/chain entries
538 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
549 * Add sequences to the pe'th pdbentry's sequence set.
554 public void addSequence(int pe, SequenceI[] seq)
556 addSequenceAndChain(pe, seq, null);
560 * add the given sequences to the mapping scope for the given pdb file handle
563 * - pdbFile identifier
565 * - set of sequences it can be mapped to
567 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
569 for (int pe = 0; pe < getPdbCount(); pe++)
571 if (getPdbEntry(pe).getFile().equals(pdbFile))
573 addSequence(pe, seq);
579 public abstract void highlightAtoms(List<AtomSpec> atoms);
581 protected boolean isNucleotide()
583 return this.nucleotide;
587 * Returns a readable description of all mappings for the wrapped pdbfile to
588 * any mapped sequences
594 public String printMappings()
596 if (pdbEntry == null)
600 StringBuilder sb = new StringBuilder(128);
601 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
603 String pdbfile = getPdbEntry(pdbe).getFile();
604 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
605 sb.append(getSsm().printMappings(pdbfile, seqs));
607 return sb.toString();
611 * Returns the mapped structure position for a given aligned column of a given
612 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
613 * not mapped to structure.
620 protected int getMappedPosition(SequenceI seq, int alignedPos,
621 StructureMapping mapping)
623 if (alignedPos >= seq.getLength())
628 if (Comparison.isGap(seq.getCharAt(alignedPos)))
632 int seqPos = seq.findPosition(alignedPos);
633 int pos = mapping.getPDBResNum(seqPos);
638 * Helper method to identify residues that can participate in a structure
639 * superposition command. For each structure, identify a sequence in the
640 * alignment which is mapped to the structure. Identify non-gapped columns in
641 * the sequence which have a mapping to a residue in the structure. Returns
642 * the index of the first structure that has a mapping to the alignment.
645 * the sequence alignment which is the basis of structure
648 * a BitSet, where bit j is set to indicate that every structure has
649 * a mapped residue present in column j (so the column can
650 * participate in structure alignment)
652 * an array of data beans corresponding to pdb file index
655 protected int findSuperposableResidues(AlignmentI alignment,
656 BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
658 int refStructure = -1;
659 String[] files = getStructureFiles();
664 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
666 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
670 * Find the first mapped sequence (if any) for this PDB entry which is in
673 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
674 for (int s = 0; s < seqCountForPdbFile; s++)
676 for (StructureMapping mapping : mappings)
678 final SequenceI theSequence = getSequence()[pdbfnum][s];
679 if (mapping.getSequence() == theSequence
680 && alignment.findIndex(theSequence) > -1)
682 if (refStructure < 0)
684 refStructure = pdbfnum;
686 for (int r = 0; r < alignment.getWidth(); r++)
692 int pos = getMappedPosition(theSequence, r, mapping);
693 if (pos < 1 || pos == lastPos)
699 structures[pdbfnum].pdbResNo[r] = pos;
701 String chain = mapping.getChain();
702 if (chain != null && chain.trim().length() > 0)
704 structures[pdbfnum].chain = chain;
706 structures[pdbfnum].pdbId = mapping.getPdbId();
707 structures[pdbfnum].isRna = theSequence.getRNA() != null;
710 * move on to next pdb file (ignore sequences for other chains
711 * for the same structure)
713 s = seqCountForPdbFile;
714 break; // fixme break out of two loops here!
723 * Returns true if the structure viewer has loaded all of the files of
724 * interest (identified by the file mapping having been set up), or false if
725 * any are still not loaded after a timeout interval.
729 protected boolean waitForFileLoad(String[] files)
732 * give up after 10 secs plus 1 sec per file
734 long starttime = System.currentTimeMillis();
735 long endTime = 10000 + 1000 * files.length + starttime;
736 String notLoaded = null;
738 boolean waiting = true;
739 while (waiting && System.currentTimeMillis() < endTime)
742 for (String file : files)
751 StructureMapping[] sm = getSsm().getMapping(file);
752 if (sm == null || sm.length == 0)
756 } catch (Throwable x)
766 "Timed out waiting for structure viewer to load file "
774 public boolean isListeningFor(SequenceI seq)
776 if (sequence != null)
778 for (SequenceI[] seqs : sequence)
782 for (SequenceI s : seqs)
784 if (s == seq || (s.getDatasetSequence() != null
785 && s.getDatasetSequence() == seq.getDatasetSequence()))
796 public boolean isFinishedInit()
801 public void setFinishedInit(boolean fi)
803 this.finishedInit = fi;
807 * Returns a list of chains mapped in this viewer, formatted as
812 public List<String> getChainNames()
818 * Returns the Jalview panel hosting the structure viewer (if any)
822 public JalviewStructureDisplayI getViewer()
827 public void setViewer(JalviewStructureDisplayI v)
833 * Constructs and sends a command to align structures against a reference
834 * structure, based on one or more sequence alignments. May optionally return
835 * an error or warning message for the alignment command(s).
838 * an array of one or more alignment views to process
841 public String superposeStructures(List<AlignmentViewPanel> alignWith)
844 String[] files = getStructureFiles();
846 if (!waitForFileLoad(files))
852 for (AlignmentViewPanel view : alignWith)
854 AlignmentI alignment = view.getAlignment();
855 HiddenColumns hiddenCols = alignment.getHiddenColumns();
858 * 'matched' bit i will be set for visible alignment columns i where
859 * all sequences have a residue with a mapping to their PDB structure
861 BitSet matched = new BitSet();
862 final int width = alignment.getWidth();
863 for (int m = 0; m < width; m++)
865 if (hiddenCols == null || hiddenCols.isVisible(m))
871 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
872 for (int f = 0; f < files.length; f++)
874 structures[f] = new AAStructureBindingModel.SuperposeData(width,
875 getModelIdForFile(files[f]));
879 * Calculate the superposable alignment columns ('matched'), and the
880 * corresponding structure residue positions (structures.pdbResNo)
882 int refStructure = findSuperposableResidues(alignment,
883 matched, structures);
886 * require at least 4 positions to be able to execute superposition
888 int nmatched = matched.cardinality();
889 if (nmatched < MIN_POS_TO_SUPERPOSE)
891 String msg = MessageManager.formatMessage("label.insufficient_residues",
893 error += view.getViewName() + ": " + msg + "; ";
898 * get a model of the superposable residues in the reference structure
900 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
904 * Show all as backbone before doing superposition(s)
905 * (residues used for matching will be shown as ribbon)
907 // todo better way to ensure synchronous than setting getReply true!!
908 executeCommands(commandGenerator.showBackbone(), true, null);
911 * superpose each (other) structure to the reference in turn
913 for (int i = 0; i < structures.length; i++)
915 if (i != refStructure)
917 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
918 List<StructureCommandI> commands = commandGenerator
919 .superposeStructures(refAtoms, atomSpec);
920 List<String> replies = executeCommands(commands, true, null);
921 for (String reply : replies)
923 // return this error (Chimera only) to the user
924 if (reply.toLowerCase().contains("unequal numbers of atoms"))
926 error += "; " + reply;
936 private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
939 AtomSpecModel model = new AtomSpecModel();
940 int nextColumnMatch = matched.nextSetBit(0);
941 while (nextColumnMatch != -1)
943 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
944 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
945 superposeData.chain);
946 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
953 * returns the current sequenceRenderer that should be used to colour the
960 public abstract SequenceRenderer getSequenceRenderer(
961 AlignmentViewPanel alignment);
964 * Sends a command to the structure viewer to colour each chain with a
965 * distinct colour (to the extent supported by the viewer)
967 public void colourByChain()
969 colourBySequence = false;
971 // TODO: JAL-628 colour chains distinctly across all visible models
973 executeCommand(commandGenerator.colourByChain(), false,
974 COLOURING_STRUCTURES);
978 * Sends a command to the structure viewer to colour each chain with a
979 * distinct colour (to the extent supported by the viewer)
981 public void colourByCharge()
983 colourBySequence = false;
985 executeCommands(commandGenerator.colourByCharge(), false,
986 COLOURING_STRUCTURES);
990 * Sends a command to the structure to apply a colour scheme (defined in
991 * Jalview but not necessarily applied to the alignment), which defines a
992 * colour per residue letter. More complex schemes (e.g. that depend on
993 * consensus) cannot be used here and are ignored.
997 public void colourByJalviewColourScheme(ColourSchemeI cs)
999 colourBySequence = false;
1001 if (cs == null || !cs.isSimple())
1007 * build a map of {Residue3LetterCode, Color}
1009 Map<String, Color> colours = new HashMap<>();
1010 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1012 for (String resName : residues)
1014 char res = resName.length() == 3
1015 ? ResidueProperties.getSingleCharacterCode(resName)
1016 : resName.charAt(0);
1017 Color colour = cs.findColour(res, 0, null, null, 0f);
1018 colours.put(resName, colour);
1022 * pass to the command constructor, and send the command
1024 List<StructureCommandI> cmd = commandGenerator
1025 .colourByResidues(colours);
1026 executeCommands(cmd, false, COLOURING_STRUCTURES);
1029 public void setBackgroundColour(Color col)
1031 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1032 executeCommand(cmd, false, null);
1036 * Sends one command to the structure viewer. If {@code getReply} is true, the
1037 * command is sent synchronously, otherwise in a deferred thread.
1039 * If a progress message is supplied, this is displayed before command
1040 * execution, and removed afterwards.
1047 private List<String> executeCommand(StructureCommandI cmd,
1048 boolean getReply, String msg)
1053 * synchronous (same thread) execution so reply can be returned
1055 final JalviewStructureDisplayI theViewer = getViewer();
1056 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1059 return executeCommand(cmd, getReply);
1064 theViewer.stopProgressBar(null, handle);
1071 * asynchronous (new thread) execution if no reply needed
1073 final JalviewStructureDisplayI theViewer = getViewer();
1074 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1076 SwingUtilities.invokeLater(new Runnable()
1083 executeCommand(cmd, false);
1088 theViewer.stopProgressBar(null, handle);
1098 * Execute one structure viewer command. If {@code getReply} is true, may
1099 * optionally return one or more reply messages, else returns null.
1104 protected abstract List<String> executeCommand(StructureCommandI cmd,
1108 * A helper method that converts list of commands to a vararg array
1114 private List<String> executeCommands(List<StructureCommandI> commands,
1115 boolean getReply, String msg)
1117 return executeCommands(getReply, msg,
1118 commands.toArray(new StructureCommandI[commands.size()]));
1122 * Executes one or more structure viewer commands. If a progress message is
1123 * provided, it is shown first, and removed after all commands have been run.
1130 protected List<String> executeCommands(boolean getReply, String msg,
1131 StructureCommandI[] commands)
1133 // todo: tidy this up
1136 * show progress message if specified
1138 final JalviewStructureDisplayI theViewer = getViewer();
1139 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1141 List<String> response = getReply ? new ArrayList<>() : null;
1144 for (StructureCommandI cmd : commands)
1146 List<String> replies = executeCommand(cmd, getReply, null);
1147 if (getReply && replies != null)
1149 response.addAll(replies);
1157 theViewer.stopProgressBar(null, handle);
1163 * colour any structures associated with sequences in the given alignment
1164 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
1165 * if colourBySequence is enabled.
1167 public void colourBySequence(AlignmentViewPanel alignmentv)
1169 if (!colourBySequence || !isLoadingFinished())
1173 if (getSsm() == null)
1177 String[] files = getStructureFiles();
1179 SequenceRenderer sr = getSequenceRenderer(alignmentv);
1180 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, files,
1181 sequence, sr, alignmentv);
1183 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1184 .colourBySequence(colourMap);
1185 executeCommands(colourBySequenceCommands, false, null);
1189 * Centre the display in the structure viewer
1191 public void focusView()
1193 executeCommand(commandGenerator.focusView(), false, null);
1197 * Generates and executes a command to show only specified chains in the
1198 * structure viewer. The list of chains to show should contain entries
1199 * formatted as "pdbid:chaincode".
1203 public void showChains(List<String> toShow)
1205 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1208 * Reformat the pdbid:chainCode values as modelNo:chainCode
1209 * since this is what is needed to construct the viewer command
1210 * todo: find a less messy way to do this
1212 List<String> showThese = new ArrayList<>();
1213 for (String chainId : toShow)
1215 String[] tokens = chainId.split("\\:");
1216 if (tokens.length == 2)
1218 String pdbFile = getFileForChain(chainId);
1219 String model = getModelIdForFile(pdbFile);
1220 showThese.add(model + ":" + tokens[1]);
1223 executeCommands(commandGenerator.showChains(showThese), false, null);
1227 * Answers the structure viewer's model id given a PDB file name. Returns an
1228 * empty string if model id is not found.
1233 protected abstract String getModelIdForFile(String chainId);
1235 public boolean hasFileLoadingError()
1237 return fileLoadingError != null && fileLoadingError.length() > 0;
1241 * Returns the FeatureRenderer for the given alignment view, or null if
1242 * feature display is turned off in the view.
1247 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1249 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1251 return ap.getAlignViewport().isShowSequenceFeatures()
1252 ? ap.getFeatureRenderer()
1256 protected void setStructureCommands(StructureCommandsI cmd)
1258 commandGenerator = cmd;
1262 * Records association of one chain id (formatted as "pdbid:chainCode") with
1263 * the corresponding PDB file name
1268 public void addChainFile(String chainId, String fileName)
1270 chainFile.put(chainId, fileName);
1274 * Returns the PDB filename for the given chain id (formatted as
1275 * "pdbid:chainCode"), or null if not found
1280 protected String getFileForChain(String chainId)
1282 return chainFile.get(chainId);
1286 public void updateColours(Object source)
1288 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1289 // ignore events from panels not used to colour this view
1290 if (!getViewer().isUsedForColourBy(ap))
1294 if (!isLoadingFromArchive())
1296 colourBySequence(ap);
1300 public StructureCommandsI getCommandGenerator()
1302 return commandGenerator;
1305 protected abstract ViewerType getViewerType();
1308 * Send a structure viewer command asynchronously in a new thread. If the
1309 * progress message is not null, display this message while the command is
1313 * @param progressMsg
1315 protected void sendAsynchronousCommand(StructureCommandI command,
1318 final JalviewStructureDisplayI theViewer = getViewer();
1319 final long handle = progressMsg == null ? 0
1320 : theViewer.startProgressBar(progressMsg);
1321 SwingUtilities.invokeLater(new Runnable()
1328 executeCommand(command, false, null);
1331 if (progressMsg != null)
1333 theViewer.stopProgressBar(null, handle);
1342 * Builds a data structure which records mapped structure residues for each
1343 * colour. From this we can easily generate the viewer commands for colour by
1344 * sequence. Constructs and returns a map of {@code Color} to
1345 * {@code AtomSpecModel}, where the atomspec model holds
1353 * Ordering is by order of addition (for colours), natural ordering (for
1354 * models and chains)
1363 protected Map<Object, AtomSpecModel> buildColoursMap(
1364 StructureSelectionManager ssm, String[] files,
1365 SequenceI[][] sequence, SequenceRenderer sr, AlignmentViewPanel viewPanel)
1367 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1368 FeatureColourFinder finder = new FeatureColourFinder(fr);
1369 AlignViewportI viewport = viewPanel.getAlignViewport();
1370 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1371 AlignmentI al = viewport.getAlignment();
1372 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1373 Color lastColour = null;
1375 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1377 final String modelId = getModelIdForFile(files[pdbfnum]);
1378 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1380 if (mapping == null || mapping.length < 1)
1385 int startPos = -1, lastPos = -1;
1386 String lastChain = "";
1387 for (int s = 0; s < sequence[pdbfnum].length; s++)
1389 for (int sp, m = 0; m < mapping.length; m++)
1391 final SequenceI seq = sequence[pdbfnum][s];
1392 if (mapping[m].getSequence() == seq
1393 && (sp = al.findIndex(seq)) > -1)
1395 SequenceI asp = al.getSequenceAt(sp);
1396 for (int r = 0; r < asp.getLength(); r++)
1398 // no mapping to gaps in sequence
1399 if (Comparison.isGap(asp.getCharAt(r)))
1403 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1405 if (pos < 1 || pos == lastPos)
1410 Color colour = sr.getResidueColour(seq, r, finder);
1413 * darker colour for hidden regions
1415 if (!cs.isVisible(r))
1417 colour = Color.GRAY;
1420 final String chain = mapping[m].getChain();
1423 * Just keep incrementing the end position for this colour range
1424 * _unless_ colour, PDB model or chain has changed, or there is a
1425 * gap in the mapped residue sequence
1427 final boolean newColour = !colour.equals(lastColour);
1428 final boolean nonContig = lastPos + 1 != pos;
1429 final boolean newChain = !chain.equals(lastChain);
1430 if (newColour || nonContig || newChain)
1434 addAtomSpecRange(colourMap, lastColour, modelId,
1435 startPos, lastPos, lastChain);
1439 lastColour = colour;
1443 // final colour range
1444 if (lastColour != null)
1446 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1447 lastPos, lastChain);
1458 * todo better refactoring (map lookup or similar to get viewer structure id)
1464 protected String getModelId(int pdbfnum, String file)
1466 return String.valueOf(pdbfnum);
1470 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1471 * full PDB file path
1476 public void stashFoundChains(StructureFile pdb, String file)
1478 for (int i = 0; i < pdb.getChains().size(); i++)
1480 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1481 addChainFile(chid, file);
1482 getChainNames().add(chid);
1487 * Helper method to add one contiguous range to the AtomSpec model for the given
1488 * value (creating the model if necessary). As used by Jalview, {@code value} is
1490 * <li>a colour, when building a 'colour structure by sequence' command</li>
1491 * <li>a feature value, when building a 'set Chimera attributes from features'
1502 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1504 String model, int startPos, int endPos, String chain)
1507 * Get/initialize map of data for the colour
1509 AtomSpecModel atomSpec = map.get(value);
1510 if (atomSpec == null)
1512 atomSpec = new AtomSpecModel();
1513 map.put(value, atomSpec);
1516 atomSpec.addRange(model, startPos, endPos, chain);
1520 * Returns the file extension (including '.' separator) to use for a saved
1521 * viewer session file. Default is to return null (not supported), override as
1526 public String getSessionFileExtension()
1532 * If supported, saves the state of the structure viewer to a temporary file
1533 * and returns the file. Returns null and logs an error on any failure.
1537 public File saveSession()
1539 String prefix = getViewerType().toString();
1540 String suffix = getSessionFileExtension();
1544 f = File.createTempFile(prefix, suffix);
1546 } catch (IOException e)
1548 Cache.log.error(String.format("Error saving %s session: %s",
1549 prefix, e.toString()));
1556 * Saves the structure viewer session to the given file
1560 protected void saveSession(File f)
1562 StructureCommandI cmd = commandGenerator
1563 .saveSession(f.getPath());
1566 executeCommand(cmd, false);
1571 * Returns true if the viewer is an external structure viewer for which the
1572 * process is still alive, else false (for Jmol, or an external viewer which
1573 * the user has independently closed)
1577 public boolean isViewerRunning()
1583 * Closes Jalview's structure viewer panel and releases associated resources.
1584 * If it is managing an external viewer program, and {@code forceClose} is
1585 * true, also shuts down that program.
1589 public void closeViewer(boolean forceClose)
1591 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1592 releaseUIResources();
1594 // add external viewer shutdown in overrides
1595 // todo - or can maybe pull up to here