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;
32 import java.util.Locale;
35 import javax.swing.SwingUtilities;
37 import jalview.api.AlignViewportI;
38 import jalview.api.AlignmentViewPanel;
39 import jalview.api.FeatureRenderer;
40 import jalview.api.SequenceRenderer;
41 import jalview.api.StructureSelectionManagerProvider;
42 import jalview.api.structures.JalviewStructureDisplayI;
43 import jalview.bin.Console;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.ColumnSelection;
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.StructureCommandsI.AtomSpecType;
65 import jalview.structure.StructureListener;
66 import jalview.structure.StructureMapping;
67 import jalview.structure.StructureSelectionManager;
68 import jalview.util.Comparison;
69 import jalview.util.MessageManager;
73 * A base class to hold common function for 3D structure model binding. Initial
74 * version created by refactoring JMol and Chimera binding models, but other
75 * structure viewers could in principle be accommodated in future.
80 public abstract class AAStructureBindingModel
81 extends SequenceStructureBindingModel
82 implements StructureListener, StructureSelectionManagerProvider
85 * Data bean class to simplify parameterisation in superposeStructures
87 public static class SuperposeData
89 public String filename;
93 public String chain = "";
96 * is the mapped sequence not protein ?
101 * The pdb residue number (if any) mapped to columns of the alignment
103 public int[] pdbResNo; // or use SparseIntArray?
105 public String modelId;
111 * width of alignment (number of columns that may potentially
112 * participate in superposition)
114 * structure viewer model number
116 public SuperposeData(int width, String model)
118 pdbResNo = new int[width];
123 private static final int MIN_POS_TO_SUPERPOSE = 4;
125 private static final String COLOURING_STRUCTURES = MessageManager
126 .getString("status.colouring_structures");
129 * the Jalview panel through which the user interacts
130 * with the structure viewer
132 private JalviewStructureDisplayI viewer;
135 * helper that generates command syntax
137 private StructureCommandsI commandGenerator;
139 private StructureSelectionManager ssm;
142 * modelled chains, formatted as "pdbid:chainCode"
144 private List<String> chainNames;
147 * lookup of pdb file name by key "pdbid:chainCode"
149 private Map<String, String> chainFile;
152 * distinct PDB entries (pdb files) associated
155 private PDBEntry[] pdbEntry;
158 * sequences mapped to each pdbentry
160 private SequenceI[][] sequence;
163 * array of target chains for sequences - tied to pdbentry and sequence[]
165 private String[][] chains;
168 * datasource protocol for access to PDBEntrylatest
170 DataSourceType protocol = null;
172 protected boolean colourBySequence = true;
175 * true if all sequences appear to be nucleotide
177 private boolean nucleotide;
179 private boolean finishedInit = false;
182 * current set of model filenames loaded in the viewer
184 protected String[] modelFileNames = null;
186 public String fileLoadingError;
188 protected Thread externalViewerMonitor;
196 public AAStructureBindingModel(StructureSelectionManager ssm,
200 this.sequence = seqs;
201 chainNames = new ArrayList<>();
202 chainFile = new HashMap<>();
213 public AAStructureBindingModel(StructureSelectionManager ssm,
214 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
215 DataSourceType protocol)
217 this(ssm, sequenceIs);
218 this.nucleotide = Comparison.isNucleotide(sequenceIs);
219 this.pdbEntry = pdbentry;
220 this.protocol = protocol;
224 private boolean resolveChains()
227 * final count of chain mappings discovered
230 // JBPNote: JAL-2693 - this should be a list of chain mappings per
231 // [pdbentry][sequence]
232 String[][] newchains = new String[pdbEntry.length][];
234 for (PDBEntry pdb : pdbEntry)
236 SequenceI[] seqsForPdb = sequence[pe];
237 if (seqsForPdb != null)
239 newchains[pe] = new String[seqsForPdb.length];
241 for (SequenceI asq : seqsForPdb)
243 String chain = (chains != null && chains[pe] != null)
246 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
247 : asq.getDatasetSequence();
248 if (sq.getAllPDBEntries() != null)
250 for (PDBEntry pdbentry : sq.getAllPDBEntries())
252 if (pdb.getFile() != null && pdbentry.getFile() != null
253 && pdb.getFile().equals(pdbentry.getFile()))
255 String chaincode = pdbentry.getChainCode();
256 if (chaincode != null && chaincode.length() > 0)
265 newchains[pe][se] = chain;
273 return chainmaps > 0;
276 public StructureSelectionManager getSsm()
282 * Returns the i'th PDBEntry (or null)
287 public PDBEntry getPdbEntry(int i)
289 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
293 * Answers true if this binding includes the given PDB id, else false
298 public boolean hasPdbId(String pdbId)
300 if (pdbEntry != null)
302 for (PDBEntry pdb : pdbEntry)
304 if (pdb.getId().equals(pdbId))
314 * Returns the number of modelled PDB file entries.
318 public int getPdbCount()
320 return pdbEntry == null ? 0 : pdbEntry.length;
323 public SequenceI[][] getSequence()
328 public String[][] getChains()
333 public DataSourceType getProtocol()
338 // TODO may remove this if calling methods can be pulled up here
339 protected void setPdbentry(PDBEntry[] pdbentry)
341 this.pdbEntry = pdbentry;
344 protected void setSequence(SequenceI[][] sequence)
346 this.sequence = sequence;
349 protected void setChains(String[][] chains)
351 this.chains = chains;
355 * Construct a title string for the viewer window based on the data Jalview
364 public String getViewerTitle(String viewerName, boolean verbose)
366 if (getSequence() == null || getSequence().length < 1
367 || getPdbCount() < 1 || getSequence()[0].length < 1)
369 return ("Jalview " + viewerName + " Window");
371 // TODO: give a more informative title when multiple structures are
373 StringBuilder title = new StringBuilder(64);
374 final PDBEntry pdbe = getPdbEntry(0);
375 title.append(viewerName + " view for " + getSequence()[0][0].getName()
376 + ":" + pdbe.getId());
380 String method = (String) pdbe.getProperty("method");
383 title.append(" Method: ").append(method);
385 String chain = (String) pdbe.getProperty("chains");
388 title.append(" Chain:").append(chain);
391 return title.toString();
395 * Called by after closeViewer is called, to release any resources and
396 * references so they can be garbage collected. Override if needed.
398 protected void releaseUIResources()
403 public void releaseReferences(Object svl)
407 public boolean isColourBySequence()
409 return colourBySequence;
413 * Called when the binding thinks the UI needs to be refreshed after a
414 * structure viewer state change. This could be because structures were
415 * loaded, or because an error has occurred. Default does nothing, override as
418 public void refreshGUI()
423 * Instruct the Jalview binding to update the pdbentries vector if necessary
424 * prior to matching the jmol view's contents to the list of structure files
425 * Jalview knows about. By default does nothing, override as required.
427 public void refreshPdbEntries()
431 public void setColourBySequence(boolean colourBySequence)
433 this.colourBySequence = colourBySequence;
436 protected void addSequenceAndChain(int pe, SequenceI[] seq,
439 if (pe < 0 || pe >= getPdbCount())
441 throw new Error(MessageManager.formatMessage(
442 "error.implementation_error_no_pdbentry_from_index",
444 { Integer.valueOf(pe).toString() }));
446 final String nullChain = "TheNullChain";
447 List<SequenceI> s = new ArrayList<>();
448 List<String> c = new ArrayList<>();
449 if (getChains() == null)
451 setChains(new String[getPdbCount()][]);
453 if (getSequence()[pe] != null)
455 for (int i = 0; i < getSequence()[pe].length; i++)
457 s.add(getSequence()[pe][i]);
458 if (getChains()[pe] != null)
460 if (i < getChains()[pe].length)
462 c.add(getChains()[pe][i]);
471 if (tchain != null && tchain.length > 0)
478 for (int i = 0; i < seq.length; i++)
480 if (!s.contains(seq[i]))
483 if (tchain != null && i < tchain.length)
485 c.add(tchain[i] == null ? nullChain : tchain[i]);
489 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
490 getSequence()[pe] = tmp;
493 String[] tch = c.toArray(new String[c.size()]);
494 for (int i = 0; i < tch.length; i++)
496 if (tch[i] == nullChain)
501 getChains()[pe] = tch;
505 getChains()[pe] = null;
510 * add structures and any known sequence associations
512 * @returns the pdb entries added to the current set.
514 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
515 SequenceI[][] seq, String[][] chns)
517 List<PDBEntry> v = new ArrayList<>();
518 List<int[]> rtn = new ArrayList<>();
519 for (int i = 0; i < getPdbCount(); i++)
521 v.add(getPdbEntry(i));
523 for (int i = 0; i < pdbe.length; i++)
525 int r = v.indexOf(pdbe[i]);
526 if (r == -1 || r >= getPdbCount())
528 rtn.add(new int[] { v.size(), i });
533 // just make sure the sequence/chain entries are all up to date
534 addSequenceAndChain(r, seq[i], chns[i]);
537 pdbe = v.toArray(new PDBEntry[v.size()]);
541 // expand the tied sequence[] and string[] arrays
542 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
543 String[][] sch = new String[getPdbCount()][];
544 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
545 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
548 pdbe = new PDBEntry[rtn.size()];
549 for (int r = 0; r < pdbe.length; r++)
551 int[] stri = (rtn.get(r));
552 // record the pdb file as a new addition
553 pdbe[r] = getPdbEntry(stri[0]);
554 // and add the new sequence/chain entries
555 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
566 * Add sequences to the pe'th pdbentry's sequence set.
571 public void addSequence(int pe, SequenceI[] seq)
573 addSequenceAndChain(pe, seq, null);
577 * add the given sequences to the mapping scope for the given pdb file handle
580 * - pdbFile identifier
582 * - set of sequences it can be mapped to
584 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
586 for (int pe = 0; pe < getPdbCount(); pe++)
588 if (getPdbEntry(pe).getFile().equals(pdbFile))
590 addSequence(pe, seq);
596 public abstract void highlightAtoms(List<AtomSpec> atoms);
598 protected boolean isNucleotide()
600 return this.nucleotide;
604 * Returns a readable description of all mappings for the wrapped pdbfile to
605 * any mapped sequences
611 public String printMappings()
613 if (pdbEntry == null)
617 StringBuilder sb = new StringBuilder(128);
618 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
620 String pdbfile = getPdbEntry(pdbe).getFile();
621 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
622 sb.append(getSsm().printMappings(pdbfile, seqs));
624 return sb.toString();
628 * Returns the mapped structure position for a given aligned column of a given
629 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
630 * not mapped to structure.
637 protected int getMappedPosition(SequenceI seq, int alignedPos,
638 StructureMapping mapping)
640 if (alignedPos >= seq.getLength())
645 if (Comparison.isGap(seq.getCharAt(alignedPos)))
649 int seqPos = seq.findPosition(alignedPos);
650 int pos = mapping.getPDBResNum(seqPos);
655 * Helper method to identify residues that can participate in a structure
656 * superposition command. For each structure, identify a sequence in the
657 * alignment which is mapped to the structure. Identify non-gapped columns in
658 * the sequence which have a mapping to a residue in the structure. Returns
659 * the index of the first structure that has a mapping to the alignment.
662 * the sequence alignment which is the basis of structure
665 * a BitSet, where bit j is set to indicate that every structure has
666 * a mapped residue present in column j (so the column can
667 * participate in structure alignment)
669 * an array of data beans corresponding to pdb file index
672 protected int findSuperposableResidues(AlignmentI alignment,
674 AAStructureBindingModel.SuperposeData[] structures)
676 int refStructure = -1;
677 String[] files = getStructureFiles();
682 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
684 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
688 * Find the first mapped sequence (if any) for this PDB entry which is in
691 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
692 for (int s = 0; s < seqCountForPdbFile; s++)
694 for (StructureMapping mapping : mappings)
696 final SequenceI theSequence = getSequence()[pdbfnum][s];
697 if (mapping.getSequence() == theSequence
698 && alignment.findIndex(theSequence) > -1)
700 if (refStructure < 0)
702 refStructure = pdbfnum;
704 for (int r = 0; r < alignment.getWidth(); r++)
710 int pos = getMappedPosition(theSequence, r, mapping);
711 if (pos < 1 || pos == lastPos)
717 structures[pdbfnum].pdbResNo[r] = pos;
719 String chain = mapping.getChain();
720 if (chain != null && chain.trim().length() > 0)
722 structures[pdbfnum].chain = chain;
724 structures[pdbfnum].pdbId = mapping.getPdbId();
725 structures[pdbfnum].isRna = !theSequence.isProtein();
728 * move on to next pdb file (ignore sequences for other chains
729 * for the same structure)
731 s = seqCountForPdbFile;
732 break; // fixme break out of two loops here!
741 * Returns true if the structure viewer has loaded all of the files of
742 * interest (identified by the file mapping having been set up), or false if
743 * any are still not loaded after a timeout interval.
747 protected boolean waitForFileLoad(String[] files)
750 * give up after 10 secs plus 1 sec per file
752 long starttime = System.currentTimeMillis();
753 long endTime = 10000 + 1000 * files.length + starttime;
754 String notLoaded = null;
756 boolean waiting = true;
757 while (waiting && System.currentTimeMillis() < endTime)
760 for (String file : files)
769 StructureMapping[] sm = getSsm().getMapping(file);
770 if (sm == null || sm.length == 0)
774 } catch (Throwable x)
783 jalview.bin.Console.errPrintln(
784 "Timed out waiting for structure viewer to load file "
792 public boolean isListeningFor(SequenceI seq)
794 if (sequence != null)
796 for (SequenceI[] seqs : sequence)
800 for (SequenceI s : seqs)
802 if (s == seq || (s.getDatasetSequence() != null
803 && s.getDatasetSequence() == seq.getDatasetSequence()))
814 public boolean isFinishedInit()
819 public void setFinishedInit(boolean fi)
821 this.finishedInit = fi;
825 * Returns a list of chains mapped in this viewer, formatted as
830 public List<String> getChainNames()
836 * Returns the Jalview panel hosting the structure viewer (if any)
840 public JalviewStructureDisplayI getViewer()
845 public void setViewer(JalviewStructureDisplayI v)
851 * Constructs and sends a command to align structures against a reference
852 * structure, based on one or more sequence alignments. May optionally return
853 * an error or warning message for the alignment command(s).
856 * an array of one or more alignment views to process
859 public String superposeStructures(List<AlignmentViewPanel> alignWith)
862 String[] files = getStructureFiles();
864 if (!waitForFileLoad(files))
870 for (AlignmentViewPanel view : alignWith)
872 AlignmentI alignment = view.getAlignment();
873 HiddenColumns hiddenCols = alignment.getHiddenColumns();
875 * 'matched' bit i will be set for visible alignment columns i where
876 * all sequences have a residue with a mapping to their PDB structure
878 final int width = alignment.getWidth();
879 BitSet matched = new BitSet();
880 ColumnSelection cs = view.getAlignViewport().getColumnSelection();
881 // restrict to active column selection, if there is one
882 if (cs != null && cs.hasSelectedColumns()
883 && cs.getSelected().size() >= 4)
885 for (int s : cs.getSelected())
892 for (int m = 0; m < width; m++)
894 if (hiddenCols == null || hiddenCols.isVisible(m))
900 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
901 for (int f = 0; f < files.length; f++)
903 structures[f] = new AAStructureBindingModel.SuperposeData(width,
904 getModelIdForFile(files[f]));
908 * Calculate the superposable alignment columns ('matched'), and the
909 * corresponding structure residue positions (structures.pdbResNo)
911 int refStructure = findSuperposableResidues(alignment, matched,
915 * require at least 4 positions to be able to execute superposition
917 int nmatched = matched.cardinality();
918 if (nmatched < MIN_POS_TO_SUPERPOSE)
920 String msg = MessageManager
921 .formatMessage("label.insufficient_residues", nmatched);
922 error += view.getViewName() + ": " + msg + "; ";
927 * get a model of the superposable residues in the reference structure
929 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
933 * Show all as backbone before doing superposition(s)
934 * (residues used for matching will be shown as ribbon)
936 // todo better way to ensure synchronous than setting getReply true!!
937 executeCommands(commandGenerator.showBackbone(), true, null);
939 AtomSpecType backbone = structures[refStructure].isRna
940 ? AtomSpecType.PHOSPHATE
941 : AtomSpecType.ALPHA;
942 List<AtomSpecModel> models = new ArrayList<AtomSpecModel>();
943 models.add(refAtoms);
945 * superpose each (other) structure to the reference in turn
947 for (int i = 0; i < structures.length; i++)
949 if (i != refStructure)
951 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
952 List<StructureCommandI> commands = commandGenerator
953 .superposeStructures(refAtoms, atomSpec, backbone);
954 List<String> replies = executeCommands(commands, true, null);
955 for (String reply : replies)
957 // return this error (Chimera only) to the user
958 if (reply.toLowerCase(Locale.ROOT)
959 .contains("unequal numbers of atoms"))
961 error += "; " + reply;
964 models.add(atomSpec);
967 List<StructureCommandI> finalView = commandGenerator
968 .centerViewOn(models);
969 if (finalView != null && finalView.size() > 0)
971 executeCommands(finalView, false, "Centered on Superposition");
977 private AtomSpecModel getAtomSpec(
978 AAStructureBindingModel.SuperposeData superposeData,
981 AtomSpecModel model = new AtomSpecModel();
982 int nextColumnMatch = matched.nextSetBit(0);
983 while (nextColumnMatch != -1)
985 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
986 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
987 superposeData.chain);
988 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
995 * returns the current sequenceRenderer that should be used to colour the
1002 public abstract SequenceRenderer getSequenceRenderer(
1003 AlignmentViewPanel alignment);
1006 * Sends a command to the structure viewer to colour each chain with a
1007 * distinct colour (to the extent supported by the viewer)
1009 public void colourByChain()
1011 colourBySequence = false;
1013 // TODO: JAL-628 colour chains distinctly across all visible models
1015 executeCommand(false, COLOURING_STRUCTURES,
1016 commandGenerator.colourByChain());
1020 * Sends a command to the structure viewer to colour each chain with a
1021 * distinct colour (to the extent supported by the viewer)
1023 public void colourByCharge()
1025 colourBySequence = false;
1027 executeCommands(commandGenerator.colourByCharge(), false,
1028 COLOURING_STRUCTURES);
1032 * Sends a command to the structure to apply a colour scheme (defined in
1033 * Jalview but not necessarily applied to the alignment), which defines a
1034 * colour per residue letter. More complex schemes (e.g. that depend on
1035 * consensus) cannot be used here and are ignored.
1039 public void colourByJalviewColourScheme(ColourSchemeI cs)
1041 colourBySequence = false;
1043 if (cs == null || !cs.isSimple())
1049 * build a map of {Residue3LetterCode, Color}
1051 Map<String, Color> colours = new HashMap<>();
1052 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1054 for (String resName : residues)
1056 char res = resName.length() == 3
1057 ? ResidueProperties.getSingleCharacterCode(resName)
1058 : resName.charAt(0);
1059 Color colour = cs.findColour(res, 0, null, null, 0f);
1060 colours.put(resName, colour);
1064 * pass to the command constructor, and send the command
1066 List<StructureCommandI> cmd = commandGenerator
1067 .colourByResidues(colours);
1068 executeCommands(cmd, false, COLOURING_STRUCTURES);
1071 public void setBackgroundColour(Color col)
1073 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1074 executeCommand(false, null, cmd);
1078 * Execute one structure viewer command. If {@code getReply} is true, may
1079 * optionally return one or more reply messages, else returns null.
1084 protected abstract List<String> executeCommand(StructureCommandI cmd,
1088 * Executes one or more structure viewer commands
1094 public List<String> executeCommands(List<StructureCommandI> commands,
1095 boolean getReply, String msg)
1097 return executeCommand(getReply, msg,
1098 commands.toArray(new StructureCommandI[commands.size()]));
1102 * Executes one or more structure viewer commands, optionally returning the
1103 * reply, and optionally showing a status message while the command is being
1106 * If a reply is wanted, the execution is done synchronously (waits),
1107 * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1108 * are sending commands that need to execute before later calls to
1109 * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1110 * set getReply true to ensure that commands are not executed out of order.
1117 protected List<String> executeCommand(boolean getReply, String msg,
1118 StructureCommandI... cmds)
1120 JalviewStructureDisplayI theViewer = getViewer();
1121 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1126 * execute and wait for reply
1128 List<String> response = new ArrayList<>();
1131 for (StructureCommandI cmd : cmds)
1133 List<String> replies = executeCommand(cmd, true);
1134 if (replies != null)
1136 response.addAll(replies);
1144 theViewer.stopProgressBar(null, handle);
1152 String threadName = msg == null ? "StructureCommand" : msg;
1153 new Thread(new Runnable()
1160 for (StructureCommandI cmd : cmds)
1162 executeCommand(cmd, false);
1168 SwingUtilities.invokeLater(new Runnable()
1173 theViewer.stopProgressBar(null, handle);
1179 }, threadName).start();
1184 * Colours any structures associated with sequences in the given alignment as
1185 * coloured in the alignment view, provided colourBySequence is enabled
1187 public void colourBySequence(AlignmentViewPanel alignmentv)
1189 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1193 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1196 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1197 .colourBySequence(colourMap);
1198 executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1202 * Centre the display in the structure viewer
1204 public void focusView()
1206 executeCommand(false, null, commandGenerator.focusView());
1210 * Generates and executes a command to show only specified chains in the
1211 * structure viewer. The list of chains to show should contain entries
1212 * formatted as "pdbid:chaincode".
1216 public void showChains(List<String> toShow)
1218 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1221 * Reformat the pdbid:chainCode values as modelNo:chainCode
1222 * since this is what is needed to construct the viewer command
1223 * todo: find a less messy way to do this
1225 List<String> showThese = new ArrayList<>();
1226 for (String chainId : toShow)
1228 String[] tokens = chainId.split("\\:");
1229 if (tokens.length == 2)
1231 String pdbFile = getFileForChain(chainId);
1232 String model = getModelIdForFile(pdbFile);
1233 showThese.add(model + ":" + tokens[1]);
1236 executeCommands(commandGenerator.showChains(showThese), false, null);
1240 * Answers the structure viewer's model id given a PDB file name. Returns an
1241 * empty string if model id is not found.
1246 protected abstract String getModelIdForFile(String chainId);
1248 public boolean hasFileLoadingError()
1250 return fileLoadingError != null && fileLoadingError.length() > 0;
1254 * Returns the FeatureRenderer for the given alignment view
1259 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1261 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1267 return ap.getFeatureRenderer();
1270 protected void setStructureCommands(StructureCommandsI cmd)
1272 commandGenerator = cmd;
1276 * Records association of one chain id (formatted as "pdbid:chainCode") with
1277 * the corresponding PDB file name
1282 public void addChainFile(String chainId, String fileName)
1284 chainFile.put(chainId, fileName);
1288 * Returns the PDB filename for the given chain id (formatted as
1289 * "pdbid:chainCode"), or null if not found
1294 protected String getFileForChain(String chainId)
1296 return chainFile.get(chainId);
1300 public void updateColours(Object source)
1302 if (getViewer() == null)
1304 // can happen if a viewer was not instantiated or cleaned up and is still
1305 // registered - mostly during tests
1308 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1309 // ignore events from panels not used to colour this view
1310 if (!getViewer().isUsedForColourBy(ap))
1314 if (!isLoadingFromArchive())
1316 colourBySequence(ap);
1320 public StructureCommandsI getCommandGenerator()
1322 return commandGenerator;
1325 protected abstract ViewerType getViewerType();
1328 * Builds a data structure which records mapped structure residues for each
1329 * colour. From this we can easily generate the viewer commands for colour by
1330 * sequence. Constructs and returns a map of {@code Color} to
1331 * {@code AtomSpecModel}, where the atomspec model holds
1339 * Ordering is by order of addition (for colours), natural ordering (for
1340 * models and chains)
1347 protected Map<Object, AtomSpecModel> buildColoursMap(
1348 StructureSelectionManager ssm, SequenceI[][] sequence,
1349 AlignmentViewPanel viewPanel)
1351 String[] files = getStructureFiles();
1352 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1353 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1354 FeatureColourFinder finder = new FeatureColourFinder(fr);
1355 AlignViewportI viewport = viewPanel.getAlignViewport();
1356 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1357 AlignmentI al = viewport.getAlignment();
1358 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1359 Color lastColour = null;
1361 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1363 final String modelId = getModelIdForFile(files[pdbfnum]);
1364 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1366 if (mapping == null || mapping.length < 1)
1371 int startPos = -1, lastPos = -1;
1372 String lastChain = "";
1373 for (int s = 0; s < sequence[pdbfnum].length; s++)
1375 for (int sp, m = 0; m < mapping.length; m++)
1377 final SequenceI seq = sequence[pdbfnum][s];
1378 if (mapping[m].getSequence() == seq
1379 && (sp = al.findIndex(seq)) > -1)
1381 SequenceI asp = al.getSequenceAt(sp);
1382 for (int r = 0; r < asp.getLength(); r++)
1384 // no mapping to gaps in sequence
1385 if (Comparison.isGap(asp.getCharAt(r)))
1389 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1391 if (pos < 1 || pos == lastPos)
1396 Color colour = sr.getResidueColour(seq, r, finder);
1399 * darker colour for hidden regions
1401 if (!cs.isVisible(r))
1403 colour = Color.GRAY;
1406 final String chain = mapping[m].getChain();
1409 * Just keep incrementing the end position for this colour range
1410 * _unless_ colour, PDB model or chain has changed, or there is a
1411 * gap in the mapped residue sequence
1413 final boolean newColour = !colour.equals(lastColour);
1414 final boolean nonContig = lastPos + 1 != pos;
1415 final boolean newChain = !chain.equals(lastChain);
1416 if (newColour || nonContig || newChain)
1420 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1421 lastPos, lastChain);
1425 lastColour = colour;
1429 // final colour range
1430 if (lastColour != null)
1432 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1433 lastPos, lastChain);
1444 * todo better refactoring (map lookup or similar to get viewer structure id)
1450 protected String getModelId(int pdbfnum, String file)
1452 return String.valueOf(pdbfnum);
1456 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1457 * full PDB file path
1462 public void stashFoundChains(StructureFile pdb, String file)
1464 for (int i = 0; i < pdb.getChains().size(); i++)
1466 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1467 addChainFile(chid, file);
1468 getChainNames().add(chid);
1473 * Helper method to add one contiguous range to the AtomSpec model for the
1474 * given value (creating the model if necessary). As used by Jalview,
1477 * <li>a colour, when building a 'colour structure by sequence' command</li>
1478 * <li>a feature value, when building a 'set Chimera attributes from features'
1489 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1490 Object value, String model, int startPos, int endPos,
1494 * Get/initialize map of data for the colour
1496 AtomSpecModel atomSpec = map.get(value);
1497 if (atomSpec == null)
1499 atomSpec = new AtomSpecModel();
1500 map.put(value, atomSpec);
1503 atomSpec.addRange(model, startPos, endPos, chain);
1507 * Returns the file extension (including '.' separator) to use for a saved
1508 * viewer session file. Default is to return null (not supported), override as
1513 public String getSessionFileExtension()
1519 * If supported, saves the state of the structure viewer to a temporary file
1520 * and returns the file. Returns null and logs an error on any failure.
1524 public File saveSession()
1526 String prefix = getViewerType().toString();
1527 String suffix = getSessionFileExtension();
1531 f = File.createTempFile(prefix, suffix);
1533 } catch (IOException e)
1535 Console.error(String.format("Error saving %s session: %s", prefix,
1544 * Use restoreSession when you want to restore a previously saved sesssion to
1545 * the running viewer instance.
1547 * @param absolutePath
1549 public void restoreSession(String absolutePath)
1551 String prefix = getViewerType().toString();
1554 StructureCommandI cmd = commandGenerator.restoreSession(absolutePath);
1557 executeCommand(cmd, false);
1559 } catch (Throwable e)
1561 Console.error(String.format("Error restoring %s session: %s", prefix,
1568 * Saves the structure viewer session to the given file
1572 protected void saveSession(File f)
1574 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1577 executeCommand(cmd, false);
1582 * Returns true if the viewer is an external structure viewer for which the
1583 * process is still alive, else false (for Jmol, or an external viewer which
1584 * the user has independently closed)
1588 public boolean isViewerRunning()
1594 * Closes Jalview's structure viewer panel and releases associated resources.
1595 * If it is managing an external viewer program, and {@code forceClose} is
1596 * true, also asks that program to close.
1600 public void closeViewer(boolean forceClose)
1602 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1603 releaseUIResources();
1606 * end the thread that closes this panel if the external viewer closes
1608 if (externalViewerMonitor != null)
1610 externalViewerMonitor.interrupt();
1611 externalViewerMonitor = null;
1618 StructureCommandI cmd = getCommandGenerator().closeViewer();
1621 executeCommand(cmd, false);
1627 * Returns the URL of a help page for the structure viewer, or null if none is
1632 public String getHelpURL()
1639 * Helper method to build a map of
1640 * { featureType, { feature value, AtomSpecModel } }
1646 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1647 AlignmentViewPanel viewPanel)
1649 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1650 String[] files = getStructureFiles();
1656 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1662 AlignViewportI viewport = viewPanel.getAlignViewport();
1663 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1666 * if alignment is showing features from complement, we also transfer
1667 * these features to the corresponding mapped structure residues
1669 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1670 List<String> complementFeatures = new ArrayList<>();
1671 FeatureRenderer complementRenderer = null;
1672 if (showLinkedFeatures)
1674 AlignViewportI comp = fr.getViewport().getCodingComplement();
1677 complementRenderer = Desktop.getAlignFrameFor(comp)
1678 .getFeatureRenderer();
1679 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1682 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1687 AlignmentI alignment = viewPanel.getAlignment();
1688 SequenceI[][] seqs = getSequence();
1690 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1692 String modelId = getModelIdForFile(files[pdbfnum]);
1693 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1695 if (mapping == null || mapping.length < 1)
1700 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1702 for (int m = 0; m < mapping.length; m++)
1704 final SequenceI seq = seqs[pdbfnum][seqNo];
1705 int sp = alignment.findIndex(seq);
1706 StructureMapping structureMapping = mapping[m];
1707 if (structureMapping.getSequence() == seq && sp > -1)
1710 * found a sequence with a mapping to a structure;
1711 * now scan its features
1713 if (!visibleFeatures.isEmpty())
1715 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1718 if (showLinkedFeatures)
1720 scanComplementFeatures(complementRenderer, structureMapping,
1721 seq, theMap, modelId);
1731 * Ask the structure viewer to open a session file. Returns true if
1732 * successful, else false (or not supported).
1737 public boolean openSession(String filepath)
1739 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1744 executeCommand(cmd, true);
1745 // todo: test for failure - how?
1750 * Scans visible features in mapped positions of the CDS/peptide complement,
1751 * and adds any found to the map of attribute values/structure positions
1753 * @param complementRenderer
1754 * @param structureMapping
1757 * @param modelNumber
1759 protected static void scanComplementFeatures(
1760 FeatureRenderer complementRenderer,
1761 StructureMapping structureMapping, SequenceI seq,
1762 Map<String, Map<Object, AtomSpecModel>> theMap,
1766 * for each sequence residue mapped to a structure position...
1768 for (int seqPos : structureMapping.getMapping().keySet())
1771 * find visible complementary features at mapped position(s)
1773 MappedFeatures mf = complementRenderer
1774 .findComplementFeaturesAtResidue(seq, seqPos);
1777 for (SequenceFeature sf : mf.features)
1779 String type = sf.getType();
1782 * Don't copy features which originated from Chimera
1784 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1785 .equals(sf.getFeatureGroup()))
1791 * record feature 'value' (score/description/type) as at the
1792 * corresponding structure position
1794 List<int[]> mappedRanges = structureMapping
1795 .getPDBResNumRanges(seqPos, seqPos);
1797 if (!mappedRanges.isEmpty())
1799 String value = sf.getDescription();
1800 if (value == null || value.length() == 0)
1804 float score = sf.getScore();
1805 if (score != 0f && !Float.isNaN(score))
1807 value = Float.toString(score);
1809 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1810 if (featureValues == null)
1812 featureValues = new HashMap<>();
1813 theMap.put(type, featureValues);
1815 for (int[] range : mappedRanges)
1817 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1818 range[1], structureMapping.getChain());
1827 * Inspect features on the sequence; for each feature that is visible,
1828 * determine its mapped ranges in the structure (if any) according to the
1829 * given mapping, and add them to the map.
1831 * @param visibleFeatures
1837 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1838 StructureMapping mapping, SequenceI seq,
1839 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1841 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1842 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1843 for (SequenceFeature sf : sfs)
1845 String type = sf.getType();
1848 * Don't copy features which originated from Chimera
1850 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1851 .equals(sf.getFeatureGroup()))
1856 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1859 if (!mappedRanges.isEmpty())
1861 String value = sf.getDescription();
1862 if (value == null || value.length() == 0)
1866 float score = sf.getScore();
1867 if (score != 0f && !Float.isNaN(score))
1869 value = Float.toString(score);
1871 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1872 if (featureValues == null)
1874 featureValues = new HashMap<>();
1875 theMap.put(type, featureValues);
1877 for (int[] range : mappedRanges)
1879 addAtomSpecRange(featureValues, value, modelId, range[0],
1880 range[1], mapping.getChain());
1887 * Returns the number of structure files in the structure viewer and mapped to
1888 * Jalview. This may be zero if the files are still in the process of loading
1893 public int getMappedStructureCount()
1895 String[] files = getStructureFiles();
1896 return files == null ? 0 : files.length;
1900 * Starts a thread that waits for the external viewer program process to
1901 * finish, so that we can then close the associated resources. This avoids
1902 * leaving orphaned viewer panels in Jalview if the user closes the external
1907 protected void startExternalViewerMonitor(Process p)
1909 externalViewerMonitor = new Thread(new Runnable()
1918 JalviewStructureDisplayI display = getViewer();
1919 if (display != null)
1921 display.closeViewer(false);
1923 } catch (InterruptedException e)
1925 // exit thread if Chimera Viewer is closed in Jalview
1929 externalViewerMonitor.start();
1933 * If supported by the external structure viewer, sends it commands to notify
1934 * model or selection changes to the specified URL (where Jalview has started
1939 protected void startListening(String uri)
1941 List<StructureCommandI> commands = getCommandGenerator()
1942 .startNotifications(uri);
1943 if (commands != null)
1945 executeCommands(commands, false, null);
1950 * If supported by the external structure viewer, sends it commands to stop
1951 * notifying model or selection changes
1953 protected void stopListening()
1955 List<StructureCommandI> commands = getCommandGenerator()
1956 .stopNotifications();
1957 if (commands != null)
1959 executeCommands(commands, false, null);
1964 * If supported by the structure viewer, queries it for all residue attributes
1965 * with the given attribute name, and creates features on corresponding
1966 * residues of the alignment. Returns the number of features added.
1969 * @param alignmentPanel
1972 public int copyStructureAttributesToFeatures(String attName,
1973 AlignmentPanel alignmentPanel)
1975 StructureCommandI cmd = getCommandGenerator()
1976 .getResidueAttributes(attName);
1981 List<String> residueAttributes = executeCommand(cmd, true);
1983 int featuresAdded = createFeaturesForAttributes(attName,
1985 if (featuresAdded > 0)
1987 alignmentPanel.getFeatureRenderer().featuresAdded();
1989 return featuresAdded;
1993 * Parses {@code residueAttributes} and creates sequence features on any
1994 * mapped alignment residues. Returns the number of features created.
1996 * {@code residueAttributes} is the reply from the structure viewer to a
1997 * command to list any residue attributes for the given attribute name. Syntax
1998 * and parsing of this is viewer-specific.
2001 * @param residueAttributes
2004 protected int createFeaturesForAttributes(String attName,
2005 List<String> residueAttributes)