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.AppletFormatAdapter;
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())
263 // false if any annotation present from this structure
264 // JBPNote this fails for jmol/chimera view because the *file* is
265 // passed, not the structure data ID -
266 if (MCview.PDBfile.isCalcIdForFile(ala,
267 findIdForPDBFile(pdbFile)))
277 pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
278 if (pdb.id != null && pdb.id.trim().length() > 0
279 && AppletFormatAdapter.FILE.equals(protocol))
281 registerPDBFile(pdb.id.trim(), pdbFile);
283 } catch (Exception ex)
285 ex.printStackTrace();
290 for (int s = 0; s < sequence.length; s++)
292 boolean infChain = true;
293 if (targetChains != null && targetChains[s] != null)
296 targetChain = targetChains[s];
298 else if (sequence[s].getName().indexOf("|") > -1)
300 targetChain = sequence[s].getName().substring(
301 sequence[s].getName().lastIndexOf("|") + 1);
302 if (targetChain.length() > 1)
304 if (targetChain.trim().length() == 0)
310 // not a valid chain identifier
321 AlignSeq maxAlignseq = null;
322 String maxChainId = " ";
323 PDBChain maxChain = null;
324 boolean first = true;
325 for (int i = 0; i < pdb.chains.size(); i++)
327 PDBChain chain = (pdb.chains.elementAt(i));
328 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
331 continue; // don't try to map chains don't match.
333 // TODO: correctly determine sequence type for mixed na/peptide
335 AlignSeq as = new AlignSeq(sequence[s],
336 pdb.chains.elementAt(i).sequence,
337 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
339 as.calcScoreMatrix();
342 if (first || as.maxscore > max
343 || (as.maxscore == max && chain.id.equals(targetChain)))
349 maxChainId = chain.id;
352 if (maxChain == null)
356 final StringBuffer mappingDetails = new StringBuffer();
357 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
358 + maxChain.sequence.getSequenceAsString());
359 mappingDetails.append("\nNo of residues = "
360 + maxChain.residues.size() + "\n\n");
361 PrintStream ps = new PrintStream(System.out)
363 public void print(String x)
365 mappingDetails.append(x);
368 public void println()
370 mappingDetails.append("\n");
374 maxAlignseq.printAlignment(ps);
376 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
377 + " " + maxAlignseq.seq2end);
378 mappingDetails.append("\nSEQ start/end "
379 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
380 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
382 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
383 jalview.datamodel.Mapping sqmpping = maxAlignseq
384 .getMappingFromS1(false);
385 jalview.datamodel.Mapping omap = new jalview.datamodel.Mapping(
386 sqmpping.getMap().getInverse());
387 maxChain.transferRESNUMFeatures(sequence[s], null);
389 // allocate enough slots to store the mapping from positions in
390 // sequence[s] to the associated chain
391 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
392 .getLength()) + 2][2];
398 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
399 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
401 resNum = tmp.resNumber;
402 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
403 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
407 } while (index < maxChain.atoms.size());
409 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
411 pdbFile = "INLINE" + pdb.id;
413 StructureMapping newMapping = new StructureMapping(sequence[s],
414 pdbFile, pdb.id, maxChainId, mapping,
415 mappingDetails.toString());
416 if (forStructureView)
419 if (mappings == null)
421 mappings = new StructureMapping[1];
425 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
426 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
430 mappings[mappings.length - 1] = newMapping;
432 maxChain.transferResidueAnnotation(newMapping, sqmpping);
439 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
441 listeners.removeElement(svl);
442 if (svl instanceof SequenceListener)
444 for (int i = 0; i < listeners.size(); i++)
446 if (listeners.elementAt(i) instanceof StructureListener)
448 ((StructureListener) listeners.elementAt(i))
449 .releaseReferences(svl);
454 if (pdbfiles == null)
458 boolean removeMapping = true;
460 Vector pdbs = new Vector();
461 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
465 StructureListener sl;
466 for (int i = 0; i < listeners.size(); i++)
468 if (listeners.elementAt(i) instanceof StructureListener)
470 sl = (StructureListener) listeners.elementAt(i);
471 handlepdbs = sl.getPdbFile();
472 for (int j = 0; j < handlepdbs.length; j++)
474 if (pdbs.contains(handlepdbs[j]))
476 pdbs.removeElement(handlepdbs[j]);
483 if (pdbs.size() > 0 && mappings != null)
485 Vector tmp = new Vector();
486 for (int i = 0; i < mappings.length; i++)
488 if (!pdbs.contains(mappings[i].pdbfile))
490 tmp.addElement(mappings[i]);
494 mappings = new StructureMapping[tmp.size()];
495 tmp.copyInto(mappings);
499 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
501 if (listeners == null)
503 // old or prematurely sent event
506 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
507 SearchResults results = null;
508 SequenceI lastseq = null;
509 int lastipos = -1, indexpos;
510 for (int i = 0; i < listeners.size(); i++)
512 if (listeners.elementAt(i) instanceof SequenceListener)
516 results = new SearchResults();
518 if (mappings != null)
520 for (int j = 0; j < mappings.length; j++)
522 if (mappings[j].pdbfile.equals(pdbfile)
523 && mappings[j].pdbchain.equals(chain))
525 indexpos = mappings[j].getSeqPos(pdbResNum);
526 if (lastipos != indexpos && lastseq != mappings[j].sequence)
528 results.addResult(mappings[j].sequence, indexpos, indexpos);
530 lastseq = mappings[j].sequence;
531 // construct highlighted sequence list
532 if (seqmappings != null)
535 Enumeration e = seqmappings.elements();
536 while (e.hasMoreElements())
539 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
540 mappings[j].sequence, indexpos, results);
552 for (int i = 0; i < listeners.size(); i++)
554 Object li = listeners.elementAt(i);
555 if (li instanceof SequenceListener)
557 ((SequenceListener) li).highlightSequence(results);
563 Vector seqmappings = null; // should be a simpler list of mapped seuqence
566 * highlight regions associated with a position (indexpos) in seq
569 * the sequeence that the mouse over occured on
571 * the absolute position being mouseovered in seq (0 to seq.length())
573 * the sequence position (if -1, seq.findPosition is called to
574 * resolve the residue number)
576 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
579 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
580 SearchResults results = null;
583 index = seq.findPosition(indexpos);
585 StructureListener sl;
587 for (int i = 0; i < listeners.size(); i++)
589 Object listener = listeners.elementAt(i);
590 if (listener == source)
594 if (listener instanceof StructureListener)
596 sl = (StructureListener) listener;
597 if (mappings == null)
601 for (int j = 0; j < mappings.length; j++)
603 if (mappings[j].sequence == seq
604 || mappings[j].sequence == seq.getDatasetSequence())
606 atomNo = mappings[j].getAtomNum(index);
610 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
611 mappings[j].pdbchain, mappings[j].pdbfile);
618 if (relaySeqMappings && hasSequenceListeners
619 && listener instanceof SequenceListener)
622 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
627 results = new SearchResults();
628 if (index >= seq.getStart() && index <= seq.getEnd())
630 // construct highlighted sequence list
632 if (seqmappings != null)
634 Enumeration e = seqmappings.elements();
635 while (e.hasMoreElements())
638 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
639 seq, index, results);
642 // hasSequenceListeners = results.getSize() > 0;
643 if (handlingVamsasMo)
645 // maybe have to resolve seq to a dataset seqeunce...
646 // add in additional direct sequence and/or dataset sequence
648 results.addResult(seq, index, index);
652 if (hasSequenceListeners)
654 ((SequenceListener) listener).highlightSequence(results);
657 else if (listener instanceof VamsasListener && !handlingVamsasMo)
660 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
663 // pass the mouse over and absolute position onto the
665 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
667 else if (listener instanceof SecondaryStructureListener)
669 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
677 * true if a mouse over event from an external (ie Vamsas) source is being
680 boolean handlingVamsasMo = false;
685 * as mouseOverSequence but only route event to SequenceListeners
689 * in an alignment sequence
691 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
694 handlingVamsasMo = true;
695 long msg = sequenceI.hashCode() * (1 + position);
699 mouseOverSequence(sequenceI, position, -1, source);
701 handlingVamsasMo = false;
704 public Annotation[] colourSequenceFromStructure(SequenceI seq,
708 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
709 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
711 * Annotation [] annotations = new Annotation[seq.getLength()];
713 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
714 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
715 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
717 * for (int j = 0; j < mappings.length; j++) {
719 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
720 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
721 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
722 * "+mappings[j].pdbfile);
724 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
725 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
727 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
728 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
729 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
730 * mappings[j].pdbfile); }
732 * annotations[index] = new Annotation("X",null,' ',0,col); } return
733 * annotations; } } } }
735 * return annotations;
739 public void structureSelectionChanged()
743 public void sequenceSelectionChanged()
747 public void sequenceColoursChanged(Object source)
749 StructureListener sl;
750 for (int i = 0; i < listeners.size(); i++)
752 if (listeners.elementAt(i) instanceof StructureListener)
754 sl = (StructureListener) listeners.elementAt(i);
755 sl.updateColours(source);
760 public StructureMapping[] getMapping(String pdbfile)
762 Vector tmp = new Vector();
763 if (mappings != null)
765 for (int i = 0; i < mappings.length; i++)
767 if (mappings[i].pdbfile.equals(pdbfile))
769 tmp.addElement(mappings[i]);
773 StructureMapping[] ret = new StructureMapping[tmp.size()];
774 for (int i = 0; i < tmp.size(); i++)
776 ret[i] = (StructureMapping) tmp.elementAt(i);
782 public String printMapping(String pdbfile)
784 StringBuffer sb = new StringBuffer();
785 for (int i = 0; i < mappings.length; i++)
787 if (mappings[i].pdbfile.equals(pdbfile))
789 sb.append(mappings[i].mappingDetails);
793 return sb.toString();
796 private int[] seqmappingrefs = null; // refcount for seqmappings elements
798 private synchronized void modifySeqMappingList(boolean add,
799 AlignedCodonFrame[] codonFrames)
801 if (!add && (seqmappings == null || seqmappings.size() == 0))
805 if (seqmappings == null)
807 seqmappings = new Vector();
809 if (codonFrames != null && codonFrames.length > 0)
811 for (int cf = 0; cf < codonFrames.length; cf++)
813 if (seqmappings.contains(codonFrames[cf]))
817 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
821 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
823 int pos = seqmappings.indexOf(codonFrames[cf]);
824 int[] nr = new int[seqmappingrefs.length - 1];
827 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
829 if (pos < seqmappingrefs.length - 1)
831 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
832 seqmappingrefs.length - pos - 2);
841 seqmappings.addElement(codonFrames[cf]);
843 int[] nsr = new int[(seqmappingrefs == null) ? 1
844 : seqmappingrefs.length + 1];
845 if (seqmappingrefs != null && seqmappingrefs.length > 0)
847 System.arraycopy(seqmappingrefs, 0, nsr, 0,
848 seqmappingrefs.length);
850 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
851 seqmappingrefs = nsr;
858 public void removeMappings(AlignedCodonFrame[] codonFrames)
860 modifySeqMappingList(false, codonFrames);
863 public void addMappings(AlignedCodonFrame[] codonFrames)
865 modifySeqMappingList(true, codonFrames);
868 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
870 public void addSelectionListener(SelectionListener selecter)
872 if (!sel_listeners.contains(selecter))
874 sel_listeners.addElement(selecter);
878 public void removeSelectionListener(SelectionListener toremove)
880 if (sel_listeners.contains(toremove))
882 sel_listeners.removeElement(toremove);
886 public synchronized void sendSelection(
887 jalview.datamodel.SequenceGroup selection,
888 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
890 if (sel_listeners != null && sel_listeners.size() > 0)
892 Enumeration listeners = sel_listeners.elements();
893 while (listeners.hasMoreElements())
895 SelectionListener slis = ((SelectionListener) listeners
899 slis.selection(selection, colsel, source);
906 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
908 public synchronized void sendViewPosition(
909 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
910 int startSeq, int endSeq)
913 if (view_listeners != null && view_listeners.size() > 0)
915 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
917 while (listeners.hasMoreElements())
919 AlignmentViewPanelListener slis = listeners.nextElement();
922 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
929 public void finalize() throws Throwable
931 if (listeners != null)
936 if (pdbIdFileName != null)
938 pdbIdFileName.clear();
939 pdbIdFileName = null;
941 if (sel_listeners != null)
943 sel_listeners.clear();
944 sel_listeners = null;
946 if (view_listeners != null)
948 view_listeners.clear();
949 view_listeners = null;
952 seqmappingrefs = null;
956 * release all references associated with this manager provider
960 public static void release(StructureSelectionManagerProvider jalviewLite)
962 // synchronized (instances)
964 if (instances == null)
968 StructureSelectionManager mnger = (instances.get(jalviewLite));
971 instances.remove(jalviewLite);
975 } catch (Throwable x)
983 public void registerPDBEntry(PDBEntry pdbentry)
985 if (pdbentry.getFile() != null
986 && pdbentry.getFile().trim().length() > 0)
988 registerPDBFile(pdbentry.getId(), pdbentry.getFile());