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())
264 // false if any annotation present from this structure
265 // JBPNote this fails for jmol/chimera view because the *file* is
266 // passed, not the structure data ID -
267 if (MCview.PDBfile.isCalcIdForFile(ala.getCalcId(),
268 findIdForPDBFile(pdbFile)))
278 pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
279 if (pdb.id != null && pdb.id.trim().length() > 0
280 && FormatAdapter.FILE.equals(protocol))
282 registerPDBFile(pdb.id.trim(), pdbFile);
284 } catch (Exception ex)
286 ex.printStackTrace();
291 for (int s = 0; s < sequence.length; s++)
293 boolean infChain = true;
294 if (targetChains != null && targetChains[s] != null)
297 targetChain = targetChains[s];
299 else if (sequence[s].getName().indexOf("|") > -1)
301 targetChain = sequence[s].getName().substring(
302 sequence[s].getName().lastIndexOf("|") + 1);
303 if (targetChain.length() > 1)
305 if (targetChain.trim().length() == 0)
311 // not a valid chain identifier
322 AlignSeq maxAlignseq = null;
323 String maxChainId = " ";
324 PDBChain maxChain = null;
325 boolean first = true;
326 for (int i = 0; i < pdb.chains.size(); i++)
328 PDBChain chain = (pdb.chains.elementAt(i));
329 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
332 continue; // don't try to map chains don't match.
334 // TODO: correctly determine sequence type for mixed na/peptide
336 AlignSeq as = new AlignSeq(sequence[s],
337 pdb.chains.elementAt(i).sequence,
338 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
340 as.calcScoreMatrix();
343 if (first || as.maxscore > max
344 || (as.maxscore == max && chain.id.equals(targetChain)))
350 maxChainId = chain.id;
353 if (maxChain == null)
357 final StringBuffer mappingDetails = new StringBuffer();
358 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
359 + maxChain.sequence.getSequenceAsString());
360 mappingDetails.append("\nNo of residues = "
361 + maxChain.residues.size() + "\n\n");
362 PrintStream ps = new PrintStream(System.out)
364 public void print(String x)
366 mappingDetails.append(x);
369 public void println()
371 mappingDetails.append("\n");
375 maxAlignseq.printAlignment(ps);
377 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
378 + " " + maxAlignseq.seq2end);
379 mappingDetails.append("\nSEQ start/end "
380 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
381 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
383 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
385 maxChain.transferRESNUMFeatures(sequence[s], null);
387 // allocate enough slots to store the mapping from positions in
388 // sequence[s] to the associated chain
389 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
390 .getLength()) + 2][2];
396 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
397 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
399 resNum = tmp.resNumber;
400 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
401 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
405 } while (index < maxChain.atoms.size());
407 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
409 pdbFile = "INLINE" + pdb.id;
411 StructureMapping newMapping = new StructureMapping(sequence[s],
412 pdbFile, pdb.id, maxChainId, mapping,
413 mappingDetails.toString());
414 if (forStructureView)
417 if (mappings == null)
419 mappings = new StructureMapping[1];
423 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
424 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
428 mappings[mappings.length - 1] = newMapping;
430 maxChain.transferResidueAnnotation(newMapping);
437 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
439 listeners.removeElement(svl);
440 if (svl instanceof SequenceListener)
442 for (int i = 0; i < listeners.size(); i++)
444 if (listeners.elementAt(i) instanceof StructureListener)
446 ((StructureListener) listeners.elementAt(i))
447 .releaseReferences(svl);
452 if (pdbfiles == null)
456 boolean removeMapping = true;
458 Vector pdbs = new Vector();
459 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
463 StructureListener sl;
464 for (int i = 0; i < listeners.size(); i++)
466 if (listeners.elementAt(i) instanceof StructureListener)
468 sl = (StructureListener) listeners.elementAt(i);
469 handlepdbs = sl.getPdbFile();
470 for (int j = 0; j < handlepdbs.length; j++)
472 if (pdbs.contains(handlepdbs[j]))
474 pdbs.removeElement(handlepdbs[j]);
481 if (pdbs.size() > 0 && mappings != null)
483 Vector tmp = new Vector();
484 for (int i = 0; i < mappings.length; i++)
486 if (!pdbs.contains(mappings[i].pdbfile))
488 tmp.addElement(mappings[i]);
492 mappings = new StructureMapping[tmp.size()];
493 tmp.copyInto(mappings);
497 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
499 if (listeners == null)
501 // old or prematurely sent event
504 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
505 SearchResults results = null;
506 SequenceI lastseq = null;
507 int lastipos = -1, indexpos;
508 for (int i = 0; i < listeners.size(); i++)
510 if (listeners.elementAt(i) instanceof SequenceListener)
514 results = new SearchResults();
516 if (mappings != null)
518 for (int j = 0; j < mappings.length; j++)
520 if (mappings[j].pdbfile.equals(pdbfile)
521 && mappings[j].pdbchain.equals(chain))
523 indexpos = mappings[j].getSeqPos(pdbResNum);
524 if (lastipos != indexpos && lastseq != mappings[j].sequence)
526 results.addResult(mappings[j].sequence, indexpos, indexpos);
528 lastseq = mappings[j].sequence;
529 // construct highlighted sequence list
530 if (seqmappings != null)
533 Enumeration e = seqmappings.elements();
534 while (e.hasMoreElements())
537 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
538 mappings[j].sequence, indexpos, results);
550 for (int i = 0; i < listeners.size(); i++)
552 Object li = listeners.elementAt(i);
553 if (li instanceof SequenceListener)
555 ((SequenceListener) li).highlightSequence(results);
561 Vector seqmappings = null; // should be a simpler list of mapped seuqence
564 * highlight regions associated with a position (indexpos) in seq
567 * the sequeence that the mouse over occured on
569 * the absolute position being mouseovered in seq (0 to seq.length())
571 * the sequence position (if -1, seq.findPosition is called to
572 * resolve the residue number)
574 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
577 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
578 SearchResults results = null;
581 index = seq.findPosition(indexpos);
583 StructureListener sl;
585 for (int i = 0; i < listeners.size(); i++)
587 Object listener = listeners.elementAt(i);
588 if (listener == source)
592 if (listener instanceof StructureListener)
594 sl = (StructureListener) listener;
595 if (mappings == null)
599 for (int j = 0; j < mappings.length; j++)
601 if (mappings[j].sequence == seq
602 || mappings[j].sequence == seq.getDatasetSequence())
604 atomNo = mappings[j].getAtomNum(index);
608 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
609 mappings[j].pdbchain, mappings[j].pdbfile);
616 if (relaySeqMappings && hasSequenceListeners
617 && listener instanceof SequenceListener)
620 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
625 results = new SearchResults();
626 if (index >= seq.getStart() && index <= seq.getEnd())
628 // construct highlighted sequence list
630 if (seqmappings != null)
632 Enumeration e = seqmappings.elements();
633 while (e.hasMoreElements())
636 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
637 seq, index, results);
640 // hasSequenceListeners = results.getSize() > 0;
641 if (handlingVamsasMo)
643 // maybe have to resolve seq to a dataset seqeunce...
644 // add in additional direct sequence and/or dataset sequence
646 results.addResult(seq, index, index);
650 if (hasSequenceListeners)
652 ((SequenceListener) listener).highlightSequence(results);
655 else if (listener instanceof VamsasListener && !handlingVamsasMo)
658 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
661 // pass the mouse over and absolute position onto the
663 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
665 else if (listener instanceof SecondaryStructureListener)
667 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
675 * true if a mouse over event from an external (ie Vamsas) source is being
678 boolean handlingVamsasMo = false;
683 * as mouseOverSequence but only route event to SequenceListeners
687 * in an alignment sequence
689 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
692 handlingVamsasMo = true;
693 long msg = sequenceI.hashCode() * (1 + position);
697 mouseOverSequence(sequenceI, position, -1, source);
699 handlingVamsasMo = false;
702 public Annotation[] colourSequenceFromStructure(SequenceI seq,
706 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
707 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
709 * Annotation [] annotations = new Annotation[seq.getLength()];
711 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
712 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
713 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
715 * for (int j = 0; j < mappings.length; j++) {
717 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
718 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
719 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
720 * "+mappings[j].pdbfile);
722 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
723 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
725 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
726 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
727 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
728 * mappings[j].pdbfile); }
730 * annotations[index] = new Annotation("X",null,' ',0,col); } return
731 * annotations; } } } }
733 * return annotations;
737 public void structureSelectionChanged()
741 public void sequenceSelectionChanged()
745 public void sequenceColoursChanged(Object source)
747 StructureListener sl;
748 for (int i = 0; i < listeners.size(); i++)
750 if (listeners.elementAt(i) instanceof StructureListener)
752 sl = (StructureListener) listeners.elementAt(i);
753 sl.updateColours(source);
758 public StructureMapping[] getMapping(String pdbfile)
760 Vector tmp = new Vector();
761 if (mappings != null)
763 for (int i = 0; i < mappings.length; i++)
765 if (mappings[i].pdbfile.equals(pdbfile))
767 tmp.addElement(mappings[i]);
771 StructureMapping[] ret = new StructureMapping[tmp.size()];
772 for (int i = 0; i < tmp.size(); i++)
774 ret[i] = (StructureMapping) tmp.elementAt(i);
780 public String printMapping(String pdbfile)
782 StringBuffer sb = new StringBuffer();
783 for (int i = 0; i < mappings.length; i++)
785 if (mappings[i].pdbfile.equals(pdbfile))
787 sb.append(mappings[i].mappingDetails);
791 return sb.toString();
794 private int[] seqmappingrefs = null; // refcount for seqmappings elements
796 private synchronized void modifySeqMappingList(boolean add,
797 AlignedCodonFrame[] codonFrames)
799 if (!add && (seqmappings == null || seqmappings.size() == 0))
803 if (seqmappings == null)
805 seqmappings = new Vector();
807 if (codonFrames != null && codonFrames.length > 0)
809 for (int cf = 0; cf < codonFrames.length; cf++)
811 if (seqmappings.contains(codonFrames[cf]))
815 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
819 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
821 int pos = seqmappings.indexOf(codonFrames[cf]);
822 int[] nr = new int[seqmappingrefs.length - 1];
825 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
827 if (pos < seqmappingrefs.length - 1)
829 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
830 seqmappingrefs.length - pos - 2);
839 seqmappings.addElement(codonFrames[cf]);
841 int[] nsr = new int[(seqmappingrefs == null) ? 1
842 : seqmappingrefs.length + 1];
843 if (seqmappingrefs != null && seqmappingrefs.length > 0)
845 System.arraycopy(seqmappingrefs, 0, nsr, 0,
846 seqmappingrefs.length);
848 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
849 seqmappingrefs = nsr;
856 public void removeMappings(AlignedCodonFrame[] codonFrames)
858 modifySeqMappingList(false, codonFrames);
861 public void addMappings(AlignedCodonFrame[] codonFrames)
863 modifySeqMappingList(true, codonFrames);
866 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
868 public void addSelectionListener(SelectionListener selecter)
870 if (!sel_listeners.contains(selecter))
872 sel_listeners.addElement(selecter);
876 public void removeSelectionListener(SelectionListener toremove)
878 if (sel_listeners.contains(toremove))
880 sel_listeners.removeElement(toremove);
884 public synchronized void sendSelection(
885 jalview.datamodel.SequenceGroup selection,
886 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
888 if (sel_listeners != null && sel_listeners.size() > 0)
890 Enumeration listeners = sel_listeners.elements();
891 while (listeners.hasMoreElements())
893 SelectionListener slis = ((SelectionListener) listeners
897 slis.selection(selection, colsel, source);
904 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
906 public synchronized void sendViewPosition(
907 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
908 int startSeq, int endSeq)
911 if (view_listeners != null && view_listeners.size() > 0)
913 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
915 while (listeners.hasMoreElements())
917 AlignmentViewPanelListener slis = listeners.nextElement();
920 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
927 public void finalize() throws Throwable
929 if (listeners != null)
934 if (pdbIdFileName != null)
936 pdbIdFileName.clear();
937 pdbIdFileName = null;
939 if (sel_listeners != null)
941 sel_listeners.clear();
942 sel_listeners = null;
944 if (view_listeners != null)
946 view_listeners.clear();
947 view_listeners = null;
950 seqmappingrefs = null;
954 * release all references associated with this manager provider
958 public static void release(StructureSelectionManagerProvider jalviewLite)
960 // synchronized (instances)
962 if (instances == null)
966 StructureSelectionManager mnger = (instances.get(jalviewLite));
969 instances.remove(jalviewLite);
973 } catch (Throwable x)
981 public void registerPDBEntry(PDBEntry pdbentry)
983 if (pdbentry.getFile() != null
984 && pdbentry.getFile().trim().length() > 0)
986 registerPDBFile(pdbentry.getId(), pdbentry.getFile());