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.Console;
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.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.
74 * Initial version created by refactoring JMol and Chimera binding models, but
75 * other 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);
597 public abstract void highlightAtoms(List<AtomSpec> atoms);
599 protected boolean isNucleotide()
601 return this.nucleotide;
605 * Returns a readable description of all mappings for the wrapped pdbfile to
606 * any mapped sequences
612 public String printMappings()
614 if (pdbEntry == null)
618 StringBuilder sb = new StringBuilder(128);
619 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
621 String pdbfile = getPdbEntry(pdbe).getFile();
622 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
623 sb.append(getSsm().printMappings(pdbfile, seqs));
625 return sb.toString();
629 * Returns the mapped structure position for a given aligned column of a given
630 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
631 * not mapped to structure.
638 protected int getMappedPosition(SequenceI seq, int alignedPos,
639 StructureMapping mapping)
641 if (alignedPos >= seq.getLength())
646 if (Comparison.isGap(seq.getCharAt(alignedPos)))
650 int seqPos = seq.findPosition(alignedPos);
651 int pos = mapping.getPDBResNum(seqPos);
656 * Helper method to identify residues that can participate in a structure
657 * superposition command. For each structure, identify a sequence in the
658 * alignment which is mapped to the structure. Identify non-gapped columns in
659 * the sequence which have a mapping to a residue in the structure. Returns
660 * the index of the first structure that has a mapping to the alignment.
663 * the sequence alignment which is the basis of structure
666 * a BitSet, where bit j is set to indicate that every structure has
667 * a mapped residue present in column j (so the column can
668 * participate in structure alignment)
670 * an array of data beans corresponding to pdb file index
673 protected int findSuperposableResidues(AlignmentI alignment,
675 AAStructureBindingModel.SuperposeData[] structures)
677 int refStructure = -1;
678 String[] files = getStructureFiles();
683 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
685 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
689 * Find the first mapped sequence (if any) for this PDB entry which is in
692 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
693 for (int s = 0; s < seqCountForPdbFile; s++)
695 for (StructureMapping mapping : mappings)
697 final SequenceI theSequence = getSequence()[pdbfnum][s];
698 if (mapping.getSequence() == theSequence
699 && alignment.findIndex(theSequence) > -1)
701 if (refStructure < 0)
703 refStructure = pdbfnum;
705 for (int r = 0; r < alignment.getWidth(); r++)
711 int pos = getMappedPosition(theSequence, r, mapping);
712 if (pos < 1 || pos == lastPos)
718 structures[pdbfnum].pdbResNo[r] = pos;
720 String chain = mapping.getChain();
721 if (chain != null && chain.trim().length() > 0)
723 structures[pdbfnum].chain = chain;
725 structures[pdbfnum].pdbId = mapping.getPdbId();
726 structures[pdbfnum].isRna = !theSequence.isProtein();
729 * move on to next pdb file (ignore sequences for other chains
730 * for the same structure)
732 s = seqCountForPdbFile;
733 break; // fixme break out of two loops here!
742 * Returns true if the structure viewer has loaded all of the files of
743 * interest (identified by the file mapping having been set up), or false if
744 * any are still not loaded after a timeout interval.
748 protected boolean waitForFileLoad(String[] files)
751 * give up after 10 secs plus 1 sec per file
753 long starttime = System.currentTimeMillis();
754 long endTime = 10000 + 1000 * files.length + starttime;
755 String notLoaded = null;
757 boolean waiting = true;
758 while (waiting && System.currentTimeMillis() < endTime)
761 for (String file : files)
770 StructureMapping[] sm = getSsm().getMapping(file);
771 if (sm == null || sm.length == 0)
775 } catch (Throwable x)
785 "Timed out waiting for structure viewer to load file "
793 public boolean isListeningFor(SequenceI seq)
795 if (sequence != null)
797 for (SequenceI[] seqs : sequence)
801 for (SequenceI s : seqs)
803 if (s == seq || (s.getDatasetSequence() != null
804 && s.getDatasetSequence() == seq.getDatasetSequence()))
815 public boolean isFinishedInit()
820 public void setFinishedInit(boolean fi)
822 this.finishedInit = fi;
826 * Returns a list of chains mapped in this viewer, formatted as
831 public List<String> getChainNames()
837 * Returns the Jalview panel hosting the structure viewer (if any)
841 public JalviewStructureDisplayI getViewer()
846 public void setViewer(JalviewStructureDisplayI v)
852 * Constructs and sends a command to align structures against a reference
853 * structure, based on one or more sequence alignments. May optionally return
854 * an error or warning message for the alignment command(s).
857 * an array of one or more alignment views to process
860 public String superposeStructures(List<AlignmentViewPanel> alignWith)
863 String[] files = getStructureFiles();
865 if (!waitForFileLoad(files))
871 for (AlignmentViewPanel view : alignWith)
873 AlignmentI alignment = view.getAlignment();
874 HiddenColumns hiddenCols = alignment.getHiddenColumns();
877 * 'matched' bit i will be set for visible alignment columns i where
878 * all sequences have a residue with a mapping to their PDB structure
880 BitSet matched = new BitSet();
881 final int width = alignment.getWidth();
882 for (int m = 0; m < width; m++)
884 if (hiddenCols == null || hiddenCols.isVisible(m))
890 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
891 for (int f = 0; f < files.length; f++)
893 structures[f] = new AAStructureBindingModel.SuperposeData(width,
894 getModelIdForFile(files[f]));
898 * Calculate the superposable alignment columns ('matched'), and the
899 * corresponding structure residue positions (structures.pdbResNo)
901 int refStructure = findSuperposableResidues(alignment, matched,
905 * require at least 4 positions to be able to execute superposition
907 int nmatched = matched.cardinality();
908 if (nmatched < MIN_POS_TO_SUPERPOSE)
910 String msg = MessageManager
911 .formatMessage("label.insufficient_residues", nmatched);
912 error += view.getViewName() + ": " + msg + "; ";
917 * get a model of the superposable residues in the reference structure
919 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
923 * Show all as backbone before doing superposition(s)
924 * (residues used for matching will be shown as ribbon)
926 // todo better way to ensure synchronous than setting getReply true!!
927 executeCommands(commandGenerator.showBackbone(), true, null);
929 AtomSpecType backbone = structures[refStructure].isRna ? AtomSpecType.PHOSPHATE : AtomSpecType.ALPHA;
931 * superpose each (other) structure to the reference in turn
933 for (int i = 0; i < structures.length; i++)
935 if (i != refStructure)
937 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
938 List<StructureCommandI> commands = commandGenerator
939 .superposeStructures(refAtoms, atomSpec, backbone);
940 List<String> replies = executeCommands(commands, true, null);
941 for (String reply : replies)
943 // return this error (Chimera only) to the user
944 if (reply.toLowerCase(Locale.ROOT).contains("unequal numbers of atoms"))
946 error += "; " + reply;
956 private AtomSpecModel getAtomSpec(
957 AAStructureBindingModel.SuperposeData superposeData,
960 AtomSpecModel model = new AtomSpecModel();
961 int nextColumnMatch = matched.nextSetBit(0);
962 while (nextColumnMatch != -1)
964 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
965 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
966 superposeData.chain);
967 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
974 * returns the current sequenceRenderer that should be used to colour the
981 public abstract SequenceRenderer getSequenceRenderer(
982 AlignmentViewPanel alignment);
985 * Sends a command to the structure viewer to colour each chain with a
986 * distinct colour (to the extent supported by the viewer)
988 public void colourByChain()
990 colourBySequence = false;
992 // TODO: JAL-628 colour chains distinctly across all visible models
994 executeCommand(false, COLOURING_STRUCTURES,
995 commandGenerator.colourByChain());
999 * Sends a command to the structure viewer to colour each chain with a
1000 * distinct colour (to the extent supported by the viewer)
1002 public void colourByCharge()
1004 colourBySequence = false;
1006 executeCommands(commandGenerator.colourByCharge(), false,
1007 COLOURING_STRUCTURES);
1011 * Sends a command to the structure to apply a colour scheme (defined in
1012 * Jalview but not necessarily applied to the alignment), which defines a
1013 * colour per residue letter. More complex schemes (e.g. that depend on
1014 * consensus) cannot be used here and are ignored.
1018 public void colourByJalviewColourScheme(ColourSchemeI cs)
1020 colourBySequence = false;
1022 if (cs == null || !cs.isSimple())
1028 * build a map of {Residue3LetterCode, Color}
1030 Map<String, Color> colours = new HashMap<>();
1031 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1033 for (String resName : residues)
1035 char res = resName.length() == 3
1036 ? ResidueProperties.getSingleCharacterCode(resName)
1037 : resName.charAt(0);
1038 Color colour = cs.findColour(res, 0, null, null, 0f);
1039 colours.put(resName, colour);
1043 * pass to the command constructor, and send the command
1045 List<StructureCommandI> cmd = commandGenerator
1046 .colourByResidues(colours);
1047 executeCommands(cmd, false, COLOURING_STRUCTURES);
1050 public void setBackgroundColour(Color col)
1052 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1053 executeCommand(false, null, cmd);
1057 * Execute one structure viewer command. If {@code getReply} is true, may
1058 * optionally return one or more reply messages, else returns null.
1063 protected abstract List<String> executeCommand(StructureCommandI cmd,
1067 * Executes one or more structure viewer commands
1073 protected List<String> executeCommands(List<StructureCommandI> commands,
1074 boolean getReply, String msg)
1076 return executeCommand(getReply, msg,
1077 commands.toArray(new StructureCommandI[commands.size()]));
1081 * Executes one or more structure viewer commands, optionally returning the
1082 * reply, and optionally showing a status message while the command is being
1085 * If a reply is wanted, the execution is done synchronously (waits),
1086 * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1087 * are sending commands that need to execute before later calls to
1088 * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1089 * set getReply true to ensure that commands are not executed out of order.
1096 protected List<String> executeCommand(boolean getReply, String msg,
1097 StructureCommandI... cmds)
1099 JalviewStructureDisplayI theViewer = getViewer();
1100 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1105 * execute and wait for reply
1107 List<String> response = new ArrayList<>();
1110 for (StructureCommandI cmd : cmds)
1112 List<String> replies = executeCommand(cmd, true);
1113 if (replies != null)
1115 response.addAll(replies);
1123 theViewer.stopProgressBar(null, handle);
1131 String threadName = msg == null ? "StructureCommand" : msg;
1132 new Thread(new Runnable()
1139 for (StructureCommandI cmd : cmds)
1141 executeCommand(cmd, false);
1147 SwingUtilities.invokeLater(new Runnable()
1152 theViewer.stopProgressBar(null, handle);
1158 }, threadName).start();
1163 * Colours any structures associated with sequences in the given alignment as
1164 * coloured in the alignment view, provided colourBySequence is enabled
1166 public void colourBySequence(AlignmentViewPanel alignmentv)
1168 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1172 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1175 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1176 .colourBySequence(colourMap);
1177 executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1181 * Centre the display in the structure viewer
1183 public void focusView()
1185 executeCommand(false, null, commandGenerator.focusView());
1189 * Generates and executes a command to show only specified chains in the
1190 * structure viewer. The list of chains to show should contain entries
1191 * formatted as "pdbid:chaincode".
1195 public void showChains(List<String> toShow)
1197 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1200 * Reformat the pdbid:chainCode values as modelNo:chainCode
1201 * since this is what is needed to construct the viewer command
1202 * todo: find a less messy way to do this
1204 List<String> showThese = new ArrayList<>();
1205 for (String chainId : toShow)
1207 String[] tokens = chainId.split("\\:");
1208 if (tokens.length == 2)
1210 String pdbFile = getFileForChain(chainId);
1211 String model = getModelIdForFile(pdbFile);
1212 showThese.add(model + ":" + tokens[1]);
1215 executeCommands(commandGenerator.showChains(showThese), false, null);
1219 * Answers the structure viewer's model id given a PDB file name. Returns an
1220 * empty string if model id is not found.
1225 protected abstract String getModelIdForFile(String chainId);
1227 public boolean hasFileLoadingError()
1229 return fileLoadingError != null && fileLoadingError.length() > 0;
1233 * Returns the FeatureRenderer for the given alignment view
1238 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1240 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1246 return ap.getFeatureRenderer();
1249 protected void setStructureCommands(StructureCommandsI cmd)
1251 commandGenerator = cmd;
1255 * Records association of one chain id (formatted as "pdbid:chainCode") with
1256 * the corresponding PDB file name
1261 public void addChainFile(String chainId, String fileName)
1263 chainFile.put(chainId, fileName);
1267 * Returns the PDB filename for the given chain id (formatted as
1268 * "pdbid:chainCode"), or null if not found
1273 protected String getFileForChain(String chainId)
1275 return chainFile.get(chainId);
1279 public void updateColours(Object source)
1281 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1282 // ignore events from panels not used to colour this view
1283 if (!getViewer().isUsedForColourBy(ap))
1287 if (!isLoadingFromArchive())
1289 colourBySequence(ap);
1293 public StructureCommandsI getCommandGenerator()
1295 return commandGenerator;
1298 protected abstract ViewerType getViewerType();
1301 * Builds a data structure which records mapped structure residues for each
1302 * colour. From this we can easily generate the viewer commands for colour by
1303 * sequence. Constructs and returns a map of {@code Color} to
1304 * {@code AtomSpecModel}, where the atomspec model holds
1312 * Ordering is by order of addition (for colours), natural ordering (for
1313 * models and chains)
1320 protected Map<Object, AtomSpecModel> buildColoursMap(
1321 StructureSelectionManager ssm, SequenceI[][] sequence,
1322 AlignmentViewPanel viewPanel)
1324 String[] files = getStructureFiles();
1325 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1326 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1327 FeatureColourFinder finder = new FeatureColourFinder(fr);
1328 AlignViewportI viewport = viewPanel.getAlignViewport();
1329 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1330 AlignmentI al = viewport.getAlignment();
1331 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1332 Color lastColour = null;
1334 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1336 final String modelId = getModelIdForFile(files[pdbfnum]);
1337 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1339 if (mapping == null || mapping.length < 1)
1344 int startPos = -1, lastPos = -1;
1345 String lastChain = "";
1346 for (int s = 0; s < sequence[pdbfnum].length; s++)
1348 for (int sp, m = 0; m < mapping.length; m++)
1350 final SequenceI seq = sequence[pdbfnum][s];
1351 if (mapping[m].getSequence() == seq
1352 && (sp = al.findIndex(seq)) > -1)
1354 SequenceI asp = al.getSequenceAt(sp);
1355 for (int r = 0; r < asp.getLength(); r++)
1357 // no mapping to gaps in sequence
1358 if (Comparison.isGap(asp.getCharAt(r)))
1362 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1364 if (pos < 1 || pos == lastPos)
1369 Color colour = sr.getResidueColour(seq, r, finder);
1372 * darker colour for hidden regions
1374 if (!cs.isVisible(r))
1376 colour = Color.GRAY;
1379 final String chain = mapping[m].getChain();
1382 * Just keep incrementing the end position for this colour range
1383 * _unless_ colour, PDB model or chain has changed, or there is a
1384 * gap in the mapped residue sequence
1386 final boolean newColour = !colour.equals(lastColour);
1387 final boolean nonContig = lastPos + 1 != pos;
1388 final boolean newChain = !chain.equals(lastChain);
1389 if (newColour || nonContig || newChain)
1393 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1394 lastPos, lastChain);
1398 lastColour = colour;
1402 // final colour range
1403 if (lastColour != null)
1405 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1406 lastPos, lastChain);
1417 * todo better refactoring (map lookup or similar to get viewer structure id)
1423 protected String getModelId(int pdbfnum, String file)
1425 return String.valueOf(pdbfnum);
1429 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1430 * full PDB file path
1435 public void stashFoundChains(StructureFile pdb, String file)
1437 for (int i = 0; i < pdb.getChains().size(); i++)
1439 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1440 addChainFile(chid, file);
1441 getChainNames().add(chid);
1446 * Helper method to add one contiguous range to the AtomSpec model for the
1447 * given value (creating the model if necessary). As used by Jalview,
1450 * <li>a colour, when building a 'colour structure by sequence' command</li>
1451 * <li>a feature value, when building a 'set Chimera attributes from features'
1462 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1463 Object value, String model, int startPos, int endPos,
1467 * Get/initialize map of data for the colour
1469 AtomSpecModel atomSpec = map.get(value);
1470 if (atomSpec == null)
1472 atomSpec = new AtomSpecModel();
1473 map.put(value, atomSpec);
1476 atomSpec.addRange(model, startPos, endPos, chain);
1480 * Returns the file extension (including '.' separator) to use for a saved
1481 * viewer session file. Default is to return null (not supported), override as
1486 public String getSessionFileExtension()
1492 * If supported, saves the state of the structure viewer to a temporary file
1493 * and returns the file. Returns null and logs an error on any failure.
1497 public File saveSession()
1499 String prefix = getViewerType().toString();
1500 String suffix = getSessionFileExtension();
1504 f = File.createTempFile(prefix, suffix);
1506 } catch (IOException e)
1508 Console.error(String.format("Error saving %s session: %s", prefix,
1516 * Saves the structure viewer session to the given file
1520 protected void saveSession(File f)
1522 StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1525 executeCommand(cmd, false);
1530 * Returns true if the viewer is an external structure viewer for which the
1531 * process is still alive, else false (for Jmol, or an external viewer which
1532 * the user has independently closed)
1536 public boolean isViewerRunning()
1542 * Closes Jalview's structure viewer panel and releases associated resources.
1543 * If it is managing an external viewer program, and {@code forceClose} is
1544 * true, also asks that program to close.
1548 public void closeViewer(boolean forceClose)
1550 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1551 releaseUIResources();
1554 * end the thread that closes this panel if the external viewer closes
1556 if (externalViewerMonitor != null)
1558 externalViewerMonitor.interrupt();
1559 externalViewerMonitor = null;
1566 StructureCommandI cmd = getCommandGenerator().closeViewer();
1569 executeCommand(cmd, false);
1575 * Returns the URL of a help page for the structure viewer, or null if none is
1580 public String getHelpURL()
1587 * Helper method to build a map of
1588 * { featureType, { feature value, AtomSpecModel } }
1594 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1595 AlignmentViewPanel viewPanel)
1597 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1598 String[] files = getStructureFiles();
1604 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1610 AlignViewportI viewport = viewPanel.getAlignViewport();
1611 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1614 * if alignment is showing features from complement, we also transfer
1615 * these features to the corresponding mapped structure residues
1617 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1618 List<String> complementFeatures = new ArrayList<>();
1619 FeatureRenderer complementRenderer = null;
1620 if (showLinkedFeatures)
1622 AlignViewportI comp = fr.getViewport().getCodingComplement();
1625 complementRenderer = Desktop.getAlignFrameFor(comp)
1626 .getFeatureRenderer();
1627 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1630 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1635 AlignmentI alignment = viewPanel.getAlignment();
1636 SequenceI[][] seqs = getSequence();
1638 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1640 String modelId = getModelIdForFile(files[pdbfnum]);
1641 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1643 if (mapping == null || mapping.length < 1)
1648 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1650 for (int m = 0; m < mapping.length; m++)
1652 final SequenceI seq = seqs[pdbfnum][seqNo];
1653 int sp = alignment.findIndex(seq);
1654 StructureMapping structureMapping = mapping[m];
1655 if (structureMapping.getSequence() == seq && sp > -1)
1658 * found a sequence with a mapping to a structure;
1659 * now scan its features
1661 if (!visibleFeatures.isEmpty())
1663 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1666 if (showLinkedFeatures)
1668 scanComplementFeatures(complementRenderer, structureMapping,
1669 seq, theMap, modelId);
1679 * Ask the structure viewer to open a session file. Returns true if
1680 * successful, else false (or not supported).
1685 public boolean openSession(String filepath)
1687 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1692 executeCommand(cmd, true);
1693 // todo: test for failure - how?
1698 * Scans visible features in mapped positions of the CDS/peptide complement,
1699 * and adds any found to the map of attribute values/structure positions
1701 * @param complementRenderer
1702 * @param structureMapping
1705 * @param modelNumber
1707 protected static void scanComplementFeatures(
1708 FeatureRenderer complementRenderer,
1709 StructureMapping structureMapping, SequenceI seq,
1710 Map<String, Map<Object, AtomSpecModel>> theMap,
1714 * for each sequence residue mapped to a structure position...
1716 for (int seqPos : structureMapping.getMapping().keySet())
1719 * find visible complementary features at mapped position(s)
1721 MappedFeatures mf = complementRenderer
1722 .findComplementFeaturesAtResidue(seq, seqPos);
1725 for (SequenceFeature sf : mf.features)
1727 String type = sf.getType();
1730 * Don't copy features which originated from Chimera
1732 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1733 .equals(sf.getFeatureGroup()))
1739 * record feature 'value' (score/description/type) as at the
1740 * corresponding structure position
1742 List<int[]> mappedRanges = structureMapping
1743 .getPDBResNumRanges(seqPos, seqPos);
1745 if (!mappedRanges.isEmpty())
1747 String value = sf.getDescription();
1748 if (value == null || value.length() == 0)
1752 float score = sf.getScore();
1753 if (score != 0f && !Float.isNaN(score))
1755 value = Float.toString(score);
1757 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1758 if (featureValues == null)
1760 featureValues = new HashMap<>();
1761 theMap.put(type, featureValues);
1763 for (int[] range : mappedRanges)
1765 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1766 range[1], structureMapping.getChain());
1775 * Inspect features on the sequence; for each feature that is visible,
1776 * determine its mapped ranges in the structure (if any) according to the
1777 * given mapping, and add them to the map.
1779 * @param visibleFeatures
1785 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1786 StructureMapping mapping, SequenceI seq,
1787 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1789 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1790 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1791 for (SequenceFeature sf : sfs)
1793 String type = sf.getType();
1796 * Don't copy features which originated from Chimera
1798 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1799 .equals(sf.getFeatureGroup()))
1804 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1807 if (!mappedRanges.isEmpty())
1809 String value = sf.getDescription();
1810 if (value == null || value.length() == 0)
1814 float score = sf.getScore();
1815 if (score != 0f && !Float.isNaN(score))
1817 value = Float.toString(score);
1819 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1820 if (featureValues == null)
1822 featureValues = new HashMap<>();
1823 theMap.put(type, featureValues);
1825 for (int[] range : mappedRanges)
1827 addAtomSpecRange(featureValues, value, modelId, range[0],
1828 range[1], mapping.getChain());
1835 * Returns the number of structure files in the structure viewer and mapped to
1836 * Jalview. This may be zero if the files are still in the process of loading
1841 public int getMappedStructureCount()
1843 String[] files = getStructureFiles();
1844 return files == null ? 0 : files.length;
1848 * Starts a thread that waits for the external viewer program process to
1849 * finish, so that we can then close the associated resources. This avoids
1850 * leaving orphaned viewer panels in Jalview if the user closes the external
1855 protected void startExternalViewerMonitor(Process p)
1857 externalViewerMonitor = new Thread(new Runnable()
1866 JalviewStructureDisplayI display = getViewer();
1867 if (display != null)
1869 display.closeViewer(false);
1871 } catch (InterruptedException e)
1873 // exit thread if Chimera Viewer is closed in Jalview
1877 externalViewerMonitor.start();
1881 * If supported by the external structure viewer, sends it commands to notify
1882 * model or selection changes to the specified URL (where Jalview has started
1887 protected void startListening(String uri)
1889 List<StructureCommandI> commands = getCommandGenerator()
1890 .startNotifications(uri);
1891 if (commands != null)
1893 executeCommands(commands, false, null);
1898 * If supported by the external structure viewer, sends it commands to stop
1899 * notifying model or selection changes
1901 protected void stopListening()
1903 List<StructureCommandI> commands = getCommandGenerator()
1904 .stopNotifications();
1905 if (commands != null)
1907 executeCommands(commands, false, null);
1912 * If supported by the structure viewer, queries it for all residue attributes
1913 * with the given attribute name, and creates features on corresponding
1914 * residues of the alignment. Returns the number of features added.
1917 * @param alignmentPanel
1920 public int copyStructureAttributesToFeatures(String attName,
1921 AlignmentPanel alignmentPanel)
1923 StructureCommandI cmd = getCommandGenerator()
1924 .getResidueAttributes(attName);
1929 List<String> residueAttributes = executeCommand(cmd, true);
1931 int featuresAdded = createFeaturesForAttributes(attName,
1933 if (featuresAdded > 0)
1935 alignmentPanel.getFeatureRenderer().featuresAdded();
1937 return featuresAdded;
1941 * Parses {@code residueAttributes} and creates sequence features on any
1942 * mapped alignment residues. Returns the number of features created.
1944 * {@code residueAttributes} is the reply from the structure viewer to a
1945 * command to list any residue attributes for the given attribute name. Syntax
1946 * and parsing of this is viewer-specific.
1949 * @param residueAttributes
1952 protected int createFeaturesForAttributes(String attName,
1953 List<String> residueAttributes)