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.SearchResults;
29 import jalview.datamodel.SequenceI;
30 import jalview.util.MessageManager;
32 import java.io.PrintStream;
33 import java.util.Enumeration;
34 import java.util.Hashtable;
35 import java.util.IdentityHashMap;
36 import java.util.Vector;
39 import MCview.PDBChain;
41 public class StructureSelectionManager
43 static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
45 StructureMapping[] mappings;
48 * debug function - write all mappings to stdout
50 public void reportMapping()
54 System.err.println("reportMapping: No PDB/Sequence mappings.");
58 System.err.println("reportMapping: There are " + mappings.length
60 for (int m = 0; m < mappings.length; m++)
62 System.err.println("mapping " + m + " : " + mappings[m].pdbfile);
67 Hashtable mappingData = new Hashtable();
69 private static StructureSelectionManager nullProvider = null;
71 public static StructureSelectionManager getStructureSelectionManager(
72 StructureSelectionManagerProvider context)
76 if (nullProvider == null)
78 if (instances != null)
80 throw new Error(MessageManager.getString("error.implementation_error_structure_selection_manager_null"),
81 new NullPointerException(MessageManager.getString("exception.ssm_context_is_null")));
85 nullProvider = new StructureSelectionManager();
90 if (instances == null)
92 instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
94 StructureSelectionManager instance = instances.get(context);
97 if (nullProvider != null)
99 instance = nullProvider;
103 instance = new StructureSelectionManager();
105 instances.put(context, instance);
111 * flag controlling whether SeqMappings are relayed from received sequence
112 * mouse over events to other sequences
114 boolean relaySeqMappings = true;
117 * Enable or disable relay of seqMapping events to other sequences. You might
118 * want to do this if there are many sequence mappings and the host computer
123 public void setRelaySeqMappings(boolean relay)
125 relaySeqMappings = relay;
129 * get the state of the relay seqMappings flag.
131 * @return true if sequence mouse overs are being relayed to other mapped
134 public boolean isRelaySeqMappingsEnabled()
136 return relaySeqMappings;
139 Vector listeners = new Vector();
142 * register a listener for alignment sequence mouseover events
146 public void addStructureViewerListener(Object svl)
148 if (!listeners.contains(svl))
150 listeners.addElement(svl);
154 public String alreadyMappedToFile(String pdbid)
156 if (mappings != null)
158 for (int i = 0; i < mappings.length; i++)
160 if (mappings[i].getPdbId().equals(pdbid))
162 return mappings[i].pdbfile;
170 * create sequence structure mappings between each sequence and the given
171 * pdbFile (retrieved via the given protocol).
174 * - one or more sequences to be mapped to pdbFile
175 * @param targetChains
176 * - optional chain specification for mapping each sequence to pdb
177 * (may be nill, individual elements may be nill)
179 * - structure data resource
181 * - how to resolve data from resource
182 * @return null or the structure data parsed as a pdb file
184 synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
185 String[] targetChains, String pdbFile, String protocol)
188 * There will be better ways of doing this in the future, for now we'll use
189 * the tried and tested MCview pdb mapping
191 MCview.PDBfile pdb = null;
194 pdb = new MCview.PDBfile(pdbFile, protocol);
195 } catch (Exception ex)
197 ex.printStackTrace();
202 for (int s = 0; s < sequence.length; s++)
204 boolean infChain = true;
205 if (targetChains != null && targetChains[s] != null)
208 targetChain = targetChains[s];
210 else if (sequence[s].getName().indexOf("|") > -1)
212 targetChain = sequence[s].getName().substring(
213 sequence[s].getName().lastIndexOf("|") + 1);
214 if (targetChain.length() > 1)
216 if (targetChain.trim().length() == 0)
222 // not a valid chain identifier
233 AlignSeq maxAlignseq = null;
234 String maxChainId = " ";
235 PDBChain maxChain = null;
236 boolean first = true;
237 for (int i = 0; i < pdb.chains.size(); i++)
239 PDBChain chain = ((PDBChain) pdb.chains.elementAt(i));
240 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
243 continue; // don't try to map chains don't match.
245 // TODO: correctly determine sequence type for mixed na/peptide
247 AlignSeq as = new AlignSeq(sequence[s],
248 ((PDBChain) pdb.chains.elementAt(i)).sequence,
249 ((PDBChain) pdb.chains.elementAt(i)).isNa ? AlignSeq.DNA
251 as.calcScoreMatrix();
254 if (first || as.maxscore > max
255 || (as.maxscore == max && chain.id.equals(targetChain)))
261 maxChainId = chain.id;
264 if (maxChain == null)
268 final StringBuffer mappingDetails = new StringBuffer();
269 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
270 + maxChain.sequence.getSequenceAsString());
271 mappingDetails.append("\nNo of residues = "
272 + maxChain.residues.size() + "\n\n");
273 PrintStream ps = new PrintStream(System.out)
275 public void print(String x)
277 mappingDetails.append(x);
280 public void println()
282 mappingDetails.append("\n");
286 maxAlignseq.printAlignment(ps);
288 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
289 + " " + maxAlignseq.seq2end);
290 mappingDetails.append("\nSEQ start/end "
291 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
292 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
294 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
296 maxChain.transferRESNUMFeatures(sequence[s], null);
298 // allocate enough slots to store the mapping from positions in
299 // sequence[s] to the associated chain
300 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
301 .getLength()) + 2][2];
307 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
308 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
310 resNum = tmp.resNumber;
311 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
312 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
316 } while (index < maxChain.atoms.size());
318 if (mappings == null)
320 mappings = new StructureMapping[1];
324 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
325 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
329 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
331 pdbFile = "INLINE" + pdb.id;
334 mappings[mappings.length - 1] = new StructureMapping(sequence[s],
335 pdbFile, pdb.id, maxChainId, mapping,
336 mappingDetails.toString());
337 maxChain.transferResidueAnnotation(mappings[mappings.length - 1]);
344 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
346 listeners.removeElement(svl);
347 if (svl instanceof SequenceListener)
349 for (int i = 0; i < listeners.size(); i++)
351 if (listeners.elementAt(i) instanceof StructureListener)
353 ((StructureListener) listeners.elementAt(i))
354 .releaseReferences(svl);
359 if (pdbfiles == null)
363 boolean removeMapping = true;
365 Vector pdbs = new Vector();
366 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
370 StructureListener sl;
371 for (int i = 0; i < listeners.size(); i++)
373 if (listeners.elementAt(i) instanceof StructureListener)
375 sl = (StructureListener) listeners.elementAt(i);
376 handlepdbs = sl.getPdbFile();
377 for (int j = 0; j < handlepdbs.length; j++)
379 if (pdbs.contains(handlepdbs[j]))
381 pdbs.removeElement(handlepdbs[j]);
388 if (pdbs.size() > 0 && mappings != null)
390 Vector tmp = new Vector();
391 for (int i = 0; i < mappings.length; i++)
393 if (!pdbs.contains(mappings[i].pdbfile))
395 tmp.addElement(mappings[i]);
399 mappings = new StructureMapping[tmp.size()];
400 tmp.copyInto(mappings);
404 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
406 if (listeners == null)
408 // old or prematurely sent event
411 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
412 SearchResults results = null;
413 SequenceI lastseq = null;
414 int lastipos = -1, indexpos;
415 for (int i = 0; i < listeners.size(); i++)
417 if (listeners.elementAt(i) instanceof SequenceListener)
421 results = new SearchResults();
423 if (mappings != null)
425 for (int j = 0; j < mappings.length; j++)
427 if (mappings[j].pdbfile.equals(pdbfile)
428 && mappings[j].pdbchain.equals(chain))
430 indexpos = mappings[j].getSeqPos(pdbResNum);
431 if (lastipos != indexpos && lastseq != mappings[j].sequence)
433 results.addResult(mappings[j].sequence, indexpos, indexpos);
435 lastseq = mappings[j].sequence;
436 // construct highlighted sequence list
437 if (seqmappings != null)
440 Enumeration e = seqmappings.elements();
441 while (e.hasMoreElements())
444 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
445 mappings[j].sequence, indexpos, results);
457 for (int i = 0; i < listeners.size(); i++)
459 Object li = listeners.elementAt(i);
460 if (li instanceof SequenceListener)
462 ((SequenceListener) li).highlightSequence(results);
468 Vector seqmappings = null; // should be a simpler list of mapped seuqence
471 * highlight regions associated with a position (indexpos) in seq
474 * the sequeence that the mouse over occured on
476 * the absolute position being mouseovered in seq (0 to seq.length())
478 * the sequence position (if -1, seq.findPosition is called to
479 * resolve the residue number)
481 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
484 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
485 SearchResults results = null;
488 index = seq.findPosition(indexpos);
490 StructureListener sl;
492 for (int i = 0; i < listeners.size(); i++)
494 Object listener = listeners.elementAt(i);
495 if (listener == source)
499 if (listener instanceof StructureListener)
501 sl = (StructureListener) listener;
502 if (mappings == null)
506 for (int j = 0; j < mappings.length; j++)
508 if (mappings[j].sequence == seq
509 || mappings[j].sequence == seq.getDatasetSequence())
511 atomNo = mappings[j].getAtomNum(index);
515 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
516 mappings[j].pdbchain, mappings[j].pdbfile);
523 if (relaySeqMappings && hasSequenceListeners
524 && listener instanceof SequenceListener)
527 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
532 results = new SearchResults();
533 if (index >= seq.getStart() && index <= seq.getEnd())
535 // construct highlighted sequence list
537 if (seqmappings != null)
539 Enumeration e = seqmappings.elements();
540 while (e.hasMoreElements())
543 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
544 seq, index, results);
547 // hasSequenceListeners = results.getSize() > 0;
548 if (handlingVamsasMo)
550 // maybe have to resolve seq to a dataset seqeunce...
551 // add in additional direct sequence and/or dataset sequence
553 results.addResult(seq, index, index);
557 if (hasSequenceListeners)
559 ((SequenceListener) listener).highlightSequence(results);
562 else if (listener instanceof VamsasListener && !handlingVamsasMo)
565 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
568 // pass the mouse over and absolute position onto the
570 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
572 else if (listener instanceof SecondaryStructureListener)
574 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
582 * true if a mouse over event from an external (ie Vamsas) source is being
585 boolean handlingVamsasMo = false;
590 * as mouseOverSequence but only route event to SequenceListeners
594 * in an alignment sequence
596 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
599 handlingVamsasMo = true;
600 long msg = sequenceI.hashCode() * (1 + position);
604 mouseOverSequence(sequenceI, position, -1, source);
606 handlingVamsasMo = false;
609 public Annotation[] colourSequenceFromStructure(SequenceI seq,
613 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
614 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
616 * Annotation [] annotations = new Annotation[seq.getLength()];
618 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
619 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
620 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
622 * for (int j = 0; j < mappings.length; j++) {
624 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
625 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
626 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
627 * "+mappings[j].pdbfile);
629 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
630 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
632 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
633 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
634 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
635 * mappings[j].pdbfile); }
637 * annotations[index] = new Annotation("X",null,' ',0,col); } return
638 * annotations; } } } }
640 * return annotations;
644 public void structureSelectionChanged()
648 public void sequenceSelectionChanged()
652 public void sequenceColoursChanged(Object source)
654 StructureListener sl;
655 for (int i = 0; i < listeners.size(); i++)
657 if (listeners.elementAt(i) instanceof StructureListener)
659 sl = (StructureListener) listeners.elementAt(i);
660 sl.updateColours(source);
665 public StructureMapping[] getMapping(String pdbfile)
667 Vector tmp = new Vector();
668 if (mappings != null)
670 for (int i = 0; i < mappings.length; i++)
672 if (mappings[i].pdbfile.equals(pdbfile))
674 tmp.addElement(mappings[i]);
678 StructureMapping[] ret = new StructureMapping[tmp.size()];
679 for (int i = 0; i < tmp.size(); i++)
681 ret[i] = (StructureMapping) tmp.elementAt(i);
687 public String printMapping(String pdbfile)
689 StringBuffer sb = new StringBuffer();
690 for (int i = 0; i < mappings.length; i++)
692 if (mappings[i].pdbfile.equals(pdbfile))
694 sb.append(mappings[i].mappingDetails);
698 return sb.toString();
701 private int[] seqmappingrefs = null; // refcount for seqmappings elements
703 private synchronized void modifySeqMappingList(boolean add,
704 AlignedCodonFrame[] codonFrames)
706 if (!add && (seqmappings == null || seqmappings.size() == 0))
710 if (seqmappings == null)
712 seqmappings = new Vector();
714 if (codonFrames != null && codonFrames.length > 0)
716 for (int cf = 0; cf < codonFrames.length; cf++)
718 if (seqmappings.contains(codonFrames[cf]))
722 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
726 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
728 int pos = seqmappings.indexOf(codonFrames[cf]);
729 int[] nr = new int[seqmappingrefs.length - 1];
732 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
734 if (pos < seqmappingrefs.length - 1)
736 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
737 seqmappingrefs.length - pos - 2);
746 seqmappings.addElement(codonFrames[cf]);
748 int[] nsr = new int[(seqmappingrefs == null) ? 1
749 : seqmappingrefs.length + 1];
750 if (seqmappingrefs != null && seqmappingrefs.length > 0)
752 System.arraycopy(seqmappingrefs, 0, nsr, 0,
753 seqmappingrefs.length);
755 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
756 seqmappingrefs = nsr;
763 public void removeMappings(AlignedCodonFrame[] codonFrames)
765 modifySeqMappingList(false, codonFrames);
768 public void addMappings(AlignedCodonFrame[] codonFrames)
770 modifySeqMappingList(true, codonFrames);
773 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
775 public void addSelectionListener(SelectionListener selecter)
777 if (!sel_listeners.contains(selecter))
779 sel_listeners.addElement(selecter);
783 public void removeSelectionListener(SelectionListener toremove)
785 if (sel_listeners.contains(toremove))
787 sel_listeners.removeElement(toremove);
791 public synchronized void sendSelection(
792 jalview.datamodel.SequenceGroup selection,
793 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
795 if (sel_listeners != null && sel_listeners.size() > 0)
797 Enumeration listeners = sel_listeners.elements();
798 while (listeners.hasMoreElements())
800 SelectionListener slis = ((SelectionListener) listeners
804 slis.selection(selection, colsel, source);
811 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
813 public synchronized void sendViewPosition(
814 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
815 int startSeq, int endSeq)
818 if (view_listeners != null && view_listeners.size() > 0)
820 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
822 while (listeners.hasMoreElements())
824 AlignmentViewPanelListener slis = listeners.nextElement();
827 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
834 public void finalize() throws Throwable
836 if (listeners != null)
841 if (mappingData != null)
846 if (sel_listeners != null)
848 sel_listeners.clear();
849 sel_listeners = null;
851 if (view_listeners != null)
853 view_listeners.clear();
854 view_listeners = null;
857 seqmappingrefs = null;
861 * release all references associated with this manager provider
865 public static void release(StructureSelectionManagerProvider jalviewLite)
867 // synchronized (instances)
869 if (instances == null)
873 StructureSelectionManager mnger = (instances.get(jalviewLite));
876 instances.remove(jalviewLite);
880 } catch (Throwable x)