avoid creating lots of identical search results. patch for JAL-751
[jalview.git] / src / jalview / structure / StructureSelectionManager.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.structure;
19
20 import java.io.*;
21 import java.util.*;
22
23 import MCview.*;
24 import jalview.analysis.*;
25 import jalview.datamodel.*;
26
27 public class StructureSelectionManager
28 {
29   static StructureSelectionManager instance;
30
31   StructureMapping[] mappings;
32
33   Hashtable mappingData = new Hashtable();
34
35   public static StructureSelectionManager getStructureSelectionManager()
36   {
37     if (instance == null)
38     {
39       instance = new StructureSelectionManager();
40     }
41
42     return instance;
43   }
44
45   /**
46    * flag controlling whether SeqMappings are relayed from received sequence
47    * mouse over events to other sequences
48    */
49   boolean relaySeqMappings = true;
50
51   /**
52    * Enable or disable relay of seqMapping events to other sequences. You might
53    * want to do this if there are many sequence mappings and the host computer
54    * is slow
55    * 
56    * @param relay
57    */
58   public void setRelaySeqMappings(boolean relay)
59   {
60     relaySeqMappings = relay;
61   }
62
63   /**
64    * get the state of the relay seqMappings flag.
65    * 
66    * @return true if sequence mouse overs are being relayed to other mapped
67    *         sequences
68    */
69   public boolean isRelaySeqMappingsEnabled()
70   {
71     return relaySeqMappings;
72   }
73
74   Vector listeners = new Vector();
75
76   /**
77    * register a listener for alignment sequence mouseover events
78    * @param svl
79    */
80   public void addStructureViewerListener(Object svl)
81   {
82     if (!listeners.contains(svl))
83     {
84       listeners.addElement(svl);
85     }
86   }
87
88   public String alreadyMappedToFile(String pdbid)
89   {
90     if (mappings != null)
91     {
92       for (int i = 0; i < mappings.length; i++)
93       {
94         if (mappings[i].getPdbId().equals(pdbid))
95         {
96           return mappings[i].pdbfile;
97         }
98       }
99     }
100     return null;
101   }
102
103   /**
104    * create sequence structure mappings between each sequence and the given
105    * pdbFile (retrieved via the given protocol).
106    * 
107    * @param sequence
108    *          - one or more sequences to be mapped to pdbFile
109    * @param targetChains
110    *          - optional chain specification for mapping each sequence to pdb
111    *          (may be nill, individual elements may be nill)
112    * @param pdbFile
113    *          - structure data resource
114    * @param protocol
115    *          - how to resolve data from resource
116    * @return null or the structure data parsed as a pdb file
117    */
118   synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
119           String[] targetChains, String pdbFile, String protocol)
120   {
121     /*
122      * There will be better ways of doing this in the future, for now we'll use
123      * the tried and tested MCview pdb mapping
124      */
125     MCview.PDBfile pdb = null;
126     try
127     {
128       pdb = new MCview.PDBfile(pdbFile, protocol);
129     } catch (Exception ex)
130     {
131       ex.printStackTrace();
132       return null;
133     }
134
135     String targetChain;
136     for (int s = 0; s < sequence.length; s++)
137     {
138       if (targetChains != null && targetChains[s] != null)
139         targetChain = targetChains[s];
140       else if (sequence[s].getName().indexOf("|") > -1)
141       {
142         targetChain = sequence[s].getName().substring(
143                 sequence[s].getName().lastIndexOf("|") + 1);
144       }
145       else
146         targetChain = "";
147
148       int max = -10;
149       AlignSeq maxAlignseq = null;
150       String maxChainId = " ";
151       PDBChain maxChain = null;
152       boolean first = true;
153       for (int i = 0; i < pdb.chains.size(); i++)
154       {
155         // TODO: re http://issues.jalview.org/browse/JAL-583 : this patch may
156         // need to be revoked
157         PDBChain chain = ((PDBChain) pdb.chains.elementAt(i));
158         if (targetChain.length() > 0 && !targetChain.equals(chain.id))
159         {
160           continue; // don't try to map chains don't match.
161         }
162         // end of patch for limiting computed mappings
163         // TODO: correctly determine sequence type for mixed na/peptide
164         // structures
165         AlignSeq as = new AlignSeq(sequence[s],
166                 ((PDBChain) pdb.chains.elementAt(i)).sequence,
167                 ((PDBChain) pdb.chains.elementAt(i)).isNa ? AlignSeq.DNA
168                         : AlignSeq.PEP);
169         as.calcScoreMatrix();
170         as.traceAlignment();
171
172         if (first || as.maxscore > max
173                 || (as.maxscore == max && chain.id.equals(targetChain)))
174         {
175           first = false;
176           maxChain = chain;
177           max = as.maxscore;
178           maxAlignseq = as;
179           maxChainId = chain.id;
180         }
181       }
182       if (maxChain == null)
183       {
184         continue;
185       }
186       final StringBuffer mappingDetails = new StringBuffer();
187       mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
188               + maxChain.sequence.getSequenceAsString());
189       mappingDetails.append("\nNo of residues = "
190               + maxChain.residues.size() + "\n\n");
191       PrintStream ps = new PrintStream(System.out)
192       {
193         public void print(String x)
194         {
195           mappingDetails.append(x);
196         }
197
198         public void println()
199         {
200           mappingDetails.append("\n");
201         }
202       };
203
204       maxAlignseq.printAlignment(ps);
205
206       mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
207               + " " + maxAlignseq.seq2end);
208       mappingDetails.append("\nSEQ start/end "
209               + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
210               + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
211
212       maxChain.makeExactMapping(maxAlignseq, sequence[s]);
213
214       maxChain.transferRESNUMFeatures(sequence[s], null);
215
216       // allocate enough slots to store the mapping from positions in
217       // sequence[s] to the associated chain
218       int[][] mapping = new int[maxChain.sequence.getEnd() + 2][2];
219       int resNum = -10000;
220       int index = 0;
221
222       do
223       {
224         Atom tmp = (Atom) maxChain.atoms.elementAt(index);
225         if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
226         {
227           resNum = tmp.resNumber;
228           mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
229           mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
230         }
231
232         index++;
233       } while (index < maxChain.atoms.size());
234
235       if (mappings == null)
236       {
237         mappings = new StructureMapping[1];
238       }
239       else
240       {
241         StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
242         System.arraycopy(mappings, 0, tmp, 0, mappings.length);
243         mappings = tmp;
244       }
245
246       if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
247         pdbFile = "INLINE" + pdb.id;
248
249       mappings[mappings.length - 1] = new StructureMapping(sequence[s],
250               pdbFile, pdb.id, maxChainId, mapping,
251               mappingDetails.toString());
252       maxChain.transferResidueAnnotation(mappings[mappings.length - 1]);
253     }
254     // ///////
255
256     return pdb;
257   }
258
259   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
260   {
261     listeners.removeElement(svl);
262     if (pdbfiles == null)
263     {
264       return;
265     }
266     boolean removeMapping = true;
267     String[] handlepdbs;
268     Vector pdbs = new Vector();
269     for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
270       ;
271     StructureListener sl;
272     for (int i = 0; i < listeners.size(); i++)
273     {
274       if (listeners.elementAt(i) instanceof StructureListener)
275       {
276         sl = (StructureListener) listeners.elementAt(i);
277         handlepdbs = sl.getPdbFile();
278         for (int j = 0; j < handlepdbs.length; j++)
279         {
280           if (pdbs.contains(handlepdbs[j]))
281           {
282             pdbs.removeElement(handlepdbs[j]);
283           }
284         }
285
286       }
287     }
288
289     if (pdbs.size() > 0 && mappings != null)
290     {
291       Vector tmp = new Vector();
292       for (int i = 0; i < mappings.length; i++)
293       {
294         if (!pdbs.contains(mappings[i].pdbfile))
295         {
296           tmp.addElement(mappings[i]);
297         }
298       }
299
300       mappings = new StructureMapping[tmp.size()];
301       tmp.copyInto(mappings);
302     }
303   }
304
305   public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
306   {
307     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
308     SearchResults results = null;
309     SequenceI lastseq = null;
310     int lastipos = -1, indexpos;
311     for (int i = 0; i < listeners.size(); i++)
312     {
313       if (listeners.elementAt(i) instanceof SequenceListener)
314       {
315         if (results == null)
316         {
317           results = new SearchResults();
318         }
319         if (mappings != null)
320         {
321           for (int j = 0; j < mappings.length; j++)
322           {
323             if (mappings[j].pdbfile.equals(pdbfile)
324                     && mappings[j].pdbchain.equals(chain))
325             {
326               indexpos = mappings[j].getSeqPos(pdbResNum);
327               if (lastipos != indexpos && lastseq != mappings[j].sequence)
328               {
329                 results.addResult(mappings[j].sequence, indexpos, indexpos);
330                 lastipos = indexpos;
331                 lastseq = mappings[j].sequence;
332                 // construct highlighted sequence list
333                 if (seqmappings != null)
334                 {
335
336                   Enumeration e = seqmappings.elements();
337                   while (e.hasMoreElements())
338
339                   {
340                     ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
341                             mappings[j].sequence, indexpos, results);
342                   }
343                 }
344               }
345
346             }
347           }
348         }
349       }
350     }
351     if (results.getSize() > 0)
352     {
353       for (int i = 0; i < listeners.size(); i++)
354       {
355         Object li = listeners.elementAt(i);
356         if (li instanceof SequenceListener)
357           ((SequenceListener) li).highlightSequence(results);
358       }
359     }
360   }
361
362   Vector seqmappings = null; // should be a simpler list of mapped seuqence
363
364   /**
365    * highlight regions associated with a position (indexpos) in seq
366    * 
367    * @param seq
368    *          the sequeence that the mouse over occured on
369    * @param indexpos
370    *          the absolute position being mouseovered in seq (0 to seq.length())
371    * @param index
372    *          the sequence position (if -1, seq.findPosition is called to
373    *          resolve the residue number)
374    */
375   public void mouseOverSequence(SequenceI seq, int indexpos, int index,
376           VamsasSource source)
377   {
378     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
379     SearchResults results = null;
380     if (index == -1)
381       index = seq.findPosition(indexpos);
382     StructureListener sl;
383     int atomNo = 0;
384     for (int i = 0; i < listeners.size(); i++)
385     {
386       if (listeners.elementAt(i) instanceof StructureListener)
387       {
388         sl = (StructureListener) listeners.elementAt(i);
389         if (mappings == null)
390         {
391           continue;
392         }
393         for (int j = 0; j < mappings.length; j++)
394         {
395           if (mappings[j].sequence == seq
396                   || mappings[j].sequence == seq.getDatasetSequence())
397           {
398             atomNo = mappings[j].getAtomNum(index);
399
400             if (atomNo > 0)
401             {
402               sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
403                       mappings[j].pdbchain, mappings[j].pdbfile);
404             }
405           }
406         }
407       }
408       else
409       {
410         if (relaySeqMappings && hasSequenceListeners
411                 && listeners.elementAt(i) instanceof SequenceListener)
412         {
413           // DEBUG
414           // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
415           // index);
416
417           if (results == null)
418           {
419             results = new SearchResults();
420             if (index >= seq.getStart() && index <= seq.getEnd())
421             {
422               // construct highlighted sequence list
423
424               if (seqmappings != null)
425               {
426                 Enumeration e = seqmappings.elements();
427                 while (e.hasMoreElements())
428
429                 {
430                   ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
431                           seq, index, results);
432                 }
433               }
434               // hasSequenceListeners = results.getSize() > 0;
435               if (handlingVamsasMo)
436               {
437                 // maybe have to resolve seq to a dataset seqeunce...
438                 // add in additional direct sequence and/or dataset sequence
439                 // highlighting
440                 results.addResult(seq, index, index);
441               }
442             }
443           }
444           if (hasSequenceListeners)
445           {
446             ((SequenceListener) listeners.elementAt(i))
447                     .highlightSequence(results);
448           }
449         }
450         else if (listeners.elementAt(i) instanceof VamsasListener
451                 && !handlingVamsasMo)
452         {
453           // DEBUG
454           // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
455           // " +
456           // index);
457           // pass the mouse over and absolute position onto the
458           // VamsasListener(s)
459           ((VamsasListener) listeners.elementAt(i)).mouseOver(seq,
460                   indexpos, source);
461         }
462       }
463     }
464   }
465
466   /**
467    * true if a mouse over event from an external (ie Vamsas) source is being
468    * handled
469    */
470   boolean handlingVamsasMo = false;
471
472   long lastmsg = 0;
473
474   /**
475    * as mouseOverSequence but only route event to SequenceListeners
476    * 
477    * @param sequenceI
478    * @param position
479    *          in an alignment sequence
480    */
481   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
482           VamsasSource source)
483   {
484     handlingVamsasMo = true;
485     long msg = sequenceI.hashCode() * (1 + position);
486     if (lastmsg != msg)
487     {
488       lastmsg = msg;
489       mouseOverSequence(sequenceI, position, -1, source);
490     }
491     handlingVamsasMo = false;
492   }
493
494   public Annotation[] colourSequenceFromStructure(SequenceI seq,
495           String pdbid)
496   {
497     return null;
498     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
499     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
500     /*
501      * Annotation [] annotations = new Annotation[seq.getLength()];
502      * 
503      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
504      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
505      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
506      * 
507      * for (int j = 0; j < mappings.length; j++) {
508      * 
509      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
510      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
511      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
512      * "+mappings[j].pdbfile);
513      * 
514      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
515      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
516      * 
517      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
518      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
519      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
520      * mappings[j].pdbfile); }
521      * 
522      * annotations[index] = new Annotation("X",null,' ',0,col); } return
523      * annotations; } } } }
524      * 
525      * return annotations;
526      */
527   }
528
529   public void structureSelectionChanged()
530   {
531   }
532
533   public void sequenceSelectionChanged()
534   {
535   }
536
537   public void sequenceColoursChanged(Object source)
538   {
539     StructureListener sl;
540     for (int i = 0; i < listeners.size(); i++)
541     {
542       if (listeners.elementAt(i) instanceof StructureListener)
543       {
544         sl = (StructureListener) listeners.elementAt(i);
545         sl.updateColours(source);
546       }
547     }
548   }
549
550   public StructureMapping[] getMapping(String pdbfile)
551   {
552     Vector tmp = new Vector();
553     if (mappings != null)
554     {
555       for (int i = 0; i < mappings.length; i++)
556       {
557         if (mappings[i].pdbfile.equals(pdbfile))
558         {
559           tmp.addElement(mappings[i]);
560         }
561       }
562     }
563     StructureMapping[] ret = new StructureMapping[tmp.size()];
564     for (int i = 0; i < tmp.size(); i++)
565     {
566       ret[i] = (StructureMapping) tmp.elementAt(i);
567     }
568
569     return ret;
570   }
571
572   public String printMapping(String pdbfile)
573   {
574     StringBuffer sb = new StringBuffer();
575     for (int i = 0; i < mappings.length; i++)
576     {
577       if (mappings[i].pdbfile.equals(pdbfile))
578       {
579         sb.append(mappings[i].mappingDetails);
580       }
581     }
582
583     return sb.toString();
584   }
585
586   private int[] seqmappingrefs = null; // refcount for seqmappings elements
587
588   private synchronized void modifySeqMappingList(boolean add,
589           AlignedCodonFrame[] codonFrames)
590   {
591     if (!add && (seqmappings == null || seqmappings.size() == 0))
592       return;
593     if (seqmappings == null)
594       seqmappings = new Vector();
595     if (codonFrames != null && codonFrames.length > 0)
596     {
597       for (int cf = 0; cf < codonFrames.length; cf++)
598       {
599         if (seqmappings.contains(codonFrames[cf]))
600         {
601           if (add)
602           {
603             seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
604           }
605           else
606           {
607             if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
608             {
609               int pos = seqmappings.indexOf(codonFrames[cf]);
610               int[] nr = new int[seqmappingrefs.length - 1];
611               if (pos > 0)
612               {
613                 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
614               }
615               if (pos < seqmappingrefs.length - 1)
616               {
617                 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
618                         seqmappingrefs.length - pos - 2);
619               }
620             }
621           }
622         }
623         else
624         {
625           if (add)
626           {
627             seqmappings.addElement(codonFrames[cf]);
628
629             int[] nsr = new int[(seqmappingrefs == null) ? 1
630                     : seqmappingrefs.length + 1];
631             if (seqmappingrefs != null && seqmappingrefs.length > 0)
632               System.arraycopy(seqmappingrefs, 0, nsr, 0,
633                       seqmappingrefs.length);
634             nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
635             seqmappingrefs = nsr;
636           }
637         }
638       }
639     }
640   }
641
642   public void removeMappings(AlignedCodonFrame[] codonFrames)
643   {
644     modifySeqMappingList(false, codonFrames);
645   }
646
647   public void addMappings(AlignedCodonFrame[] codonFrames)
648   {
649     modifySeqMappingList(true, codonFrames);
650   }
651
652   Vector sel_listeners = new Vector();
653
654   public void addSelectionListener(SelectionListener selecter)
655   {
656     if (!sel_listeners.contains(selecter))
657     {
658       sel_listeners.addElement(selecter);
659     }
660   }
661
662   public void removeSelectionListener(SelectionListener toremove)
663   {
664     if (sel_listeners.contains(toremove))
665     {
666       sel_listeners.removeElement(toremove);
667     }
668   }
669
670   public synchronized void sendSelection(
671           jalview.datamodel.SequenceGroup selection,
672           jalview.datamodel.ColumnSelection colsel, SelectionSource source)
673   {
674     if (sel_listeners != null && sel_listeners.size() > 0)
675     {
676       Enumeration listeners = sel_listeners.elements();
677       while (listeners.hasMoreElements())
678       {
679         SelectionListener slis = ((SelectionListener) listeners
680                 .nextElement());
681         if (slis != source)
682         {
683           slis.selection(selection, colsel, source);
684         }
685         ;
686       }
687     }
688   }
689 }