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 * create sequence structure mappings between each sequence and the given
202 * pdbFile (retrieved via the given protocol).
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)
219 * There will be better ways of doing this in the future, for now we'll use
220 * the tried and tested MCview pdb mapping
222 MCview.PDBfile pdb = null;
223 boolean parseSecStr=true;
224 for (SequenceI sq:sequence)
226 SequenceI ds = sq;while (ds.getDatasetSequence()!=null) { ds = ds.getDatasetSequence();};
227 if (ds.getAnnotation()!=null)
229 for (AlignmentAnnotation ala:ds.getAnnotation())
231 // false if any annotation present from this structure
232 if (MCview.PDBfile.isCalcIdForFile(ala.getCalcId(), pdbFile))
241 pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
243 } catch (Exception ex)
245 ex.printStackTrace();
250 for (int s = 0; s < sequence.length; s++)
252 boolean infChain = true;
253 if (targetChains != null && targetChains[s] != null)
256 targetChain = targetChains[s];
258 else if (sequence[s].getName().indexOf("|") > -1)
260 targetChain = sequence[s].getName().substring(
261 sequence[s].getName().lastIndexOf("|") + 1);
262 if (targetChain.length() > 1)
264 if (targetChain.trim().length() == 0)
270 // not a valid chain identifier
281 AlignSeq maxAlignseq = null;
282 String maxChainId = " ";
283 PDBChain maxChain = null;
284 boolean first = true;
285 for (int i = 0; i < pdb.chains.size(); i++)
287 PDBChain chain = (pdb.chains.elementAt(i));
288 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
291 continue; // don't try to map chains don't match.
293 // TODO: correctly determine sequence type for mixed na/peptide
295 AlignSeq as = new AlignSeq(sequence[s],
296 pdb.chains.elementAt(i).sequence,
297 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
299 as.calcScoreMatrix();
302 if (first || as.maxscore > max
303 || (as.maxscore == max && chain.id.equals(targetChain)))
309 maxChainId = chain.id;
312 if (maxChain == null)
316 final StringBuffer mappingDetails = new StringBuffer();
317 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
318 + maxChain.sequence.getSequenceAsString());
319 mappingDetails.append("\nNo of residues = "
320 + maxChain.residues.size() + "\n\n");
321 PrintStream ps = new PrintStream(System.out)
323 public void print(String x)
325 mappingDetails.append(x);
328 public void println()
330 mappingDetails.append("\n");
334 maxAlignseq.printAlignment(ps);
336 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
337 + " " + maxAlignseq.seq2end);
338 mappingDetails.append("\nSEQ start/end "
339 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
340 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
342 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
344 maxChain.transferRESNUMFeatures(sequence[s], null);
346 // allocate enough slots to store the mapping from positions in
347 // sequence[s] to the associated chain
348 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
349 .getLength()) + 2][2];
355 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
356 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
358 resNum = tmp.resNumber;
359 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
360 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
364 } while (index < maxChain.atoms.size());
366 if (mappings == null)
368 mappings = new StructureMapping[1];
372 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
373 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
377 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
379 pdbFile = "INLINE" + pdb.id;
382 mappings[mappings.length - 1] = new StructureMapping(sequence[s],
383 pdbFile, pdb.id, maxChainId, mapping,
384 mappingDetails.toString());
385 maxChain.transferResidueAnnotation(mappings[mappings.length - 1]);
392 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
394 listeners.removeElement(svl);
395 if (svl instanceof SequenceListener)
397 for (int i = 0; i < listeners.size(); i++)
399 if (listeners.elementAt(i) instanceof StructureListener)
401 ((StructureListener) listeners.elementAt(i))
402 .releaseReferences(svl);
407 if (pdbfiles == null)
411 boolean removeMapping = true;
413 Vector pdbs = new Vector();
414 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
418 StructureListener sl;
419 for (int i = 0; i < listeners.size(); i++)
421 if (listeners.elementAt(i) instanceof StructureListener)
423 sl = (StructureListener) listeners.elementAt(i);
424 handlepdbs = sl.getPdbFile();
425 for (int j = 0; j < handlepdbs.length; j++)
427 if (pdbs.contains(handlepdbs[j]))
429 pdbs.removeElement(handlepdbs[j]);
436 if (pdbs.size() > 0 && mappings != null)
438 Vector tmp = new Vector();
439 for (int i = 0; i < mappings.length; i++)
441 if (!pdbs.contains(mappings[i].pdbfile))
443 tmp.addElement(mappings[i]);
447 mappings = new StructureMapping[tmp.size()];
448 tmp.copyInto(mappings);
452 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
454 if (listeners == null)
456 // old or prematurely sent event
459 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
460 SearchResults results = null;
461 SequenceI lastseq = null;
462 int lastipos = -1, indexpos;
463 for (int i = 0; i < listeners.size(); i++)
465 if (listeners.elementAt(i) instanceof SequenceListener)
469 results = new SearchResults();
471 if (mappings != null)
473 for (int j = 0; j < mappings.length; j++)
475 if (mappings[j].pdbfile.equals(pdbfile)
476 && mappings[j].pdbchain.equals(chain))
478 indexpos = mappings[j].getSeqPos(pdbResNum);
479 if (lastipos != indexpos && lastseq != mappings[j].sequence)
481 results.addResult(mappings[j].sequence, indexpos, indexpos);
483 lastseq = mappings[j].sequence;
484 // construct highlighted sequence list
485 if (seqmappings != null)
488 Enumeration e = seqmappings.elements();
489 while (e.hasMoreElements())
492 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
493 mappings[j].sequence, indexpos, results);
505 for (int i = 0; i < listeners.size(); i++)
507 Object li = listeners.elementAt(i);
508 if (li instanceof SequenceListener)
510 ((SequenceListener) li).highlightSequence(results);
516 Vector seqmappings = null; // should be a simpler list of mapped seuqence
519 * highlight regions associated with a position (indexpos) in seq
522 * the sequeence that the mouse over occured on
524 * the absolute position being mouseovered in seq (0 to seq.length())
526 * the sequence position (if -1, seq.findPosition is called to
527 * resolve the residue number)
529 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
532 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
533 SearchResults results = null;
536 index = seq.findPosition(indexpos);
538 StructureListener sl;
540 for (int i = 0; i < listeners.size(); i++)
542 Object listener = listeners.elementAt(i);
543 if (listener == source)
547 if (listener instanceof StructureListener)
549 sl = (StructureListener) listener;
550 if (mappings == null)
554 for (int j = 0; j < mappings.length; j++)
556 if (mappings[j].sequence == seq
557 || mappings[j].sequence == seq.getDatasetSequence())
559 atomNo = mappings[j].getAtomNum(index);
563 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
564 mappings[j].pdbchain, mappings[j].pdbfile);
571 if (relaySeqMappings && hasSequenceListeners
572 && listener instanceof SequenceListener)
575 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
580 results = new SearchResults();
581 if (index >= seq.getStart() && index <= seq.getEnd())
583 // construct highlighted sequence list
585 if (seqmappings != null)
587 Enumeration e = seqmappings.elements();
588 while (e.hasMoreElements())
591 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
592 seq, index, results);
595 // hasSequenceListeners = results.getSize() > 0;
596 if (handlingVamsasMo)
598 // maybe have to resolve seq to a dataset seqeunce...
599 // add in additional direct sequence and/or dataset sequence
601 results.addResult(seq, index, index);
605 if (hasSequenceListeners)
607 ((SequenceListener) listener).highlightSequence(results);
610 else if (listener instanceof VamsasListener && !handlingVamsasMo)
613 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
616 // pass the mouse over and absolute position onto the
618 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
620 else if (listener instanceof SecondaryStructureListener)
622 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
630 * true if a mouse over event from an external (ie Vamsas) source is being
633 boolean handlingVamsasMo = false;
638 * as mouseOverSequence but only route event to SequenceListeners
642 * in an alignment sequence
644 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
647 handlingVamsasMo = true;
648 long msg = sequenceI.hashCode() * (1 + position);
652 mouseOverSequence(sequenceI, position, -1, source);
654 handlingVamsasMo = false;
657 public Annotation[] colourSequenceFromStructure(SequenceI seq,
661 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
662 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
664 * Annotation [] annotations = new Annotation[seq.getLength()];
666 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
667 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
668 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
670 * for (int j = 0; j < mappings.length; j++) {
672 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
673 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
674 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
675 * "+mappings[j].pdbfile);
677 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
678 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
680 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
681 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
682 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
683 * mappings[j].pdbfile); }
685 * annotations[index] = new Annotation("X",null,' ',0,col); } return
686 * annotations; } } } }
688 * return annotations;
692 public void structureSelectionChanged()
696 public void sequenceSelectionChanged()
700 public void sequenceColoursChanged(Object source)
702 StructureListener sl;
703 for (int i = 0; i < listeners.size(); i++)
705 if (listeners.elementAt(i) instanceof StructureListener)
707 sl = (StructureListener) listeners.elementAt(i);
708 sl.updateColours(source);
713 public StructureMapping[] getMapping(String pdbfile)
715 Vector tmp = new Vector();
716 if (mappings != null)
718 for (int i = 0; i < mappings.length; i++)
720 if (mappings[i].pdbfile.equals(pdbfile))
722 tmp.addElement(mappings[i]);
726 StructureMapping[] ret = new StructureMapping[tmp.size()];
727 for (int i = 0; i < tmp.size(); i++)
729 ret[i] = (StructureMapping) tmp.elementAt(i);
735 public String printMapping(String pdbfile)
737 StringBuffer sb = new StringBuffer();
738 for (int i = 0; i < mappings.length; i++)
740 if (mappings[i].pdbfile.equals(pdbfile))
742 sb.append(mappings[i].mappingDetails);
746 return sb.toString();
749 private int[] seqmappingrefs = null; // refcount for seqmappings elements
751 private synchronized void modifySeqMappingList(boolean add,
752 AlignedCodonFrame[] codonFrames)
754 if (!add && (seqmappings == null || seqmappings.size() == 0))
758 if (seqmappings == null)
760 seqmappings = new Vector();
762 if (codonFrames != null && codonFrames.length > 0)
764 for (int cf = 0; cf < codonFrames.length; cf++)
766 if (seqmappings.contains(codonFrames[cf]))
770 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
774 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
776 int pos = seqmappings.indexOf(codonFrames[cf]);
777 int[] nr = new int[seqmappingrefs.length - 1];
780 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
782 if (pos < seqmappingrefs.length - 1)
784 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
785 seqmappingrefs.length - pos - 2);
794 seqmappings.addElement(codonFrames[cf]);
796 int[] nsr = new int[(seqmappingrefs == null) ? 1
797 : seqmappingrefs.length + 1];
798 if (seqmappingrefs != null && seqmappingrefs.length > 0)
800 System.arraycopy(seqmappingrefs, 0, nsr, 0,
801 seqmappingrefs.length);
803 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
804 seqmappingrefs = nsr;
811 public void removeMappings(AlignedCodonFrame[] codonFrames)
813 modifySeqMappingList(false, codonFrames);
816 public void addMappings(AlignedCodonFrame[] codonFrames)
818 modifySeqMappingList(true, codonFrames);
821 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
823 public void addSelectionListener(SelectionListener selecter)
825 if (!sel_listeners.contains(selecter))
827 sel_listeners.addElement(selecter);
831 public void removeSelectionListener(SelectionListener toremove)
833 if (sel_listeners.contains(toremove))
835 sel_listeners.removeElement(toremove);
839 public synchronized void sendSelection(
840 jalview.datamodel.SequenceGroup selection,
841 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
843 if (sel_listeners != null && sel_listeners.size() > 0)
845 Enumeration listeners = sel_listeners.elements();
846 while (listeners.hasMoreElements())
848 SelectionListener slis = ((SelectionListener) listeners
852 slis.selection(selection, colsel, source);
859 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
861 public synchronized void sendViewPosition(
862 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
863 int startSeq, int endSeq)
866 if (view_listeners != null && view_listeners.size() > 0)
868 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
870 while (listeners.hasMoreElements())
872 AlignmentViewPanelListener slis = listeners.nextElement();
875 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
882 public void finalize() throws Throwable
884 if (listeners != null)
889 if (pdbIdFileName != null)
891 pdbIdFileName.clear();
892 pdbIdFileName = null;
894 if (sel_listeners != null)
896 sel_listeners.clear();
897 sel_listeners = null;
899 if (view_listeners != null)
901 view_listeners.clear();
902 view_listeners = null;
905 seqmappingrefs = null;
909 * release all references associated with this manager provider
913 public static void release(StructureSelectionManagerProvider jalviewLite)
915 // synchronized (instances)
917 if (instances == null)
921 StructureSelectionManager mnger = (instances.get(jalviewLite));
924 instances.remove(jalviewLite);
928 } catch (Throwable x)
936 public void registerPDBEntry(PDBEntry pdbentry)
938 if (pdbentry.getFile() != null
939 && pdbentry.getFile().trim().length() > 0)
941 registerPDBFile(pdbentry.getId(), pdbentry.getFile());