2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.structure;
23 import jalview.analysis.AlignSeq;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.datamodel.AlignedCodonFrame;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SearchResults;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.FormatAdapter;
32 import jalview.util.MessageManager;
34 import java.io.PrintStream;
35 import java.util.Enumeration;
36 import java.util.HashMap;
37 import java.util.IdentityHashMap;
38 import java.util.Vector;
41 import MCview.PDBChain;
43 public class StructureSelectionManager
45 static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
47 StructureMapping[] mappings;
50 * debug function - write all mappings to stdout
52 public void reportMapping()
56 System.err.println("reportMapping: No PDB/Sequence mappings.");
60 System.err.println("reportMapping: There are " + mappings.length
62 for (int m = 0; m < mappings.length; m++)
64 System.err.println("mapping " + m + " : " + mappings[m].pdbfile);
70 * map between the PDB IDs (or structure identifiers) used by Jalview and the
71 * absolute filenames for PDB data that corresponds to it
73 HashMap<String, String> pdbIdFileName = new HashMap<String, String>(),
74 pdbFileNameId = new HashMap<String, String>();
76 public void registerPDBFile(String idForFile, String absoluteFile)
78 pdbIdFileName.put(idForFile, absoluteFile);
79 pdbFileNameId.put(absoluteFile, idForFile);
82 public String findIdForPDBFile(String idOrFile)
84 String id = pdbFileNameId.get(idOrFile);
88 public String findFileForPDBId(String idOrFile)
90 String id = pdbIdFileName.get(idOrFile);
94 public boolean isPDBFileRegistered(String idOrFile)
96 return pdbFileNameId.containsKey(idOrFile)
97 || pdbIdFileName.containsKey(idOrFile);
100 private static StructureSelectionManager nullProvider = null;
102 public static StructureSelectionManager getStructureSelectionManager(
103 StructureSelectionManagerProvider context)
107 if (nullProvider == null)
109 if (instances != null)
111 throw new Error(MessageManager.getString("error.implementation_error_structure_selection_manager_null"),
112 new NullPointerException(MessageManager.getString("exception.ssm_context_is_null")));
116 nullProvider = new StructureSelectionManager();
121 if (instances == null)
123 instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
125 StructureSelectionManager instance = instances.get(context);
126 if (instance == null)
128 if (nullProvider != null)
130 instance = nullProvider;
134 instance = new StructureSelectionManager();
136 instances.put(context, instance);
142 * flag controlling whether SeqMappings are relayed from received sequence
143 * mouse over events to other sequences
145 boolean relaySeqMappings = true;
148 * Enable or disable relay of seqMapping events to other sequences. You might
149 * want to do this if there are many sequence mappings and the host computer
154 public void setRelaySeqMappings(boolean relay)
156 relaySeqMappings = relay;
160 * get the state of the relay seqMappings flag.
162 * @return true if sequence mouse overs are being relayed to other mapped
165 public boolean isRelaySeqMappingsEnabled()
167 return relaySeqMappings;
170 Vector listeners = new Vector();
173 * register a listener for alignment sequence mouseover events
177 public void addStructureViewerListener(Object svl)
179 if (!listeners.contains(svl))
181 listeners.addElement(svl);
185 public String alreadyMappedToFile(String pdbid)
187 if (mappings != null)
189 for (int i = 0; i < mappings.length; i++)
191 if (mappings[i].getPdbId().equals(pdbid))
193 return mappings[i].pdbfile;
201 * Import structure data and register a structure mapping for broadcasting
202 * colouring, mouseovers and selection events (convenience wrapper).
205 * - one or more sequences to be mapped to pdbFile
206 * @param targetChains
207 * - optional chain specification for mapping each sequence to pdb
208 * (may be nill, individual elements may be nill)
210 * - structure data resource
212 * - how to resolve data from resource
213 * @return null or the structure data parsed as a pdb file
215 synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
216 String[] targetChains, String pdbFile, String protocol)
218 return setMapping(true, sequence, targetChains, pdbFile, protocol);
222 * create sequence structure mappings between each sequence and the given
223 * pdbFile (retrieved via the given protocol).
225 * @param forStructureView
226 * when true, record the mapping for use in mouseOvers
229 * - one or more sequences to be mapped to pdbFile
230 * @param targetChains
231 * - optional chain specification for mapping each sequence to pdb
232 * (may be nill, individual elements may be nill)
234 * - structure data resource
236 * - how to resolve data from resource
237 * @return null or the structure data parsed as a pdb file
239 synchronized public MCview.PDBfile setMapping(boolean forStructureView,
240 SequenceI[] sequence,
241 String[] targetChains, String pdbFile, String protocol)
244 * There will be better ways of doing this in the future, for now we'll use
245 * the tried and tested MCview pdb mapping
247 MCview.PDBfile pdb = null;
248 boolean parseSecStr=true;
249 if (isPDBFileRegistered(pdbFile))
251 for (SequenceI sq : sequence)
254 while (ds.getDatasetSequence() != null)
256 ds = ds.getDatasetSequence();
259 if (ds.getAnnotation() != null)
261 for (AlignmentAnnotation ala : ds.getAnnotation())
263 // false if any annotation present from this structure
264 // JBPNote this fails for jmol/chimera view because the *file* is
265 // passed, not the structure data ID -
266 if (MCview.PDBfile.isCalcIdForFile(ala,
267 findIdForPDBFile(pdbFile)))
277 pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
278 if (pdb.id != null && pdb.id.trim().length() > 0
279 && FormatAdapter.FILE.equals(protocol))
281 registerPDBFile(pdb.id.trim(), pdbFile);
283 } catch (Exception ex)
285 ex.printStackTrace();
290 for (int s = 0; s < sequence.length; s++)
292 boolean infChain = true;
293 if (targetChains != null && targetChains[s] != null)
296 targetChain = targetChains[s];
298 else if (sequence[s].getName().indexOf("|") > -1)
300 targetChain = sequence[s].getName().substring(
301 sequence[s].getName().lastIndexOf("|") + 1);
302 if (targetChain.length() > 1)
304 if (targetChain.trim().length() == 0)
310 // not a valid chain identifier
321 AlignSeq maxAlignseq = null;
322 String maxChainId = " ";
323 PDBChain maxChain = null;
324 boolean first = true;
325 for (int i = 0; i < pdb.chains.size(); i++)
327 PDBChain chain = (pdb.chains.elementAt(i));
328 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
331 continue; // don't try to map chains don't match.
333 // TODO: correctly determine sequence type for mixed na/peptide
335 AlignSeq as = new AlignSeq(sequence[s],
336 pdb.chains.elementAt(i).sequence,
337 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
339 as.calcScoreMatrix();
342 if (first || as.maxscore > max
343 || (as.maxscore == max && chain.id.equals(targetChain)))
349 maxChainId = chain.id;
352 if (maxChain == null)
356 final StringBuffer mappingDetails = new StringBuffer();
357 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
358 + maxChain.sequence.getSequenceAsString());
359 mappingDetails.append("\nNo of residues = "
360 + maxChain.residues.size() + "\n\n");
361 PrintStream ps = new PrintStream(System.out)
363 public void print(String x)
365 mappingDetails.append(x);
368 public void println()
370 mappingDetails.append("\n");
374 maxAlignseq.printAlignment(ps);
376 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
377 + " " + maxAlignseq.seq2end);
378 mappingDetails.append("\nSEQ start/end "
379 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
380 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
382 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
384 maxChain.transferRESNUMFeatures(sequence[s], null);
386 // allocate enough slots to store the mapping from positions in
387 // sequence[s] to the associated chain
388 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
389 .getLength()) + 2][2];
395 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
396 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
398 resNum = tmp.resNumber;
399 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
400 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
404 } while (index < maxChain.atoms.size());
406 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
408 pdbFile = "INLINE" + pdb.id;
410 StructureMapping newMapping = new StructureMapping(sequence[s],
411 pdbFile, pdb.id, maxChainId, mapping,
412 mappingDetails.toString());
413 if (forStructureView)
416 if (mappings == null)
418 mappings = new StructureMapping[1];
422 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
423 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
427 mappings[mappings.length - 1] = newMapping;
429 maxChain.transferResidueAnnotation(newMapping);
436 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
438 listeners.removeElement(svl);
439 if (svl instanceof SequenceListener)
441 for (int i = 0; i < listeners.size(); i++)
443 if (listeners.elementAt(i) instanceof StructureListener)
445 ((StructureListener) listeners.elementAt(i))
446 .releaseReferences(svl);
451 if (pdbfiles == null)
455 boolean removeMapping = true;
457 Vector pdbs = new Vector();
458 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
462 StructureListener sl;
463 for (int i = 0; i < listeners.size(); i++)
465 if (listeners.elementAt(i) instanceof StructureListener)
467 sl = (StructureListener) listeners.elementAt(i);
468 handlepdbs = sl.getPdbFile();
469 for (int j = 0; j < handlepdbs.length; j++)
471 if (pdbs.contains(handlepdbs[j]))
473 pdbs.removeElement(handlepdbs[j]);
480 if (pdbs.size() > 0 && mappings != null)
482 Vector tmp = new Vector();
483 for (int i = 0; i < mappings.length; i++)
485 if (!pdbs.contains(mappings[i].pdbfile))
487 tmp.addElement(mappings[i]);
491 mappings = new StructureMapping[tmp.size()];
492 tmp.copyInto(mappings);
496 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
498 if (listeners == null)
500 // old or prematurely sent event
503 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
504 SearchResults results = null;
505 SequenceI lastseq = null;
506 int lastipos = -1, indexpos;
507 for (int i = 0; i < listeners.size(); i++)
509 if (listeners.elementAt(i) instanceof SequenceListener)
513 results = new SearchResults();
515 if (mappings != null)
517 for (int j = 0; j < mappings.length; j++)
519 if (mappings[j].pdbfile.equals(pdbfile)
520 && mappings[j].pdbchain.equals(chain))
522 indexpos = mappings[j].getSeqPos(pdbResNum);
523 if (lastipos != indexpos && lastseq != mappings[j].sequence)
525 results.addResult(mappings[j].sequence, indexpos, indexpos);
527 lastseq = mappings[j].sequence;
528 // construct highlighted sequence list
529 if (seqmappings != null)
532 Enumeration e = seqmappings.elements();
533 while (e.hasMoreElements())
536 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
537 mappings[j].sequence, indexpos, results);
549 for (int i = 0; i < listeners.size(); i++)
551 Object li = listeners.elementAt(i);
552 if (li instanceof SequenceListener)
554 ((SequenceListener) li).highlightSequence(results);
560 Vector seqmappings = null; // should be a simpler list of mapped seuqence
563 * highlight regions associated with a position (indexpos) in seq
566 * the sequeence that the mouse over occured on
568 * the absolute position being mouseovered in seq (0 to seq.length())
570 * the sequence position (if -1, seq.findPosition is called to
571 * resolve the residue number)
573 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
576 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
577 SearchResults results = null;
580 index = seq.findPosition(indexpos);
582 StructureListener sl;
584 for (int i = 0; i < listeners.size(); i++)
586 Object listener = listeners.elementAt(i);
587 if (listener == source)
591 if (listener instanceof StructureListener)
593 sl = (StructureListener) listener;
594 if (mappings == null)
598 for (int j = 0; j < mappings.length; j++)
600 if (mappings[j].sequence == seq
601 || mappings[j].sequence == seq.getDatasetSequence())
603 atomNo = mappings[j].getAtomNum(index);
607 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
608 mappings[j].pdbchain, mappings[j].pdbfile);
615 if (relaySeqMappings && hasSequenceListeners
616 && listener instanceof SequenceListener)
619 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
624 results = new SearchResults();
625 if (index >= seq.getStart() && index <= seq.getEnd())
627 // construct highlighted sequence list
629 if (seqmappings != null)
631 Enumeration e = seqmappings.elements();
632 while (e.hasMoreElements())
635 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
636 seq, index, results);
639 // hasSequenceListeners = results.getSize() > 0;
640 if (handlingVamsasMo)
642 // maybe have to resolve seq to a dataset seqeunce...
643 // add in additional direct sequence and/or dataset sequence
645 results.addResult(seq, index, index);
649 if (hasSequenceListeners)
651 ((SequenceListener) listener).highlightSequence(results);
654 else if (listener instanceof VamsasListener && !handlingVamsasMo)
657 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
660 // pass the mouse over and absolute position onto the
662 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
664 else if (listener instanceof SecondaryStructureListener)
666 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
674 * true if a mouse over event from an external (ie Vamsas) source is being
677 boolean handlingVamsasMo = false;
682 * as mouseOverSequence but only route event to SequenceListeners
686 * in an alignment sequence
688 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
691 handlingVamsasMo = true;
692 long msg = sequenceI.hashCode() * (1 + position);
696 mouseOverSequence(sequenceI, position, -1, source);
698 handlingVamsasMo = false;
701 public Annotation[] colourSequenceFromStructure(SequenceI seq,
705 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
706 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
708 * Annotation [] annotations = new Annotation[seq.getLength()];
710 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
711 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
712 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
714 * for (int j = 0; j < mappings.length; j++) {
716 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
717 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
718 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
719 * "+mappings[j].pdbfile);
721 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
722 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
724 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
725 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
726 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
727 * mappings[j].pdbfile); }
729 * annotations[index] = new Annotation("X",null,' ',0,col); } return
730 * annotations; } } } }
732 * return annotations;
736 public void structureSelectionChanged()
740 public void sequenceSelectionChanged()
744 public void sequenceColoursChanged(Object source)
746 StructureListener sl;
747 for (int i = 0; i < listeners.size(); i++)
749 if (listeners.elementAt(i) instanceof StructureListener)
751 sl = (StructureListener) listeners.elementAt(i);
752 sl.updateColours(source);
757 public StructureMapping[] getMapping(String pdbfile)
759 Vector tmp = new Vector();
760 if (mappings != null)
762 for (int i = 0; i < mappings.length; i++)
764 if (mappings[i].pdbfile.equals(pdbfile))
766 tmp.addElement(mappings[i]);
770 StructureMapping[] ret = new StructureMapping[tmp.size()];
771 for (int i = 0; i < tmp.size(); i++)
773 ret[i] = (StructureMapping) tmp.elementAt(i);
779 public String printMapping(String pdbfile)
781 StringBuffer sb = new StringBuffer();
782 for (int i = 0; i < mappings.length; i++)
784 if (mappings[i].pdbfile.equals(pdbfile))
786 sb.append(mappings[i].mappingDetails);
790 return sb.toString();
793 private int[] seqmappingrefs = null; // refcount for seqmappings elements
795 private synchronized void modifySeqMappingList(boolean add,
796 AlignedCodonFrame[] codonFrames)
798 if (!add && (seqmappings == null || seqmappings.size() == 0))
802 if (seqmappings == null)
804 seqmappings = new Vector();
806 if (codonFrames != null && codonFrames.length > 0)
808 for (int cf = 0; cf < codonFrames.length; cf++)
810 if (seqmappings.contains(codonFrames[cf]))
814 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
818 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
820 int pos = seqmappings.indexOf(codonFrames[cf]);
821 int[] nr = new int[seqmappingrefs.length - 1];
824 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
826 if (pos < seqmappingrefs.length - 1)
828 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
829 seqmappingrefs.length - pos - 2);
838 seqmappings.addElement(codonFrames[cf]);
840 int[] nsr = new int[(seqmappingrefs == null) ? 1
841 : seqmappingrefs.length + 1];
842 if (seqmappingrefs != null && seqmappingrefs.length > 0)
844 System.arraycopy(seqmappingrefs, 0, nsr, 0,
845 seqmappingrefs.length);
847 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
848 seqmappingrefs = nsr;
855 public void removeMappings(AlignedCodonFrame[] codonFrames)
857 modifySeqMappingList(false, codonFrames);
860 public void addMappings(AlignedCodonFrame[] codonFrames)
862 modifySeqMappingList(true, codonFrames);
865 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
867 public void addSelectionListener(SelectionListener selecter)
869 if (!sel_listeners.contains(selecter))
871 sel_listeners.addElement(selecter);
875 public void removeSelectionListener(SelectionListener toremove)
877 if (sel_listeners.contains(toremove))
879 sel_listeners.removeElement(toremove);
883 public synchronized void sendSelection(
884 jalview.datamodel.SequenceGroup selection,
885 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
887 if (sel_listeners != null && sel_listeners.size() > 0)
889 Enumeration listeners = sel_listeners.elements();
890 while (listeners.hasMoreElements())
892 SelectionListener slis = ((SelectionListener) listeners
896 slis.selection(selection, colsel, source);
903 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
905 public synchronized void sendViewPosition(
906 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
907 int startSeq, int endSeq)
910 if (view_listeners != null && view_listeners.size() > 0)
912 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
914 while (listeners.hasMoreElements())
916 AlignmentViewPanelListener slis = listeners.nextElement();
919 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
926 public void finalize() throws Throwable
928 if (listeners != null)
933 if (pdbIdFileName != null)
935 pdbIdFileName.clear();
936 pdbIdFileName = null;
938 if (sel_listeners != null)
940 sel_listeners.clear();
941 sel_listeners = null;
943 if (view_listeners != null)
945 view_listeners.clear();
946 view_listeners = null;
949 seqmappingrefs = null;
953 * release all references associated with this manager provider
957 public static void release(StructureSelectionManagerProvider jalviewLite)
959 // synchronized (instances)
961 if (instances == null)
965 StructureSelectionManager mnger = (instances.get(jalviewLite));
968 instances.remove(jalviewLite);
972 } catch (Throwable x)
980 public void registerPDBEntry(PDBEntry pdbentry)
982 if (pdbentry.getFile() != null
983 && pdbentry.getFile().trim().length() > 0)
985 registerPDBFile(pdbentry.getId(), pdbentry.getFile());