2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.structures.models;
23 import java.awt.Color;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.BitSet;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
31 import java.util.List;
34 import javax.swing.SwingUtilities;
36 import jalview.api.AlignViewportI;
37 import jalview.api.AlignmentViewPanel;
38 import jalview.api.FeatureRenderer;
39 import jalview.api.SequenceRenderer;
40 import jalview.api.StructureSelectionManagerProvider;
41 import jalview.api.structures.JalviewStructureDisplayI;
42 import jalview.bin.Cache;
43 import jalview.datamodel.AlignmentI;
44 import jalview.datamodel.HiddenColumns;
45 import jalview.datamodel.MappedFeatures;
46 import jalview.datamodel.PDBEntry;
47 import jalview.datamodel.SequenceFeature;
48 import jalview.datamodel.SequenceI;
49 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
50 import jalview.gui.Desktop;
51 import jalview.gui.StructureViewer.ViewerType;
52 import jalview.io.DataSourceType;
53 import jalview.io.StructureFile;
54 import jalview.renderer.seqfeatures.FeatureColourFinder;
55 import jalview.schemes.ColourSchemeI;
56 import jalview.schemes.ResidueProperties;
57 import jalview.structure.AtomSpec;
58 import jalview.structure.AtomSpecModel;
59 import jalview.structure.StructureCommandI;
60 import jalview.structure.StructureCommandsI;
61 import jalview.structure.StructureListener;
62 import jalview.structure.StructureMapping;
63 import jalview.structure.StructureSelectionManager;
64 import jalview.util.Comparison;
65 import jalview.util.MessageManager;
69 * A base class to hold common function for protein structure model binding.
70 * Initial version created by refactoring JMol and Chimera binding models, but
71 * other structure viewers could in principle be accommodated in future.
76 public abstract class AAStructureBindingModel
77 extends SequenceStructureBindingModel
78 implements StructureListener, StructureSelectionManagerProvider
81 * Data bean class to simplify parameterisation in superposeStructures
83 public static class SuperposeData
85 public String filename;
89 public String chain = "";
94 * The pdb residue number (if any) mapped to columns of the alignment
96 public int[] pdbResNo; // or use SparseIntArray?
98 public String modelId;
104 * width of alignment (number of columns that may potentially
105 * participate in superposition)
107 * structure viewer model number
109 public SuperposeData(int width, String model)
111 pdbResNo = new int[width];
116 private static final int MIN_POS_TO_SUPERPOSE = 4;
118 private static final String COLOURING_STRUCTURES = MessageManager
119 .getString("status.colouring_structures");
122 * the Jalview panel through which the user interacts
123 * with the structure viewer
125 private JalviewStructureDisplayI viewer;
128 * helper that generates command syntax
130 private StructureCommandsI commandGenerator;
132 private StructureSelectionManager ssm;
135 * modelled chains, formatted as "pdbid:chainCode"
137 private List<String> chainNames;
140 * lookup of pdb file name by key "pdbid:chainCode"
142 private Map<String, String> chainFile;
145 * distinct PDB entries (pdb files) associated
148 private PDBEntry[] pdbEntry;
151 * sequences mapped to each pdbentry
153 private SequenceI[][] sequence;
156 * array of target chains for sequences - tied to pdbentry and sequence[]
158 private String[][] chains;
161 * datasource protocol for access to PDBEntrylatest
163 DataSourceType protocol = null;
165 protected boolean colourBySequence = true;
167 private boolean nucleotide;
169 private boolean finishedInit = false;
172 * current set of model filenames loaded in the viewer
174 protected String[] modelFileNames = null;
176 public String fileLoadingError;
178 protected Thread externalViewerMonitor;
186 public AAStructureBindingModel(StructureSelectionManager ssm,
190 this.sequence = seqs;
191 chainNames = new ArrayList<>();
192 chainFile = new HashMap<>();
203 public AAStructureBindingModel(StructureSelectionManager ssm,
204 PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
205 DataSourceType protocol)
207 this(ssm, sequenceIs);
208 this.nucleotide = Comparison.isNucleotide(sequenceIs);
209 this.pdbEntry = pdbentry;
210 this.protocol = protocol;
214 private boolean resolveChains()
217 * final count of chain mappings discovered
220 // JBPNote: JAL-2693 - this should be a list of chain mappings per
221 // [pdbentry][sequence]
222 String[][] newchains = new String[pdbEntry.length][];
224 for (PDBEntry pdb : pdbEntry)
226 SequenceI[] seqsForPdb = sequence[pe];
227 if (seqsForPdb != null)
229 newchains[pe] = new String[seqsForPdb.length];
231 for (SequenceI asq : seqsForPdb)
233 String chain = (chains != null && chains[pe] != null)
236 SequenceI sq = (asq.getDatasetSequence() == null) ? asq
237 : asq.getDatasetSequence();
238 if (sq.getAllPDBEntries() != null)
240 for (PDBEntry pdbentry : sq.getAllPDBEntries())
242 if (pdb.getFile() != null && pdbentry.getFile() != null
243 && pdb.getFile().equals(pdbentry.getFile()))
245 String chaincode = pdbentry.getChainCode();
246 if (chaincode != null && chaincode.length() > 0)
255 newchains[pe][se] = chain;
263 return chainmaps > 0;
265 public StructureSelectionManager getSsm()
271 * Returns the i'th PDBEntry (or null)
276 public PDBEntry getPdbEntry(int i)
278 return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
282 * Answers true if this binding includes the given PDB id, else false
287 public boolean hasPdbId(String pdbId)
289 if (pdbEntry != null)
291 for (PDBEntry pdb : pdbEntry)
293 if (pdb.getId().equals(pdbId))
303 * Returns the number of modelled PDB file entries.
307 public int getPdbCount()
309 return pdbEntry == null ? 0 : pdbEntry.length;
312 public SequenceI[][] getSequence()
317 public String[][] getChains()
322 public DataSourceType getProtocol()
327 // TODO may remove this if calling methods can be pulled up here
328 protected void setPdbentry(PDBEntry[] pdbentry)
330 this.pdbEntry = pdbentry;
333 protected void setSequence(SequenceI[][] sequence)
335 this.sequence = sequence;
338 protected void setChains(String[][] chains)
340 this.chains = chains;
344 * Construct a title string for the viewer window based on the data Jalview
353 public String getViewerTitle(String viewerName, boolean verbose)
355 if (getSequence() == null || getSequence().length < 1
356 || getPdbCount() < 1 || getSequence()[0].length < 1)
358 return ("Jalview " + viewerName + " Window");
360 // TODO: give a more informative title when multiple structures are
362 StringBuilder title = new StringBuilder(64);
363 final PDBEntry pdbe = getPdbEntry(0);
364 title.append(viewerName + " view for " + getSequence()[0][0].getName()
365 + ":" + pdbe.getId());
369 String method = (String) pdbe.getProperty("method");
372 title.append(" Method: ").append(method);
374 String chain = (String) pdbe.getProperty("chains");
377 title.append(" Chain:").append(chain);
380 return title.toString();
384 * Called by after closeViewer is called, to release any resources and
385 * references so they can be garbage collected. Override if needed.
387 protected void releaseUIResources()
392 public void releaseReferences(Object svl)
396 public boolean isColourBySequence()
398 return colourBySequence;
402 * Called when the binding thinks the UI needs to be refreshed after a
403 * structure viewer state change. This could be because structures were
404 * loaded, or because an error has occurred. Default does nothing, override as
407 public void refreshGUI()
412 * Instruct the Jalview binding to update the pdbentries vector if necessary
413 * prior to matching the jmol view's contents to the list of structure files
414 * Jalview knows about. By default does nothing, override as required.
416 public void refreshPdbEntries()
420 public void setColourBySequence(boolean colourBySequence)
422 this.colourBySequence = colourBySequence;
425 protected void addSequenceAndChain(int pe, SequenceI[] seq,
428 if (pe < 0 || pe >= getPdbCount())
430 throw new Error(MessageManager.formatMessage(
431 "error.implementation_error_no_pdbentry_from_index",
433 { Integer.valueOf(pe).toString() }));
435 final String nullChain = "TheNullChain";
436 List<SequenceI> s = new ArrayList<>();
437 List<String> c = new ArrayList<>();
438 if (getChains() == null)
440 setChains(new String[getPdbCount()][]);
442 if (getSequence()[pe] != null)
444 for (int i = 0; i < getSequence()[pe].length; i++)
446 s.add(getSequence()[pe][i]);
447 if (getChains()[pe] != null)
449 if (i < getChains()[pe].length)
451 c.add(getChains()[pe][i]);
460 if (tchain != null && tchain.length > 0)
467 for (int i = 0; i < seq.length; i++)
469 if (!s.contains(seq[i]))
472 if (tchain != null && i < tchain.length)
474 c.add(tchain[i] == null ? nullChain : tchain[i]);
478 SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
479 getSequence()[pe] = tmp;
482 String[] tch = c.toArray(new String[c.size()]);
483 for (int i = 0; i < tch.length; i++)
485 if (tch[i] == nullChain)
490 getChains()[pe] = tch;
494 getChains()[pe] = null;
499 * add structures and any known sequence associations
501 * @returns the pdb entries added to the current set.
503 public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
504 SequenceI[][] seq, String[][] chns)
506 List<PDBEntry> v = new ArrayList<>();
507 List<int[]> rtn = new ArrayList<>();
508 for (int i = 0; i < getPdbCount(); i++)
510 v.add(getPdbEntry(i));
512 for (int i = 0; i < pdbe.length; i++)
514 int r = v.indexOf(pdbe[i]);
515 if (r == -1 || r >= getPdbCount())
517 rtn.add(new int[] { v.size(), i });
522 // just make sure the sequence/chain entries are all up to date
523 addSequenceAndChain(r, seq[i], chns[i]);
526 pdbe = v.toArray(new PDBEntry[v.size()]);
530 // expand the tied sequence[] and string[] arrays
531 SequenceI[][] sqs = new SequenceI[getPdbCount()][];
532 String[][] sch = new String[getPdbCount()][];
533 System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
534 System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
537 pdbe = new PDBEntry[rtn.size()];
538 for (int r = 0; r < pdbe.length; r++)
540 int[] stri = (rtn.get(r));
541 // record the pdb file as a new addition
542 pdbe[r] = getPdbEntry(stri[0]);
543 // and add the new sequence/chain entries
544 addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
555 * Add sequences to the pe'th pdbentry's sequence set.
560 public void addSequence(int pe, SequenceI[] seq)
562 addSequenceAndChain(pe, seq, null);
566 * add the given sequences to the mapping scope for the given pdb file handle
569 * - pdbFile identifier
571 * - set of sequences it can be mapped to
573 public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
575 for (int pe = 0; pe < getPdbCount(); pe++)
577 if (getPdbEntry(pe).getFile().equals(pdbFile))
579 addSequence(pe, seq);
585 public abstract void highlightAtoms(List<AtomSpec> atoms);
587 protected boolean isNucleotide()
589 return this.nucleotide;
593 * Returns a readable description of all mappings for the wrapped pdbfile to
594 * any mapped sequences
600 public String printMappings()
602 if (pdbEntry == null)
606 StringBuilder sb = new StringBuilder(128);
607 for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
609 String pdbfile = getPdbEntry(pdbe).getFile();
610 List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
611 sb.append(getSsm().printMappings(pdbfile, seqs));
613 return sb.toString();
617 * Returns the mapped structure position for a given aligned column of a given
618 * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
619 * not mapped to structure.
626 protected int getMappedPosition(SequenceI seq, int alignedPos,
627 StructureMapping mapping)
629 if (alignedPos >= seq.getLength())
634 if (Comparison.isGap(seq.getCharAt(alignedPos)))
638 int seqPos = seq.findPosition(alignedPos);
639 int pos = mapping.getPDBResNum(seqPos);
644 * Helper method to identify residues that can participate in a structure
645 * superposition command. For each structure, identify a sequence in the
646 * alignment which is mapped to the structure. Identify non-gapped columns in
647 * the sequence which have a mapping to a residue in the structure. Returns
648 * the index of the first structure that has a mapping to the alignment.
651 * the sequence alignment which is the basis of structure
654 * a BitSet, where bit j is set to indicate that every structure has
655 * a mapped residue present in column j (so the column can
656 * participate in structure alignment)
658 * an array of data beans corresponding to pdb file index
661 protected int findSuperposableResidues(AlignmentI alignment,
662 BitSet matched, AAStructureBindingModel.SuperposeData[] structures)
664 int refStructure = -1;
665 String[] files = getStructureFiles();
670 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
672 StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
676 * Find the first mapped sequence (if any) for this PDB entry which is in
679 final int seqCountForPdbFile = getSequence()[pdbfnum].length;
680 for (int s = 0; s < seqCountForPdbFile; s++)
682 for (StructureMapping mapping : mappings)
684 final SequenceI theSequence = getSequence()[pdbfnum][s];
685 if (mapping.getSequence() == theSequence
686 && alignment.findIndex(theSequence) > -1)
688 if (refStructure < 0)
690 refStructure = pdbfnum;
692 for (int r = 0; r < alignment.getWidth(); r++)
698 int pos = getMappedPosition(theSequence, r, mapping);
699 if (pos < 1 || pos == lastPos)
705 structures[pdbfnum].pdbResNo[r] = pos;
707 String chain = mapping.getChain();
708 if (chain != null && chain.trim().length() > 0)
710 structures[pdbfnum].chain = chain;
712 structures[pdbfnum].pdbId = mapping.getPdbId();
713 structures[pdbfnum].isRna = theSequence.getRNA() != null;
716 * move on to next pdb file (ignore sequences for other chains
717 * for the same structure)
719 s = seqCountForPdbFile;
720 break; // fixme break out of two loops here!
729 * Returns true if the structure viewer has loaded all of the files of
730 * interest (identified by the file mapping having been set up), or false if
731 * any are still not loaded after a timeout interval.
735 protected boolean waitForFileLoad(String[] files)
738 * give up after 10 secs plus 1 sec per file
740 long starttime = System.currentTimeMillis();
741 long endTime = 10000 + 1000 * files.length + starttime;
742 String notLoaded = null;
744 boolean waiting = true;
745 while (waiting && System.currentTimeMillis() < endTime)
748 for (String file : files)
757 StructureMapping[] sm = getSsm().getMapping(file);
758 if (sm == null || sm.length == 0)
762 } catch (Throwable x)
772 "Timed out waiting for structure viewer to load file "
780 public boolean isListeningFor(SequenceI seq)
782 if (sequence != null)
784 for (SequenceI[] seqs : sequence)
788 for (SequenceI s : seqs)
790 if (s == seq || (s.getDatasetSequence() != null
791 && s.getDatasetSequence() == seq.getDatasetSequence()))
802 public boolean isFinishedInit()
807 public void setFinishedInit(boolean fi)
809 this.finishedInit = fi;
813 * Returns a list of chains mapped in this viewer, formatted as
818 public List<String> getChainNames()
824 * Returns the Jalview panel hosting the structure viewer (if any)
828 public JalviewStructureDisplayI getViewer()
833 public void setViewer(JalviewStructureDisplayI v)
839 * Constructs and sends a command to align structures against a reference
840 * structure, based on one or more sequence alignments. May optionally return
841 * an error or warning message for the alignment command(s).
844 * an array of one or more alignment views to process
847 public String superposeStructures(List<AlignmentViewPanel> alignWith)
850 String[] files = getStructureFiles();
852 if (!waitForFileLoad(files))
858 for (AlignmentViewPanel view : alignWith)
860 AlignmentI alignment = view.getAlignment();
861 HiddenColumns hiddenCols = alignment.getHiddenColumns();
864 * 'matched' bit i will be set for visible alignment columns i where
865 * all sequences have a residue with a mapping to their PDB structure
867 BitSet matched = new BitSet();
868 final int width = alignment.getWidth();
869 for (int m = 0; m < width; m++)
871 if (hiddenCols == null || hiddenCols.isVisible(m))
877 AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
878 for (int f = 0; f < files.length; f++)
880 structures[f] = new AAStructureBindingModel.SuperposeData(width,
881 getModelIdForFile(files[f]));
885 * Calculate the superposable alignment columns ('matched'), and the
886 * corresponding structure residue positions (structures.pdbResNo)
888 int refStructure = findSuperposableResidues(alignment,
889 matched, structures);
892 * require at least 4 positions to be able to execute superposition
894 int nmatched = matched.cardinality();
895 if (nmatched < MIN_POS_TO_SUPERPOSE)
897 String msg = MessageManager.formatMessage("label.insufficient_residues",
899 error += view.getViewName() + ": " + msg + "; ";
904 * get a model of the superposable residues in the reference structure
906 AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
910 * Show all as backbone before doing superposition(s)
911 * (residues used for matching will be shown as ribbon)
913 // todo better way to ensure synchronous than setting getReply true!!
914 executeCommands(commandGenerator.showBackbone(), true, null);
917 * superpose each (other) structure to the reference in turn
919 for (int i = 0; i < structures.length; i++)
921 if (i != refStructure)
923 AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
924 List<StructureCommandI> commands = commandGenerator
925 .superposeStructures(refAtoms, atomSpec);
926 List<String> replies = executeCommands(commands, true, null);
927 for (String reply : replies)
929 // return this error (Chimera only) to the user
930 if (reply.toLowerCase().contains("unequal numbers of atoms"))
932 error += "; " + reply;
942 private AtomSpecModel getAtomSpec(AAStructureBindingModel.SuperposeData superposeData,
945 AtomSpecModel model = new AtomSpecModel();
946 int nextColumnMatch = matched.nextSetBit(0);
947 while (nextColumnMatch != -1)
949 int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
950 model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
951 superposeData.chain);
952 nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
959 * returns the current sequenceRenderer that should be used to colour the
966 public abstract SequenceRenderer getSequenceRenderer(
967 AlignmentViewPanel alignment);
970 * Sends a command to the structure viewer to colour each chain with a
971 * distinct colour (to the extent supported by the viewer)
973 public void colourByChain()
975 colourBySequence = false;
977 // TODO: JAL-628 colour chains distinctly across all visible models
979 executeCommand(commandGenerator.colourByChain(), false,
980 COLOURING_STRUCTURES);
984 * Sends a command to the structure viewer to colour each chain with a
985 * distinct colour (to the extent supported by the viewer)
987 public void colourByCharge()
989 colourBySequence = false;
991 executeCommands(commandGenerator.colourByCharge(), false,
992 COLOURING_STRUCTURES);
996 * Sends a command to the structure to apply a colour scheme (defined in
997 * Jalview but not necessarily applied to the alignment), which defines a
998 * colour per residue letter. More complex schemes (e.g. that depend on
999 * consensus) cannot be used here and are ignored.
1003 public void colourByJalviewColourScheme(ColourSchemeI cs)
1005 colourBySequence = false;
1007 if (cs == null || !cs.isSimple())
1013 * build a map of {Residue3LetterCode, Color}
1015 Map<String, Color> colours = new HashMap<>();
1016 List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1018 for (String resName : residues)
1020 char res = resName.length() == 3
1021 ? ResidueProperties.getSingleCharacterCode(resName)
1022 : resName.charAt(0);
1023 Color colour = cs.findColour(res, 0, null, null, 0f);
1024 colours.put(resName, colour);
1028 * pass to the command constructor, and send the command
1030 List<StructureCommandI> cmd = commandGenerator
1031 .colourByResidues(colours);
1032 executeCommands(cmd, false, COLOURING_STRUCTURES);
1035 public void setBackgroundColour(Color col)
1037 StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1038 executeCommand(cmd, false, null);
1042 * Sends one command to the structure viewer. If {@code getReply} is true, the
1043 * command is sent synchronously, otherwise in a deferred thread.
1045 * If a progress message is supplied, this is displayed before command
1046 * execution, and removed afterwards.
1053 private List<String> executeCommand(StructureCommandI cmd,
1054 boolean getReply, String msg)
1059 * synchronous (same thread) execution so reply can be returned
1061 final JalviewStructureDisplayI theViewer = getViewer();
1062 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1065 return executeCommand(cmd, getReply);
1070 theViewer.stopProgressBar(null, handle);
1077 * asynchronous (new thread) execution if no reply needed
1079 final JalviewStructureDisplayI theViewer = getViewer();
1080 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1082 SwingUtilities.invokeLater(new Runnable()
1089 executeCommand(cmd, false);
1094 theViewer.stopProgressBar(null, handle);
1104 * Execute one structure viewer command. If {@code getReply} is true, may
1105 * optionally return one or more reply messages, else returns null.
1110 protected abstract List<String> executeCommand(StructureCommandI cmd,
1114 * Executes one or more structure viewer commands. If a progress message is
1115 * provided, it is shown first, and removed after all commands have been run.
1121 protected List<String> executeCommands(List<StructureCommandI> commands,
1122 boolean getReply, String msg)
1125 * show progress message if specified
1127 final JalviewStructureDisplayI theViewer = getViewer();
1128 final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1130 List<String> response = getReply ? new ArrayList<>() : null;
1133 for (StructureCommandI cmd : commands)
1135 List<String> replies = executeCommand(cmd, getReply, null);
1136 if (getReply && replies != null)
1138 response.addAll(replies);
1146 theViewer.stopProgressBar(null, handle);
1152 * Colours any structures associated with sequences in the given alignment as
1153 * coloured in the alignment view, provided colourBySequence is enabled
1155 public void colourBySequence(AlignmentViewPanel alignmentv)
1157 if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1161 Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1164 List<StructureCommandI> colourBySequenceCommands = commandGenerator
1165 .colourBySequence(colourMap);
1166 executeCommands(colourBySequenceCommands, false, null);
1170 * Centre the display in the structure viewer
1172 public void focusView()
1174 executeCommand(commandGenerator.focusView(), false, null);
1178 * Generates and executes a command to show only specified chains in the
1179 * structure viewer. The list of chains to show should contain entries
1180 * formatted as "pdbid:chaincode".
1184 public void showChains(List<String> toShow)
1186 // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1189 * Reformat the pdbid:chainCode values as modelNo:chainCode
1190 * since this is what is needed to construct the viewer command
1191 * todo: find a less messy way to do this
1193 List<String> showThese = new ArrayList<>();
1194 for (String chainId : toShow)
1196 String[] tokens = chainId.split("\\:");
1197 if (tokens.length == 2)
1199 String pdbFile = getFileForChain(chainId);
1200 String model = getModelIdForFile(pdbFile);
1201 showThese.add(model + ":" + tokens[1]);
1204 executeCommands(commandGenerator.showChains(showThese), false, null);
1208 * Answers the structure viewer's model id given a PDB file name. Returns an
1209 * empty string if model id is not found.
1214 protected abstract String getModelIdForFile(String chainId);
1216 public boolean hasFileLoadingError()
1218 return fileLoadingError != null && fileLoadingError.length() > 0;
1222 * Returns the FeatureRenderer for the given alignment view, or null if
1223 * feature display is turned off in the view.
1228 public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1230 AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1236 return ap.getAlignViewport().isShowSequenceFeatures()
1237 ? ap.getFeatureRenderer()
1241 protected void setStructureCommands(StructureCommandsI cmd)
1243 commandGenerator = cmd;
1247 * Records association of one chain id (formatted as "pdbid:chainCode") with
1248 * the corresponding PDB file name
1253 public void addChainFile(String chainId, String fileName)
1255 chainFile.put(chainId, fileName);
1259 * Returns the PDB filename for the given chain id (formatted as
1260 * "pdbid:chainCode"), or null if not found
1265 protected String getFileForChain(String chainId)
1267 return chainFile.get(chainId);
1271 public void updateColours(Object source)
1273 AlignmentViewPanel ap = (AlignmentViewPanel) source;
1274 // ignore events from panels not used to colour this view
1275 if (!getViewer().isUsedForColourBy(ap))
1279 if (!isLoadingFromArchive())
1281 colourBySequence(ap);
1285 public StructureCommandsI getCommandGenerator()
1287 return commandGenerator;
1290 protected abstract ViewerType getViewerType();
1293 * Send a structure viewer command asynchronously in a new thread. If the
1294 * progress message is not null, display this message while the command is
1298 * @param progressMsg
1300 protected void sendAsynchronousCommand(StructureCommandI command,
1303 final JalviewStructureDisplayI theViewer = getViewer();
1304 final long handle = progressMsg == null ? 0
1305 : theViewer.startProgressBar(progressMsg);
1306 SwingUtilities.invokeLater(new Runnable()
1313 executeCommand(command, false, null);
1316 if (progressMsg != null)
1318 theViewer.stopProgressBar(null, handle);
1327 * Builds a data structure which records mapped structure residues for each
1328 * colour. From this we can easily generate the viewer commands for colour by
1329 * sequence. Constructs and returns a map of {@code Color} to
1330 * {@code AtomSpecModel}, where the atomspec model holds
1338 * Ordering is by order of addition (for colours), natural ordering (for
1339 * models and chains)
1346 protected Map<Object, AtomSpecModel> buildColoursMap(
1347 StructureSelectionManager ssm, SequenceI[][] sequence,
1348 AlignmentViewPanel viewPanel)
1350 String[] files = getStructureFiles();
1351 SequenceRenderer sr = getSequenceRenderer(viewPanel);
1352 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1353 FeatureColourFinder finder = new FeatureColourFinder(fr);
1354 AlignViewportI viewport = viewPanel.getAlignViewport();
1355 HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1356 AlignmentI al = viewport.getAlignment();
1357 Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1358 Color lastColour = null;
1360 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1362 final String modelId = getModelIdForFile(files[pdbfnum]);
1363 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1365 if (mapping == null || mapping.length < 1)
1370 int startPos = -1, lastPos = -1;
1371 String lastChain = "";
1372 for (int s = 0; s < sequence[pdbfnum].length; s++)
1374 for (int sp, m = 0; m < mapping.length; m++)
1376 final SequenceI seq = sequence[pdbfnum][s];
1377 if (mapping[m].getSequence() == seq
1378 && (sp = al.findIndex(seq)) > -1)
1380 SequenceI asp = al.getSequenceAt(sp);
1381 for (int r = 0; r < asp.getLength(); r++)
1383 // no mapping to gaps in sequence
1384 if (Comparison.isGap(asp.getCharAt(r)))
1388 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1390 if (pos < 1 || pos == lastPos)
1395 Color colour = sr.getResidueColour(seq, r, finder);
1398 * darker colour for hidden regions
1400 if (!cs.isVisible(r))
1402 colour = Color.GRAY;
1405 final String chain = mapping[m].getChain();
1408 * Just keep incrementing the end position for this colour range
1409 * _unless_ colour, PDB model or chain has changed, or there is a
1410 * gap in the mapped residue sequence
1412 final boolean newColour = !colour.equals(lastColour);
1413 final boolean nonContig = lastPos + 1 != pos;
1414 final boolean newChain = !chain.equals(lastChain);
1415 if (newColour || nonContig || newChain)
1419 addAtomSpecRange(colourMap, lastColour, modelId,
1420 startPos, lastPos, lastChain);
1424 lastColour = colour;
1428 // final colour range
1429 if (lastColour != null)
1431 addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1432 lastPos, lastChain);
1443 * todo better refactoring (map lookup or similar to get viewer structure id)
1449 protected String getModelId(int pdbfnum, String file)
1451 return String.valueOf(pdbfnum);
1455 * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1456 * full PDB file path
1461 public void stashFoundChains(StructureFile pdb, String file)
1463 for (int i = 0; i < pdb.getChains().size(); i++)
1465 String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1466 addChainFile(chid, file);
1467 getChainNames().add(chid);
1472 * Helper method to add one contiguous range to the AtomSpec model for the given
1473 * value (creating the model if necessary). As used by Jalview, {@code value} is
1475 * <li>a colour, when building a 'colour structure by sequence' command</li>
1476 * <li>a feature value, when building a 'set Chimera attributes from features'
1487 public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1489 String model, int startPos, int endPos, String chain)
1492 * Get/initialize map of data for the colour
1494 AtomSpecModel atomSpec = map.get(value);
1495 if (atomSpec == null)
1497 atomSpec = new AtomSpecModel();
1498 map.put(value, atomSpec);
1501 atomSpec.addRange(model, startPos, endPos, chain);
1505 * Returns the file extension (including '.' separator) to use for a saved
1506 * viewer session file. Default is to return null (not supported), override as
1511 public String getSessionFileExtension()
1517 * If supported, saves the state of the structure viewer to a temporary file
1518 * and returns the file. Returns null and logs an error on any failure.
1522 public File saveSession()
1524 String prefix = getViewerType().toString();
1525 String suffix = getSessionFileExtension();
1529 f = File.createTempFile(prefix, suffix);
1531 } catch (IOException e)
1533 Cache.log.error(String.format("Error saving %s session: %s",
1534 prefix, e.toString()));
1541 * Saves the structure viewer session to the given file
1545 protected void saveSession(File f)
1547 StructureCommandI cmd = commandGenerator
1548 .saveSession(f.getPath());
1551 executeCommand(cmd, false);
1556 * Returns true if the viewer is an external structure viewer for which the
1557 * process is still alive, else false (for Jmol, or an external viewer which
1558 * the user has independently closed)
1562 public boolean isViewerRunning()
1568 * Closes Jalview's structure viewer panel and releases associated resources.
1569 * If it is managing an external viewer program, and {@code forceClose} is
1570 * true, also asks that program to close.
1574 public void closeViewer(boolean forceClose)
1576 getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1577 releaseUIResources();
1580 * end the thread that closes this panel if the external viewer closes
1582 if (externalViewerMonitor != null)
1584 externalViewerMonitor.interrupt();
1585 externalViewerMonitor = null;
1590 StructureCommandI cmd = getCommandGenerator().closeViewer();
1593 executeCommand(cmd, false);
1599 * Returns the URL of a help page for the structure viewer, or null if none is
1604 public String getHelpURL()
1611 * Helper method to build a map of
1612 * { featureType, { feature value, AtomSpecModel } }
1618 protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1619 AlignmentViewPanel viewPanel)
1621 Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1622 String[] files = getStructureFiles();
1628 FeatureRenderer fr = viewPanel.getFeatureRenderer();
1634 AlignViewportI viewport = viewPanel.getAlignViewport();
1635 List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1638 * if alignment is showing features from complement, we also transfer
1639 * these features to the corresponding mapped structure residues
1641 boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1642 List<String> complementFeatures = new ArrayList<>();
1643 FeatureRenderer complementRenderer = null;
1644 if (showLinkedFeatures)
1646 AlignViewportI comp = fr.getViewport().getCodingComplement();
1649 complementRenderer = Desktop.getAlignFrameFor(comp)
1650 .getFeatureRenderer();
1651 complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1654 if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1659 AlignmentI alignment = viewPanel.getAlignment();
1660 SequenceI[][] seqs = getSequence();
1662 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1664 String modelId = getModelIdForFile(files[pdbfnum]);
1665 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1667 if (mapping == null || mapping.length < 1)
1672 for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1674 for (int m = 0; m < mapping.length; m++)
1676 final SequenceI seq = seqs[pdbfnum][seqNo];
1677 int sp = alignment.findIndex(seq);
1678 StructureMapping structureMapping = mapping[m];
1679 if (structureMapping.getSequence() == seq && sp > -1)
1682 * found a sequence with a mapping to a structure;
1683 * now scan its features
1685 if (!visibleFeatures.isEmpty())
1687 scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1690 if (showLinkedFeatures)
1692 scanComplementFeatures(complementRenderer, structureMapping,
1693 seq, theMap, modelId);
1703 * Ask the structure viewer to open a session file. Returns true if
1704 * successful, else false (or not supported).
1709 public boolean openSession(String filepath)
1711 StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1716 executeCommand(cmd, true);
1717 // todo: test for failure - how?
1722 * Scans visible features in mapped positions of the CDS/peptide complement, and
1723 * adds any found to the map of attribute values/structure positions
1725 * @param complementRenderer
1726 * @param structureMapping
1729 * @param modelNumber
1731 protected static void scanComplementFeatures(
1732 FeatureRenderer complementRenderer,
1733 StructureMapping structureMapping, SequenceI seq,
1734 Map<String, Map<Object, AtomSpecModel>> theMap,
1738 * for each sequence residue mapped to a structure position...
1740 for (int seqPos : structureMapping.getMapping().keySet())
1743 * find visible complementary features at mapped position(s)
1745 MappedFeatures mf = complementRenderer
1746 .findComplementFeaturesAtResidue(seq, seqPos);
1749 for (SequenceFeature sf : mf.features)
1751 String type = sf.getType();
1754 * Don't copy features which originated from Chimera
1756 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1757 .equals(sf.getFeatureGroup()))
1763 * record feature 'value' (score/description/type) as at the
1764 * corresponding structure position
1766 List<int[]> mappedRanges = structureMapping
1767 .getPDBResNumRanges(seqPos, seqPos);
1769 if (!mappedRanges.isEmpty())
1771 String value = sf.getDescription();
1772 if (value == null || value.length() == 0)
1776 float score = sf.getScore();
1777 if (score != 0f && !Float.isNaN(score))
1779 value = Float.toString(score);
1781 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1782 if (featureValues == null)
1784 featureValues = new HashMap<>();
1785 theMap.put(type, featureValues);
1787 for (int[] range : mappedRanges)
1789 addAtomSpecRange(featureValues, value, modelNumber, range[0],
1790 range[1], structureMapping.getChain());
1799 * Inspect features on the sequence; for each feature that is visible,
1800 * determine its mapped ranges in the structure (if any) according to the
1801 * given mapping, and add them to the map.
1803 * @param visibleFeatures
1809 protected static void scanSequenceFeatures(List<String> visibleFeatures,
1810 StructureMapping mapping, SequenceI seq,
1811 Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1813 List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1814 visibleFeatures.toArray(new String[visibleFeatures.size()]));
1815 for (SequenceFeature sf : sfs)
1817 String type = sf.getType();
1820 * Don't copy features which originated from Chimera
1822 if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1823 .equals(sf.getFeatureGroup()))
1828 List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1831 if (!mappedRanges.isEmpty())
1833 String value = sf.getDescription();
1834 if (value == null || value.length() == 0)
1838 float score = sf.getScore();
1839 if (score != 0f && !Float.isNaN(score))
1841 value = Float.toString(score);
1843 Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1844 if (featureValues == null)
1846 featureValues = new HashMap<>();
1847 theMap.put(type, featureValues);
1849 for (int[] range : mappedRanges)
1851 addAtomSpecRange(featureValues, value, modelId, range[0],
1852 range[1], mapping.getChain());
1859 * Returns the number of structure files in the structure viewer and mapped to
1860 * Jalview. This may be zero if the files are still in the process of loading
1865 public int getMappedStructureCount()
1867 String[] files = getStructureFiles();
1868 return files == null ? 0 : files.length;
1872 * Starts a thread that waits for the external viewer program process to
1873 * finish, so that we can then close the associated resources. This avoids
1874 * leaving orphaned viewer panels in Jalview if the user closes the external
1879 protected void startExternalViewerMonitor(Process p)
1881 externalViewerMonitor = new Thread(new Runnable()
1890 JalviewStructureDisplayI display = getViewer();
1891 if (display != null)
1893 display.closeViewer(false);
1895 } catch (InterruptedException e)
1897 // exit thread if Chimera Viewer is closed in Jalview
1901 externalViewerMonitor.start();