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 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 && FormatAdapter.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)
364 public void print(String x)
366 mappingDetails.append(x);
370 public void println()
372 mappingDetails.append("\n");
376 maxAlignseq.printAlignment(ps);
378 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
379 + " " + maxAlignseq.seq2end);
380 mappingDetails.append("\nSEQ start/end "
381 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
382 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
384 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
385 jalview.datamodel.Mapping sqmpping = maxAlignseq
386 .getMappingFromS1(false);
387 jalview.datamodel.Mapping omap = new jalview.datamodel.Mapping(
388 sqmpping.getMap().getInverse());
389 maxChain.transferRESNUMFeatures(sequence[s], null);
391 // allocate enough slots to store the mapping from positions in
392 // sequence[s] to the associated chain
393 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
394 .getLength()) + 2][2];
400 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
401 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
403 resNum = tmp.resNumber;
404 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
405 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
409 } while (index < maxChain.atoms.size());
411 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
413 pdbFile = "INLINE" + pdb.id;
415 StructureMapping newMapping = new StructureMapping(sequence[s],
416 pdbFile, pdb.id, maxChainId, mapping,
417 mappingDetails.toString());
418 if (forStructureView)
421 if (mappings == null)
423 mappings = new StructureMapping[1];
427 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
428 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
432 mappings[mappings.length - 1] = newMapping;
434 maxChain.transferResidueAnnotation(newMapping, sqmpping);
441 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
443 listeners.removeElement(svl);
444 if (svl instanceof SequenceListener)
446 for (int i = 0; i < listeners.size(); i++)
448 if (listeners.elementAt(i) instanceof StructureListener)
450 ((StructureListener) listeners.elementAt(i))
451 .releaseReferences(svl);
456 if (pdbfiles == null)
460 boolean removeMapping = true;
462 Vector pdbs = new Vector();
463 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
467 StructureListener sl;
468 for (int i = 0; i < listeners.size(); i++)
470 if (listeners.elementAt(i) instanceof StructureListener)
472 sl = (StructureListener) listeners.elementAt(i);
473 handlepdbs = sl.getPdbFile();
474 for (int j = 0; j < handlepdbs.length; j++)
476 if (pdbs.contains(handlepdbs[j]))
478 pdbs.removeElement(handlepdbs[j]);
485 if (pdbs.size() > 0 && mappings != null)
487 Vector tmp = new Vector();
488 for (int i = 0; i < mappings.length; i++)
490 if (!pdbs.contains(mappings[i].pdbfile))
492 tmp.addElement(mappings[i]);
496 mappings = new StructureMapping[tmp.size()];
497 tmp.copyInto(mappings);
501 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
503 if (listeners == null)
505 // old or prematurely sent event
508 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
509 SearchResults results = null;
510 SequenceI lastseq = null;
511 int lastipos = -1, indexpos;
512 for (int i = 0; i < listeners.size(); i++)
514 if (listeners.elementAt(i) instanceof SequenceListener)
518 results = new SearchResults();
520 if (mappings != null)
522 for (int j = 0; j < mappings.length; j++)
524 if (mappings[j].pdbfile.equals(pdbfile)
525 && mappings[j].pdbchain.equals(chain))
527 indexpos = mappings[j].getSeqPos(pdbResNum);
528 if (lastipos != indexpos && lastseq != mappings[j].sequence)
530 results.addResult(mappings[j].sequence, indexpos, indexpos);
532 lastseq = mappings[j].sequence;
533 // construct highlighted sequence list
534 if (seqmappings != null)
537 Enumeration e = seqmappings.elements();
538 while (e.hasMoreElements())
541 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
542 mappings[j].sequence, indexpos, results);
554 for (int i = 0; i < listeners.size(); i++)
556 Object li = listeners.elementAt(i);
557 if (li instanceof SequenceListener)
559 ((SequenceListener) li).highlightSequence(results);
565 Vector seqmappings = null; // should be a simpler list of mapped seuqence
568 * highlight regions associated with a position (indexpos) in seq
571 * the sequeence that the mouse over occured on
573 * the absolute position being mouseovered in seq (0 to seq.length())
575 * the sequence position (if -1, seq.findPosition is called to
576 * resolve the residue number)
578 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
581 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
582 SearchResults results = null;
585 index = seq.findPosition(indexpos);
587 StructureListener sl;
589 for (int i = 0; i < listeners.size(); i++)
591 Object listener = listeners.elementAt(i);
592 if (listener == source)
596 if (listener instanceof StructureListener)
598 sl = (StructureListener) listener;
599 if (mappings == null)
603 for (int j = 0; j < mappings.length; j++)
605 if (mappings[j].sequence == seq
606 || mappings[j].sequence == seq.getDatasetSequence())
608 atomNo = mappings[j].getAtomNum(index);
612 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
613 mappings[j].pdbchain, mappings[j].pdbfile);
620 if (relaySeqMappings && hasSequenceListeners
621 && listener instanceof SequenceListener)
624 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
629 results = new SearchResults();
630 if (index >= seq.getStart() && index <= seq.getEnd())
632 // construct highlighted sequence list
634 if (seqmappings != null)
636 Enumeration e = seqmappings.elements();
637 while (e.hasMoreElements())
640 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
641 seq, index, results);
644 // hasSequenceListeners = results.getSize() > 0;
645 if (handlingVamsasMo)
647 // maybe have to resolve seq to a dataset seqeunce...
648 // add in additional direct sequence and/or dataset sequence
650 results.addResult(seq, index, index);
654 if (hasSequenceListeners)
656 ((SequenceListener) listener).highlightSequence(results);
659 else if (listener instanceof VamsasListener && !handlingVamsasMo)
662 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
665 // pass the mouse over and absolute position onto the
667 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
669 else if (listener instanceof SecondaryStructureListener)
671 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
679 * true if a mouse over event from an external (ie Vamsas) source is being
682 boolean handlingVamsasMo = false;
687 * as mouseOverSequence but only route event to SequenceListeners
691 * in an alignment sequence
693 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
696 handlingVamsasMo = true;
697 long msg = sequenceI.hashCode() * (1 + position);
701 mouseOverSequence(sequenceI, position, -1, source);
703 handlingVamsasMo = false;
706 public Annotation[] colourSequenceFromStructure(SequenceI seq,
710 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
711 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
713 * Annotation [] annotations = new Annotation[seq.getLength()];
715 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
716 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
717 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
719 * for (int j = 0; j < mappings.length; j++) {
721 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
722 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
723 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
724 * "+mappings[j].pdbfile);
726 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
727 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
729 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
730 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
731 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
732 * mappings[j].pdbfile); }
734 * annotations[index] = new Annotation("X",null,' ',0,col); } return
735 * annotations; } } } }
737 * return annotations;
741 public void structureSelectionChanged()
745 public void sequenceSelectionChanged()
749 public void sequenceColoursChanged(Object source)
751 StructureListener sl;
752 for (int i = 0; i < listeners.size(); i++)
754 if (listeners.elementAt(i) instanceof StructureListener)
756 sl = (StructureListener) listeners.elementAt(i);
757 sl.updateColours(source);
762 public StructureMapping[] getMapping(String pdbfile)
764 Vector tmp = new Vector();
765 if (mappings != null)
767 for (int i = 0; i < mappings.length; i++)
769 if (mappings[i].pdbfile.equals(pdbfile))
771 tmp.addElement(mappings[i]);
775 StructureMapping[] ret = new StructureMapping[tmp.size()];
776 for (int i = 0; i < tmp.size(); i++)
778 ret[i] = (StructureMapping) tmp.elementAt(i);
784 public String printMapping(String pdbfile)
786 StringBuffer sb = new StringBuffer();
787 for (int i = 0; i < mappings.length; i++)
789 if (mappings[i].pdbfile.equals(pdbfile))
791 sb.append(mappings[i].mappingDetails);
795 return sb.toString();
798 private int[] seqmappingrefs = null; // refcount for seqmappings elements
800 private synchronized void modifySeqMappingList(boolean add,
801 AlignedCodonFrame[] codonFrames)
803 if (!add && (seqmappings == null || seqmappings.size() == 0))
807 if (seqmappings == null)
809 seqmappings = new Vector();
811 if (codonFrames != null && codonFrames.length > 0)
813 for (int cf = 0; cf < codonFrames.length; cf++)
815 if (seqmappings.contains(codonFrames[cf]))
819 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
823 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
825 int pos = seqmappings.indexOf(codonFrames[cf]);
826 int[] nr = new int[seqmappingrefs.length - 1];
829 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
831 if (pos < seqmappingrefs.length - 1)
833 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
834 seqmappingrefs.length - pos - 2);
843 seqmappings.addElement(codonFrames[cf]);
845 int[] nsr = new int[(seqmappingrefs == null) ? 1
846 : seqmappingrefs.length + 1];
847 if (seqmappingrefs != null && seqmappingrefs.length > 0)
849 System.arraycopy(seqmappingrefs, 0, nsr, 0,
850 seqmappingrefs.length);
852 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
853 seqmappingrefs = nsr;
860 public void removeMappings(AlignedCodonFrame[] codonFrames)
862 modifySeqMappingList(false, codonFrames);
865 public void addMappings(AlignedCodonFrame[] codonFrames)
867 modifySeqMappingList(true, codonFrames);
870 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
872 public void addSelectionListener(SelectionListener selecter)
874 if (!sel_listeners.contains(selecter))
876 sel_listeners.addElement(selecter);
880 public void removeSelectionListener(SelectionListener toremove)
882 if (sel_listeners.contains(toremove))
884 sel_listeners.removeElement(toremove);
888 public synchronized void sendSelection(
889 jalview.datamodel.SequenceGroup selection,
890 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
892 if (sel_listeners != null && sel_listeners.size() > 0)
894 Enumeration listeners = sel_listeners.elements();
895 while (listeners.hasMoreElements())
897 SelectionListener slis = ((SelectionListener) listeners
901 slis.selection(selection, colsel, source);
908 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
910 public synchronized void sendViewPosition(
911 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
912 int startSeq, int endSeq)
915 if (view_listeners != null && view_listeners.size() > 0)
917 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
919 while (listeners.hasMoreElements())
921 AlignmentViewPanelListener slis = listeners.nextElement();
924 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
931 public void finalize() throws Throwable
933 if (listeners != null)
938 if (pdbIdFileName != null)
940 pdbIdFileName.clear();
941 pdbIdFileName = null;
943 if (sel_listeners != null)
945 sel_listeners.clear();
946 sel_listeners = null;
948 if (view_listeners != null)
950 view_listeners.clear();
951 view_listeners = null;
954 seqmappingrefs = null;
958 * release all references associated with this manager provider
962 public static void release(StructureSelectionManagerProvider jalviewLite)
964 // synchronized (instances)
966 if (instances == null)
970 StructureSelectionManager mnger = (instances.get(jalviewLite));
973 instances.remove(jalviewLite);
977 } catch (Throwable x)
985 public void registerPDBEntry(PDBEntry pdbentry)
987 if (pdbentry.getFile() != null
988 && pdbentry.getFile().trim().length() > 0)
990 registerPDBFile(pdbentry.getId(), pdbentry.getFile());