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 for (SequenceI sq:sequence)
251 SequenceI ds = sq;while (ds.getDatasetSequence()!=null) { ds = ds.getDatasetSequence();};
252 if (ds.getAnnotation()!=null)
254 for (AlignmentAnnotation ala:ds.getAnnotation())
256 // false if any annotation present from this structure
257 if (MCview.PDBfile.isCalcIdForFile(ala.getCalcId(), pdbFile))
266 pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
268 } catch (Exception ex)
270 ex.printStackTrace();
275 for (int s = 0; s < sequence.length; s++)
277 boolean infChain = true;
278 if (targetChains != null && targetChains[s] != null)
281 targetChain = targetChains[s];
283 else if (sequence[s].getName().indexOf("|") > -1)
285 targetChain = sequence[s].getName().substring(
286 sequence[s].getName().lastIndexOf("|") + 1);
287 if (targetChain.length() > 1)
289 if (targetChain.trim().length() == 0)
295 // not a valid chain identifier
306 AlignSeq maxAlignseq = null;
307 String maxChainId = " ";
308 PDBChain maxChain = null;
309 boolean first = true;
310 for (int i = 0; i < pdb.chains.size(); i++)
312 PDBChain chain = (pdb.chains.elementAt(i));
313 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
316 continue; // don't try to map chains don't match.
318 // TODO: correctly determine sequence type for mixed na/peptide
320 AlignSeq as = new AlignSeq(sequence[s],
321 pdb.chains.elementAt(i).sequence,
322 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
324 as.calcScoreMatrix();
327 if (first || as.maxscore > max
328 || (as.maxscore == max && chain.id.equals(targetChain)))
334 maxChainId = chain.id;
337 if (maxChain == null)
341 final StringBuffer mappingDetails = new StringBuffer();
342 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
343 + maxChain.sequence.getSequenceAsString());
344 mappingDetails.append("\nNo of residues = "
345 + maxChain.residues.size() + "\n\n");
346 PrintStream ps = new PrintStream(System.out)
348 public void print(String x)
350 mappingDetails.append(x);
353 public void println()
355 mappingDetails.append("\n");
359 maxAlignseq.printAlignment(ps);
361 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
362 + " " + maxAlignseq.seq2end);
363 mappingDetails.append("\nSEQ start/end "
364 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
365 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
367 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
369 maxChain.transferRESNUMFeatures(sequence[s], null);
371 // allocate enough slots to store the mapping from positions in
372 // sequence[s] to the associated chain
373 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
374 .getLength()) + 2][2];
380 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
381 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
383 resNum = tmp.resNumber;
384 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
385 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
389 } while (index < maxChain.atoms.size());
391 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
393 pdbFile = "INLINE" + pdb.id;
395 StructureMapping newMapping = new StructureMapping(sequence[s],
396 pdbFile, pdb.id, maxChainId, mapping,
397 mappingDetails.toString());
398 if (forStructureView)
401 if (mappings == null)
403 mappings = new StructureMapping[1];
407 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
408 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
412 mappings[mappings.length - 1] = newMapping;
414 maxChain.transferResidueAnnotation(newMapping);
421 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
423 listeners.removeElement(svl);
424 if (svl instanceof SequenceListener)
426 for (int i = 0; i < listeners.size(); i++)
428 if (listeners.elementAt(i) instanceof StructureListener)
430 ((StructureListener) listeners.elementAt(i))
431 .releaseReferences(svl);
436 if (pdbfiles == null)
440 boolean removeMapping = true;
442 Vector pdbs = new Vector();
443 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
447 StructureListener sl;
448 for (int i = 0; i < listeners.size(); i++)
450 if (listeners.elementAt(i) instanceof StructureListener)
452 sl = (StructureListener) listeners.elementAt(i);
453 handlepdbs = sl.getPdbFile();
454 for (int j = 0; j < handlepdbs.length; j++)
456 if (pdbs.contains(handlepdbs[j]))
458 pdbs.removeElement(handlepdbs[j]);
465 if (pdbs.size() > 0 && mappings != null)
467 Vector tmp = new Vector();
468 for (int i = 0; i < mappings.length; i++)
470 if (!pdbs.contains(mappings[i].pdbfile))
472 tmp.addElement(mappings[i]);
476 mappings = new StructureMapping[tmp.size()];
477 tmp.copyInto(mappings);
481 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
483 if (listeners == null)
485 // old or prematurely sent event
488 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
489 SearchResults results = null;
490 SequenceI lastseq = null;
491 int lastipos = -1, indexpos;
492 for (int i = 0; i < listeners.size(); i++)
494 if (listeners.elementAt(i) instanceof SequenceListener)
498 results = new SearchResults();
500 if (mappings != null)
502 for (int j = 0; j < mappings.length; j++)
504 if (mappings[j].pdbfile.equals(pdbfile)
505 && mappings[j].pdbchain.equals(chain))
507 indexpos = mappings[j].getSeqPos(pdbResNum);
508 if (lastipos != indexpos && lastseq != mappings[j].sequence)
510 results.addResult(mappings[j].sequence, indexpos, indexpos);
512 lastseq = mappings[j].sequence;
513 // construct highlighted sequence list
514 if (seqmappings != null)
517 Enumeration e = seqmappings.elements();
518 while (e.hasMoreElements())
521 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
522 mappings[j].sequence, indexpos, results);
534 for (int i = 0; i < listeners.size(); i++)
536 Object li = listeners.elementAt(i);
537 if (li instanceof SequenceListener)
539 ((SequenceListener) li).highlightSequence(results);
545 Vector seqmappings = null; // should be a simpler list of mapped seuqence
548 * highlight regions associated with a position (indexpos) in seq
551 * the sequeence that the mouse over occured on
553 * the absolute position being mouseovered in seq (0 to seq.length())
555 * the sequence position (if -1, seq.findPosition is called to
556 * resolve the residue number)
558 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
561 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
562 SearchResults results = null;
565 index = seq.findPosition(indexpos);
567 StructureListener sl;
569 for (int i = 0; i < listeners.size(); i++)
571 Object listener = listeners.elementAt(i);
572 if (listener == source)
576 if (listener instanceof StructureListener)
578 sl = (StructureListener) listener;
579 if (mappings == null)
583 for (int j = 0; j < mappings.length; j++)
585 if (mappings[j].sequence == seq
586 || mappings[j].sequence == seq.getDatasetSequence())
588 atomNo = mappings[j].getAtomNum(index);
592 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
593 mappings[j].pdbchain, mappings[j].pdbfile);
600 if (relaySeqMappings && hasSequenceListeners
601 && listener instanceof SequenceListener)
604 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
609 results = new SearchResults();
610 if (index >= seq.getStart() && index <= seq.getEnd())
612 // construct highlighted sequence list
614 if (seqmappings != null)
616 Enumeration e = seqmappings.elements();
617 while (e.hasMoreElements())
620 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
621 seq, index, results);
624 // hasSequenceListeners = results.getSize() > 0;
625 if (handlingVamsasMo)
627 // maybe have to resolve seq to a dataset seqeunce...
628 // add in additional direct sequence and/or dataset sequence
630 results.addResult(seq, index, index);
634 if (hasSequenceListeners)
636 ((SequenceListener) listener).highlightSequence(results);
639 else if (listener instanceof VamsasListener && !handlingVamsasMo)
642 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
645 // pass the mouse over and absolute position onto the
647 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
649 else if (listener instanceof SecondaryStructureListener)
651 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
659 * true if a mouse over event from an external (ie Vamsas) source is being
662 boolean handlingVamsasMo = false;
667 * as mouseOverSequence but only route event to SequenceListeners
671 * in an alignment sequence
673 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
676 handlingVamsasMo = true;
677 long msg = sequenceI.hashCode() * (1 + position);
681 mouseOverSequence(sequenceI, position, -1, source);
683 handlingVamsasMo = false;
686 public Annotation[] colourSequenceFromStructure(SequenceI seq,
690 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
691 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
693 * Annotation [] annotations = new Annotation[seq.getLength()];
695 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
696 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
697 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
699 * for (int j = 0; j < mappings.length; j++) {
701 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
702 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
703 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
704 * "+mappings[j].pdbfile);
706 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
707 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
709 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
710 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
711 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
712 * mappings[j].pdbfile); }
714 * annotations[index] = new Annotation("X",null,' ',0,col); } return
715 * annotations; } } } }
717 * return annotations;
721 public void structureSelectionChanged()
725 public void sequenceSelectionChanged()
729 public void sequenceColoursChanged(Object source)
731 StructureListener sl;
732 for (int i = 0; i < listeners.size(); i++)
734 if (listeners.elementAt(i) instanceof StructureListener)
736 sl = (StructureListener) listeners.elementAt(i);
737 sl.updateColours(source);
742 public StructureMapping[] getMapping(String pdbfile)
744 Vector tmp = new Vector();
745 if (mappings != null)
747 for (int i = 0; i < mappings.length; i++)
749 if (mappings[i].pdbfile.equals(pdbfile))
751 tmp.addElement(mappings[i]);
755 StructureMapping[] ret = new StructureMapping[tmp.size()];
756 for (int i = 0; i < tmp.size(); i++)
758 ret[i] = (StructureMapping) tmp.elementAt(i);
764 public String printMapping(String pdbfile)
766 StringBuffer sb = new StringBuffer();
767 for (int i = 0; i < mappings.length; i++)
769 if (mappings[i].pdbfile.equals(pdbfile))
771 sb.append(mappings[i].mappingDetails);
775 return sb.toString();
778 private int[] seqmappingrefs = null; // refcount for seqmappings elements
780 private synchronized void modifySeqMappingList(boolean add,
781 AlignedCodonFrame[] codonFrames)
783 if (!add && (seqmappings == null || seqmappings.size() == 0))
787 if (seqmappings == null)
789 seqmappings = new Vector();
791 if (codonFrames != null && codonFrames.length > 0)
793 for (int cf = 0; cf < codonFrames.length; cf++)
795 if (seqmappings.contains(codonFrames[cf]))
799 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
803 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
805 int pos = seqmappings.indexOf(codonFrames[cf]);
806 int[] nr = new int[seqmappingrefs.length - 1];
809 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
811 if (pos < seqmappingrefs.length - 1)
813 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
814 seqmappingrefs.length - pos - 2);
823 seqmappings.addElement(codonFrames[cf]);
825 int[] nsr = new int[(seqmappingrefs == null) ? 1
826 : seqmappingrefs.length + 1];
827 if (seqmappingrefs != null && seqmappingrefs.length > 0)
829 System.arraycopy(seqmappingrefs, 0, nsr, 0,
830 seqmappingrefs.length);
832 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
833 seqmappingrefs = nsr;
840 public void removeMappings(AlignedCodonFrame[] codonFrames)
842 modifySeqMappingList(false, codonFrames);
845 public void addMappings(AlignedCodonFrame[] codonFrames)
847 modifySeqMappingList(true, codonFrames);
850 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
852 public void addSelectionListener(SelectionListener selecter)
854 if (!sel_listeners.contains(selecter))
856 sel_listeners.addElement(selecter);
860 public void removeSelectionListener(SelectionListener toremove)
862 if (sel_listeners.contains(toremove))
864 sel_listeners.removeElement(toremove);
868 public synchronized void sendSelection(
869 jalview.datamodel.SequenceGroup selection,
870 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
872 if (sel_listeners != null && sel_listeners.size() > 0)
874 Enumeration listeners = sel_listeners.elements();
875 while (listeners.hasMoreElements())
877 SelectionListener slis = ((SelectionListener) listeners
881 slis.selection(selection, colsel, source);
888 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
890 public synchronized void sendViewPosition(
891 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
892 int startSeq, int endSeq)
895 if (view_listeners != null && view_listeners.size() > 0)
897 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
899 while (listeners.hasMoreElements())
901 AlignmentViewPanelListener slis = listeners.nextElement();
904 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
911 public void finalize() throws Throwable
913 if (listeners != null)
918 if (pdbIdFileName != null)
920 pdbIdFileName.clear();
921 pdbIdFileName = null;
923 if (sel_listeners != null)
925 sel_listeners.clear();
926 sel_listeners = null;
928 if (view_listeners != null)
930 view_listeners.clear();
931 view_listeners = null;
934 seqmappingrefs = null;
938 * release all references associated with this manager provider
942 public static void release(StructureSelectionManagerProvider jalviewLite)
944 // synchronized (instances)
946 if (instances == null)
950 StructureSelectionManager mnger = (instances.get(jalviewLite));
953 instances.remove(jalviewLite);
957 } catch (Throwable x)
965 public void registerPDBEntry(PDBEntry pdbentry)
967 if (pdbentry.getFile() != null
968 && pdbentry.getFile().trim().length() > 0)
970 registerPDBFile(pdbentry.getId(), pdbentry.getFile());