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;
49 private boolean processSecondaryStructure = false,
50 secStructServices = false, addTempFacAnnot = false;
53 * @return true if will try to use external services for processing secondary
56 public boolean isSecStructServices()
58 return secStructServices;
62 * control use of external services for processing secondary structure
64 * @param secStructServices
66 public void setSecStructServices(boolean secStructServices)
68 this.secStructServices = secStructServices;
72 * flag controlling addition of any kind of structural annotation
74 * @return true if temperature factor annotation will be added
76 public boolean isAddTempFacAnnot()
78 return addTempFacAnnot;
82 * set flag controlling addition of structural annotation
84 * @param addTempFacAnnot
86 public void setAddTempFacAnnot(boolean addTempFacAnnot)
88 this.addTempFacAnnot = addTempFacAnnot;
93 * @return if true, the structure manager will attempt to add secondary
94 * structure lines for unannotated sequences
97 public boolean isProcessSecondaryStructure()
99 return processSecondaryStructure;
103 * Control whether structure manager will try to annotate mapped sequences
104 * with secondary structure from PDB data.
108 public void setProcessSecondaryStructure(boolean enable)
110 processSecondaryStructure = enable;
114 * debug function - write all mappings to stdout
116 public void reportMapping()
118 if (mappings == null)
120 System.err.println("reportMapping: No PDB/Sequence mappings.");
124 System.err.println("reportMapping: There are " + mappings.length
126 for (int m = 0; m < mappings.length; m++)
128 System.err.println("mapping " + m + " : " + mappings[m].pdbfile);
134 * map between the PDB IDs (or structure identifiers) used by Jalview and the
135 * absolute filenames for PDB data that corresponds to it
137 HashMap<String, String> pdbIdFileName = new HashMap<String, String>(),
138 pdbFileNameId = new HashMap<String, String>();
140 public void registerPDBFile(String idForFile, String absoluteFile)
142 pdbIdFileName.put(idForFile, absoluteFile);
143 pdbFileNameId.put(absoluteFile, idForFile);
146 public String findIdForPDBFile(String idOrFile)
148 String id = pdbFileNameId.get(idOrFile);
152 public String findFileForPDBId(String idOrFile)
154 String id = pdbIdFileName.get(idOrFile);
158 public boolean isPDBFileRegistered(String idOrFile)
160 return pdbFileNameId.containsKey(idOrFile)
161 || pdbIdFileName.containsKey(idOrFile);
164 private static StructureSelectionManager nullProvider = null;
166 public static StructureSelectionManager getStructureSelectionManager(
167 StructureSelectionManagerProvider context)
171 if (nullProvider == null)
173 if (instances != null)
175 throw new Error(MessageManager.getString("error.implementation_error_structure_selection_manager_null"),
176 new NullPointerException(MessageManager.getString("exception.ssm_context_is_null")));
180 nullProvider = new StructureSelectionManager();
185 if (instances == null)
187 instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
189 StructureSelectionManager instance = instances.get(context);
190 if (instance == null)
192 if (nullProvider != null)
194 instance = nullProvider;
198 instance = new StructureSelectionManager();
200 instances.put(context, instance);
206 * flag controlling whether SeqMappings are relayed from received sequence
207 * mouse over events to other sequences
209 boolean relaySeqMappings = true;
212 * Enable or disable relay of seqMapping events to other sequences. You might
213 * want to do this if there are many sequence mappings and the host computer
218 public void setRelaySeqMappings(boolean relay)
220 relaySeqMappings = relay;
224 * get the state of the relay seqMappings flag.
226 * @return true if sequence mouse overs are being relayed to other mapped
229 public boolean isRelaySeqMappingsEnabled()
231 return relaySeqMappings;
234 Vector listeners = new Vector();
237 * register a listener for alignment sequence mouseover events
241 public void addStructureViewerListener(Object svl)
243 if (!listeners.contains(svl))
245 listeners.addElement(svl);
249 public String alreadyMappedToFile(String pdbid)
251 if (mappings != null)
253 for (int i = 0; i < mappings.length; i++)
255 if (mappings[i].getPdbId().equals(pdbid))
257 return mappings[i].pdbfile;
265 * Import structure data and register a structure mapping for broadcasting
266 * colouring, mouseovers and selection events (convenience wrapper).
269 * - one or more sequences to be mapped to pdbFile
270 * @param targetChains
271 * - optional chain specification for mapping each sequence to pdb
272 * (may be nill, individual elements may be nill)
274 * - structure data resource
276 * - how to resolve data from resource
277 * @return null or the structure data parsed as a pdb file
279 synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
280 String[] targetChains, String pdbFile, String protocol)
282 return setMapping(true, sequence, targetChains, pdbFile, protocol);
286 * create sequence structure mappings between each sequence and the given
287 * pdbFile (retrieved via the given protocol).
289 * @param forStructureView
290 * when true, record the mapping for use in mouseOvers
293 * - one or more sequences to be mapped to pdbFile
294 * @param targetChains
295 * - optional chain specification for mapping each sequence to pdb
296 * (may be nill, individual elements may be nill)
298 * - structure data resource
300 * - how to resolve data from resource
301 * @return null or the structure data parsed as a pdb file
303 synchronized public MCview.PDBfile setMapping(boolean forStructureView,
304 SequenceI[] sequence,
305 String[] targetChains, String pdbFile, String protocol)
308 * There will be better ways of doing this in the future, for now we'll use
309 * the tried and tested MCview pdb mapping
311 MCview.PDBfile pdb = null;
312 boolean parseSecStr = processSecondaryStructure;
313 if (isPDBFileRegistered(pdbFile))
315 for (SequenceI sq : sequence)
318 while (ds.getDatasetSequence() != null)
320 ds = ds.getDatasetSequence();
323 if (ds.getAnnotation() != null)
325 for (AlignmentAnnotation ala : ds.getAnnotation())
327 // false if any annotation present from this structure
328 // JBPNote this fails for jmol/chimera view because the *file* is
329 // passed, not the structure data ID -
330 if (MCview.PDBfile.isCalcIdForFile(ala,
331 findIdForPDBFile(pdbFile)))
341 pdb = new MCview.PDBfile(addTempFacAnnot, parseSecStr,
342 secStructServices, pdbFile, protocol);
343 if (pdb.id != null && pdb.id.trim().length() > 0
344 && AppletFormatAdapter.FILE.equals(protocol))
346 registerPDBFile(pdb.id.trim(), pdbFile);
348 } catch (Exception ex)
350 ex.printStackTrace();
355 for (int s = 0; s < sequence.length; s++)
357 boolean infChain = true;
358 if (targetChains != null && targetChains[s] != null)
361 targetChain = targetChains[s];
363 else if (sequence[s].getName().indexOf("|") > -1)
365 targetChain = sequence[s].getName().substring(
366 sequence[s].getName().lastIndexOf("|") + 1);
367 if (targetChain.length() > 1)
369 if (targetChain.trim().length() == 0)
375 // not a valid chain identifier
386 AlignSeq maxAlignseq = null;
387 String maxChainId = " ";
388 PDBChain maxChain = null;
389 boolean first = true;
390 for (int i = 0; i < pdb.chains.size(); i++)
392 PDBChain chain = (pdb.chains.elementAt(i));
393 if (targetChain.length() > 0 && !targetChain.equals(chain.id)
396 continue; // don't try to map chains don't match.
398 // TODO: correctly determine sequence type for mixed na/peptide
400 AlignSeq as = new AlignSeq(sequence[s],
401 pdb.chains.elementAt(i).sequence,
402 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
404 as.calcScoreMatrix();
407 if (first || as.maxscore > max
408 || (as.maxscore == max && chain.id.equals(targetChain)))
414 maxChainId = chain.id;
417 if (maxChain == null)
421 final StringBuffer mappingDetails = new StringBuffer();
422 mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
423 + maxChain.sequence.getSequenceAsString());
424 mappingDetails.append("\nNo of residues = "
425 + maxChain.residues.size() + "\n\n");
426 PrintStream ps = new PrintStream(System.out)
429 public void print(String x)
431 mappingDetails.append(x);
435 public void println()
437 mappingDetails.append("\n");
441 maxAlignseq.printAlignment(ps);
443 mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
444 + " " + maxAlignseq.seq2end);
445 mappingDetails.append("\nSEQ start/end "
446 + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
447 + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
449 maxChain.makeExactMapping(maxAlignseq, sequence[s]);
450 jalview.datamodel.Mapping sqmpping = maxAlignseq
451 .getMappingFromS1(false);
452 jalview.datamodel.Mapping omap = new jalview.datamodel.Mapping(
453 sqmpping.getMap().getInverse());
454 maxChain.transferRESNUMFeatures(sequence[s], null);
456 // allocate enough slots to store the mapping from positions in
457 // sequence[s] to the associated chain
458 int[][] mapping = new int[sequence[s].findPosition(sequence[s]
459 .getLength()) + 2][2];
465 Atom tmp = (Atom) maxChain.atoms.elementAt(index);
466 if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
468 resNum = tmp.resNumber;
469 mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
470 mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
474 } while (index < maxChain.atoms.size());
476 if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
478 pdbFile = "INLINE" + pdb.id;
480 StructureMapping newMapping = new StructureMapping(sequence[s],
481 pdbFile, pdb.id, maxChainId, mapping,
482 mappingDetails.toString());
483 if (forStructureView)
486 if (mappings == null)
488 mappings = new StructureMapping[1];
492 StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
493 System.arraycopy(mappings, 0, tmp, 0, mappings.length);
497 mappings[mappings.length - 1] = newMapping;
499 maxChain.transferResidueAnnotation(newMapping, sqmpping);
506 public void removeStructureViewerListener(Object svl, String[] pdbfiles)
508 listeners.removeElement(svl);
509 if (svl instanceof SequenceListener)
511 for (int i = 0; i < listeners.size(); i++)
513 if (listeners.elementAt(i) instanceof StructureListener)
515 ((StructureListener) listeners.elementAt(i))
516 .releaseReferences(svl);
521 if (pdbfiles == null)
526 Vector pdbs = new Vector();
527 for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
531 StructureListener sl;
532 for (int i = 0; i < listeners.size(); i++)
534 if (listeners.elementAt(i) instanceof StructureListener)
536 sl = (StructureListener) listeners.elementAt(i);
537 handlepdbs = sl.getPdbFile();
538 for (int j = 0; j < handlepdbs.length; j++)
540 if (pdbs.contains(handlepdbs[j]))
542 pdbs.removeElement(handlepdbs[j]);
549 if (pdbs.size() > 0 && mappings != null)
551 Vector tmp = new Vector();
552 for (int i = 0; i < mappings.length; i++)
554 if (!pdbs.contains(mappings[i].pdbfile))
556 tmp.addElement(mappings[i]);
560 mappings = new StructureMapping[tmp.size()];
561 tmp.copyInto(mappings);
565 public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
567 if (listeners == null)
569 // old or prematurely sent event
572 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
573 SearchResults results = null;
574 SequenceI lastseq = null;
575 int lastipos = -1, indexpos;
576 for (int i = 0; i < listeners.size(); i++)
578 if (listeners.elementAt(i) instanceof SequenceListener)
582 results = new SearchResults();
584 if (mappings != null)
586 for (int j = 0; j < mappings.length; j++)
588 if (mappings[j].pdbfile.equals(pdbfile)
589 && mappings[j].pdbchain.equals(chain))
591 indexpos = mappings[j].getSeqPos(pdbResNum);
592 if (lastipos != indexpos && lastseq != mappings[j].sequence)
594 results.addResult(mappings[j].sequence, indexpos, indexpos);
596 lastseq = mappings[j].sequence;
597 // construct highlighted sequence list
598 if (seqmappings != null)
601 Enumeration e = seqmappings.elements();
602 while (e.hasMoreElements())
605 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
606 mappings[j].sequence, indexpos, results);
618 for (int i = 0; i < listeners.size(); i++)
620 Object li = listeners.elementAt(i);
621 if (li instanceof SequenceListener)
623 ((SequenceListener) li).highlightSequence(results);
629 Vector seqmappings = null; // should be a simpler list of mapped seuqence
632 * highlight regions associated with a position (indexpos) in seq
635 * the sequeence that the mouse over occured on
637 * the absolute position being mouseovered in seq (0 to seq.length())
639 * the sequence position (if -1, seq.findPosition is called to
640 * resolve the residue number)
642 public void mouseOverSequence(SequenceI seq, int indexpos, int index,
645 boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
646 SearchResults results = null;
649 index = seq.findPosition(indexpos);
651 StructureListener sl;
653 for (int i = 0; i < listeners.size(); i++)
655 Object listener = listeners.elementAt(i);
656 if (listener == source)
660 if (listener instanceof StructureListener)
662 sl = (StructureListener) listener;
663 if (mappings == null)
667 for (int j = 0; j < mappings.length; j++)
669 if (mappings[j].sequence == seq
670 || mappings[j].sequence == seq.getDatasetSequence())
672 atomNo = mappings[j].getAtomNum(index);
676 sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
677 mappings[j].pdbchain, mappings[j].pdbfile);
684 if (relaySeqMappings && hasSequenceListeners
685 && listener instanceof SequenceListener)
688 // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
693 results = new SearchResults();
694 if (index >= seq.getStart() && index <= seq.getEnd())
696 // construct highlighted sequence list
698 if (seqmappings != null)
700 Enumeration e = seqmappings.elements();
701 while (e.hasMoreElements())
704 ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
705 seq, index, results);
708 // hasSequenceListeners = results.getSize() > 0;
709 if (handlingVamsasMo)
711 // maybe have to resolve seq to a dataset seqeunce...
712 // add in additional direct sequence and/or dataset sequence
714 results.addResult(seq, index, index);
718 if (hasSequenceListeners)
720 ((SequenceListener) listener).highlightSequence(results);
723 else if (listener instanceof VamsasListener && !handlingVamsasMo)
726 // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
729 // pass the mouse over and absolute position onto the
731 ((VamsasListener) listener).mouseOver(seq, indexpos, source);
733 else if (listener instanceof SecondaryStructureListener)
735 ((SecondaryStructureListener) listener).mouseOverSequence(seq,
743 * true if a mouse over event from an external (ie Vamsas) source is being
746 boolean handlingVamsasMo = false;
751 * as mouseOverSequence but only route event to SequenceListeners
755 * in an alignment sequence
757 public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
760 handlingVamsasMo = true;
761 long msg = sequenceI.hashCode() * (1 + position);
765 mouseOverSequence(sequenceI, position, -1, source);
767 handlingVamsasMo = false;
770 public Annotation[] colourSequenceFromStructure(SequenceI seq,
774 // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
775 // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
777 * Annotation [] annotations = new Annotation[seq.getLength()];
779 * StructureListener sl; int atomNo = 0; for (int i = 0; i <
780 * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
781 * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
783 * for (int j = 0; j < mappings.length; j++) {
785 * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
786 * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
787 * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
788 * "+mappings[j].pdbfile);
790 * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
791 * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
793 * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
794 * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
795 * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
796 * mappings[j].pdbfile); }
798 * annotations[index] = new Annotation("X",null,' ',0,col); } return
799 * annotations; } } } }
801 * return annotations;
805 public void structureSelectionChanged()
809 public void sequenceSelectionChanged()
813 public void sequenceColoursChanged(Object source)
815 StructureListener sl;
816 for (int i = 0; i < listeners.size(); i++)
818 if (listeners.elementAt(i) instanceof StructureListener)
820 sl = (StructureListener) listeners.elementAt(i);
821 sl.updateColours(source);
826 public StructureMapping[] getMapping(String pdbfile)
828 Vector tmp = new Vector();
829 if (mappings != null)
831 for (int i = 0; i < mappings.length; i++)
833 if (mappings[i].pdbfile.equals(pdbfile))
835 tmp.addElement(mappings[i]);
839 StructureMapping[] ret = new StructureMapping[tmp.size()];
840 for (int i = 0; i < tmp.size(); i++)
842 ret[i] = (StructureMapping) tmp.elementAt(i);
848 public String printMapping(String pdbfile)
850 StringBuffer sb = new StringBuffer();
851 for (int i = 0; i < mappings.length; i++)
853 if (mappings[i].pdbfile.equals(pdbfile))
855 sb.append(mappings[i].mappingDetails);
859 return sb.toString();
862 private int[] seqmappingrefs = null; // refcount for seqmappings elements
864 private synchronized void modifySeqMappingList(boolean add,
865 AlignedCodonFrame[] codonFrames)
867 if (!add && (seqmappings == null || seqmappings.size() == 0))
871 if (seqmappings == null)
873 seqmappings = new Vector();
875 if (codonFrames != null && codonFrames.length > 0)
877 for (int cf = 0; cf < codonFrames.length; cf++)
879 if (seqmappings.contains(codonFrames[cf]))
883 seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
887 if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
889 int pos = seqmappings.indexOf(codonFrames[cf]);
890 int[] nr = new int[seqmappingrefs.length - 1];
893 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
895 if (pos < seqmappingrefs.length - 1)
897 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
898 seqmappingrefs.length - pos - 2);
907 seqmappings.addElement(codonFrames[cf]);
909 int[] nsr = new int[(seqmappingrefs == null) ? 1
910 : seqmappingrefs.length + 1];
911 if (seqmappingrefs != null && seqmappingrefs.length > 0)
913 System.arraycopy(seqmappingrefs, 0, nsr, 0,
914 seqmappingrefs.length);
916 nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
917 seqmappingrefs = nsr;
924 public void removeMappings(AlignedCodonFrame[] codonFrames)
926 modifySeqMappingList(false, codonFrames);
929 public void addMappings(AlignedCodonFrame[] codonFrames)
931 modifySeqMappingList(true, codonFrames);
934 Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
936 public void addSelectionListener(SelectionListener selecter)
938 if (!sel_listeners.contains(selecter))
940 sel_listeners.addElement(selecter);
944 public void removeSelectionListener(SelectionListener toremove)
946 if (sel_listeners.contains(toremove))
948 sel_listeners.removeElement(toremove);
952 public synchronized void sendSelection(
953 jalview.datamodel.SequenceGroup selection,
954 jalview.datamodel.ColumnSelection colsel, SelectionSource source)
956 if (sel_listeners != null && sel_listeners.size() > 0)
958 Enumeration listeners = sel_listeners.elements();
959 while (listeners.hasMoreElements())
961 SelectionListener slis = ((SelectionListener) listeners
965 slis.selection(selection, colsel, source);
972 Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
974 public synchronized void sendViewPosition(
975 jalview.api.AlignmentViewPanel source, int startRes, int endRes,
976 int startSeq, int endSeq)
979 if (view_listeners != null && view_listeners.size() > 0)
981 Enumeration<AlignmentViewPanelListener> listeners = view_listeners
983 while (listeners.hasMoreElements())
985 AlignmentViewPanelListener slis = listeners.nextElement();
988 slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
995 public void finalize() throws Throwable
997 if (listeners != null)
1002 if (pdbIdFileName != null)
1004 pdbIdFileName.clear();
1005 pdbIdFileName = null;
1007 if (sel_listeners != null)
1009 sel_listeners.clear();
1010 sel_listeners = null;
1012 if (view_listeners != null)
1014 view_listeners.clear();
1015 view_listeners = null;
1018 seqmappingrefs = null;
1022 * release all references associated with this manager provider
1024 * @param jalviewLite
1026 public static void release(StructureSelectionManagerProvider jalviewLite)
1028 // synchronized (instances)
1030 if (instances == null)
1034 StructureSelectionManager mnger = (instances.get(jalviewLite));
1037 instances.remove(jalviewLite);
1041 } catch (Throwable x)
1049 public void registerPDBEntry(PDBEntry pdbentry)
1051 if (pdbentry.getFile() != null
1052 && pdbentry.getFile().trim().length() > 0)
1054 registerPDBFile(pdbentry.getId(), pdbentry.getFile());