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;
192 boolean parseSecStr=true;
193 for (SequenceI sq:sequence)
195 SequenceI ds = sq;while (ds.getDatasetSequence()!=null) { ds = ds.getDatasetSequence();};
196 if (ds.getAnnotation()!=null)
198 for (AlignmentAnnotation ala:ds.getAnnotation())
200 // false if any annotation present from this structure
201 if (MCview.PDBfile.isCalcIdForFile(ala.getCalcId(), pdbFile))
210 pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
212 } catch (Exception ex)
214 ex.printStackTrace();
219 for (int s = 0; s < sequence.length; s++)
221 boolean infChain = true;
222 if (targetChains != null && targetChains[s] != null)
225 targetChain = targetChains[s];
227 else if (sequence[s].getName().indexOf("|") > -1)
229 targetChain = sequence[s].getName().substring(
230 sequence[s].getName().lastIndexOf("|") + 1);
231 if (targetChain.length() > 1)
233 if (targetChain.trim().length() == 0)
239 // not a valid chain identifier
250 AlignSeq maxAlignseq = null;
251 String maxChainId = " ";
252 PDBChain maxChain = null;
253 boolean first = true;
254 for (int i = 0; i < pdb.chains.size(); i++)
256 PDBChain chain = (pdb.chains.elementAt(i));
257 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
260 continue; // don't try to map chains don't match.
262 // TODO: correctly determine sequence type for mixed na/peptide
264 AlignSeq as = new AlignSeq(sequence[s],
265 pdb.chains.elementAt(i).sequence,
266 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
268 as.calcScoreMatrix();
271 if (first || as.maxscore > max
272 || (as.maxscore == max && chain.id.equals(targetChain)))
278 maxChainId = chain.id;
281 if (maxChain == null)
285 final StringBuffer mappingDetails = new StringBuffer();
286 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
287 + maxChain.sequence.getSequenceAsString());
288 mappingDetails.append("\nNo of residues = "
289 + maxChain.residues.size() + "\n\n");
290 PrintStream ps = new PrintStream(System.out)
292 public void print(String x)
294 mappingDetails.append(x);
297 public void println()
299 mappingDetails.append("\n");
303 maxAlignseq.printAlignment(ps);
305 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
306 + " " + maxAlignseq.seq2end);
307 mappingDetails.append("\nSEQ start/end "
308 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
309 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
311 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
313 maxChain.transferRESNUMFeatures(sequence[s], null);
315 // allocate enough slots to store the mapping from positions in
316 // sequence[s] to the associated chain
317 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
318 .getLength()) + 2][2];
324 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
325 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
327 resNum = tmp.resNumber;
328 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
329 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
333 } while (index < maxChain.atoms.size());
335 if (mappings == null)
337 mappings = new StructureMapping[1];
341 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
342 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
346 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
348 pdbFile = "INLINE" + pdb.id;
351 mappings[mappings.length - 1] = new StructureMapping(sequence[s],
352 pdbFile, pdb.id, maxChainId, mapping,
353 mappingDetails.toString());
354 maxChain.transferResidueAnnotation(mappings[mappings.length - 1]);
361 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
363 listeners.removeElement(svl);
364 if (svl instanceof SequenceListener)
366 for (int i = 0; i < listeners.size(); i++)
368 if (listeners.elementAt(i) instanceof StructureListener)
370 ((StructureListener) listeners.elementAt(i))
371 .releaseReferences(svl);
376 if (pdbfiles == null)
380 boolean removeMapping = true;
382 Vector pdbs = new Vector();
383 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
387 StructureListener sl;
388 for (int i = 0; i < listeners.size(); i++)
390 if (listeners.elementAt(i) instanceof StructureListener)
392 sl = (StructureListener) listeners.elementAt(i);
393 handlepdbs = sl.getPdbFile();
394 for (int j = 0; j < handlepdbs.length; j++)
396 if (pdbs.contains(handlepdbs[j]))
398 pdbs.removeElement(handlepdbs[j]);
405 if (pdbs.size() > 0 && mappings != null)
407 Vector tmp = new Vector();
408 for (int i = 0; i < mappings.length; i++)
410 if (!pdbs.contains(mappings[i].pdbfile))
412 tmp.addElement(mappings[i]);
416 mappings = new StructureMapping[tmp.size()];
417 tmp.copyInto(mappings);
421 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
423 if (listeners == null)
425 // old or prematurely sent event
428 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
429 SearchResults results = null;
430 SequenceI lastseq = null;
431 int lastipos = -1, indexpos;
432 for (int i = 0; i < listeners.size(); i++)
434 if (listeners.elementAt(i) instanceof SequenceListener)
438 results = new SearchResults();
440 if (mappings != null)
442 for (int j = 0; j < mappings.length; j++)
444 if (mappings[j].pdbfile.equals(pdbfile)
445 && mappings[j].pdbchain.equals(chain))
447 indexpos = mappings[j].getSeqPos(pdbResNum);
448 if (lastipos != indexpos && lastseq != mappings[j].sequence)
450 results.addResult(mappings[j].sequence, indexpos, indexpos);
452 lastseq = mappings[j].sequence;
453 // construct highlighted sequence list
454 if (seqmappings != null)
457 Enumeration e = seqmappings.elements();
458 while (e.hasMoreElements())
461 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
462 mappings[j].sequence, indexpos, results);
474 for (int i = 0; i < listeners.size(); i++)
476 Object li = listeners.elementAt(i);
477 if (li instanceof SequenceListener)
479 ((SequenceListener) li).highlightSequence(results);
485 Vector seqmappings = null; // should be a simpler list of mapped seuqence
488 * highlight regions associated with a position (indexpos) in seq
491 * the sequeence that the mouse over occured on
493 * the absolute position being mouseovered in seq (0 to seq.length())
495 * the sequence position (if -1, seq.findPosition is called to
496 * resolve the residue number)
498 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
501 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
502 SearchResults results = null;
505 index = seq.findPosition(indexpos);
507 StructureListener sl;
509 for (int i = 0; i < listeners.size(); i++)
511 Object listener = listeners.elementAt(i);
512 if (listener == source)
516 if (listener instanceof StructureListener)
518 sl = (StructureListener) listener;
519 if (mappings == null)
523 for (int j = 0; j < mappings.length; j++)
525 if (mappings[j].sequence == seq
526 || mappings[j].sequence == seq.getDatasetSequence())
528 atomNo = mappings[j].getAtomNum(index);
532 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
533 mappings[j].pdbchain, mappings[j].pdbfile);
540 if (relaySeqMappings && hasSequenceListeners
541 && listener instanceof SequenceListener)
544 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
549 results = new SearchResults();
550 if (index >= seq.getStart() && index <= seq.getEnd())
552 // construct highlighted sequence list
554 if (seqmappings != null)
556 Enumeration e = seqmappings.elements();
557 while (e.hasMoreElements())
560 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
561 seq, index, results);
564 // hasSequenceListeners = results.getSize() > 0;
565 if (handlingVamsasMo)
567 // maybe have to resolve seq to a dataset seqeunce...
568 // add in additional direct sequence and/or dataset sequence
570 results.addResult(seq, index, index);
574 if (hasSequenceListeners)
576 ((SequenceListener) listener).highlightSequence(results);
579 else if (listener instanceof VamsasListener && !handlingVamsasMo)
582 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
585 // pass the mouse over and absolute position onto the
587 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
589 else if (listener instanceof SecondaryStructureListener)
591 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
599 * true if a mouse over event from an external (ie Vamsas) source is being
602 boolean handlingVamsasMo = false;
607 * as mouseOverSequence but only route event to SequenceListeners
611 * in an alignment sequence
613 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
616 handlingVamsasMo = true;
617 long msg = sequenceI.hashCode() * (1 + position);
621 mouseOverSequence(sequenceI, position, -1, source);
623 handlingVamsasMo = false;
626 public Annotation[] colourSequenceFromStructure(SequenceI seq,
630 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
631 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
633 * Annotation [] annotations = new Annotation[seq.getLength()];
635 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
636 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
637 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
639 * for (int j = 0; j < mappings.length; j++) {
641 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
642 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
643 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
644 * "+mappings[j].pdbfile);
646 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
647 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
649 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
650 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
651 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
652 * mappings[j].pdbfile); }
654 * annotations[index] = new Annotation("X",null,' ',0,col); } return
655 * annotations; } } } }
657 * return annotations;
661 public void structureSelectionChanged()
665 public void sequenceSelectionChanged()
669 public void sequenceColoursChanged(Object source)
671 StructureListener sl;
672 for (int i = 0; i < listeners.size(); i++)
674 if (listeners.elementAt(i) instanceof StructureListener)
676 sl = (StructureListener) listeners.elementAt(i);
677 sl.updateColours(source);
682 public StructureMapping[] getMapping(String pdbfile)
684 Vector tmp = new Vector();
685 if (mappings != null)
687 for (int i = 0; i < mappings.length; i++)
689 if (mappings[i].pdbfile.equals(pdbfile))
691 tmp.addElement(mappings[i]);
695 StructureMapping[] ret = new StructureMapping[tmp.size()];
696 for (int i = 0; i < tmp.size(); i++)
698 ret[i] = (StructureMapping) tmp.elementAt(i);
704 public String printMapping(String pdbfile)
706 StringBuffer sb = new StringBuffer();
707 for (int i = 0; i < mappings.length; i++)
709 if (mappings[i].pdbfile.equals(pdbfile))
711 sb.append(mappings[i].mappingDetails);
715 return sb.toString();
718 private int[] seqmappingrefs = null; // refcount for seqmappings elements
720 private synchronized void modifySeqMappingList(boolean add,
721 AlignedCodonFrame[] codonFrames)
723 if (!add && (seqmappings == null || seqmappings.size() == 0))
727 if (seqmappings == null)
729 seqmappings = new Vector();
731 if (codonFrames != null && codonFrames.length > 0)
733 for (int cf = 0; cf < codonFrames.length; cf++)
735 if (seqmappings.contains(codonFrames[cf]))
739 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
743 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
745 int pos = seqmappings.indexOf(codonFrames[cf]);
746 int[] nr = new int[seqmappingrefs.length - 1];
749 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
751 if (pos < seqmappingrefs.length - 1)
753 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
754 seqmappingrefs.length - pos - 2);
763 seqmappings.addElement(codonFrames[cf]);
765 int[] nsr = new int[(seqmappingrefs == null) ? 1
766 : seqmappingrefs.length + 1];
767 if (seqmappingrefs != null && seqmappingrefs.length > 0)
769 System.arraycopy(seqmappingrefs, 0, nsr, 0,
770 seqmappingrefs.length);
772 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
773 seqmappingrefs = nsr;
780 public void removeMappings(AlignedCodonFrame[] codonFrames)
782 modifySeqMappingList(false, codonFrames);
785 public void addMappings(AlignedCodonFrame[] codonFrames)
787 modifySeqMappingList(true, codonFrames);
790 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
792 public void addSelectionListener(SelectionListener selecter)
794 if (!sel_listeners.contains(selecter))
796 sel_listeners.addElement(selecter);
800 public void removeSelectionListener(SelectionListener toremove)
802 if (sel_listeners.contains(toremove))
804 sel_listeners.removeElement(toremove);
808 public synchronized void sendSelection(
809 jalview.datamodel.SequenceGroup selection,
810 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
812 if (sel_listeners != null && sel_listeners.size() > 0)
814 Enumeration listeners = sel_listeners.elements();
815 while (listeners.hasMoreElements())
817 SelectionListener slis = ((SelectionListener) listeners
821 slis.selection(selection, colsel, source);
828 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
830 public synchronized void sendViewPosition(
831 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
832 int startSeq, int endSeq)
835 if (view_listeners != null && view_listeners.size() > 0)
837 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
839 while (listeners.hasMoreElements())
841 AlignmentViewPanelListener slis = listeners.nextElement();
844 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
851 public void finalize() throws Throwable
853 if (listeners != null)
858 if (mappingData != null)
863 if (sel_listeners != null)
865 sel_listeners.clear();
866 sel_listeners = null;
868 if (view_listeners != null)
870 view_listeners.clear();
871 view_listeners = null;
874 seqmappingrefs = null;
878 * release all references associated with this manager provider
882 public static void release(StructureSelectionManagerProvider jalviewLite)
884 // synchronized (instances)
886 if (instances == null)
890 StructureSelectionManager mnger = (instances.get(jalviewLite));
893 instances.remove(jalviewLite);
897 } catch (Throwable x)