JAL-845 fixed start/end range of a mapped SequenceGroup
[jalview.git] / src / jalview / datamodel / SequenceGroup.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10  * of the License, or (at your option) any later version.
11  *  
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.
16  * 
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.
20  */
21 package jalview.datamodel;
22
23 import java.awt.Color;
24 import java.util.ArrayList;
25 import java.util.Hashtable;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Vector;
29
30 import jalview.analysis.AAFrequency;
31 import jalview.analysis.Conservation;
32 import jalview.schemes.ColourSchemeI;
33 import jalview.schemes.ResidueProperties;
34
35 /**
36  * Collects a set contiguous ranges on a set of sequences
37  * 
38  * @author $author$
39  * @version $Revision$
40  */
41 public class SequenceGroup implements AnnotatedCollectionI
42 {
43   String groupName;
44
45   String description;
46
47   Conservation conserve;
48
49   Vector aaFrequency;
50
51   boolean displayBoxes = true;
52
53   boolean displayText = true;
54
55   boolean colourText = false;
56
57   /**
58    * after Olivier's non-conserved only character display
59    */
60   boolean showNonconserved = false;
61
62   /**
63    * group members
64    */
65   private List<SequenceI> sequences = new ArrayList<SequenceI>();
66
67   /**
68    * representative sequence for this group (if any)
69    */
70   private SequenceI seqrep = null;
71
72   int width = -1;
73
74   /**
75    * Colourscheme applied to group if any
76    */
77   public ColourSchemeI cs;
78
79   // start column (base 0)
80   int startRes = 0;
81
82   // end column (base 0)
83   int endRes = 0;
84
85   public Color outlineColour = Color.black;
86
87   public Color idColour = null;
88
89   public int thresholdTextColour = 0;
90
91   public Color textColour = Color.black;
92
93   public Color textColour2 = Color.white;
94
95   /**
96    * consensus calculation property
97    */
98   private boolean ignoreGapsInConsensus = true;
99
100   /**
101    * consensus calculation property
102    */
103   private boolean showSequenceLogo = false;
104
105   /**
106    * flag indicating if logo should be rendered normalised
107    */
108   private boolean normaliseSequenceLogo;
109
110   /**
111    * @return the includeAllConsSymbols
112    */
113   public boolean isShowSequenceLogo()
114   {
115     return showSequenceLogo;
116   }
117
118   /**
119    * Creates a new SequenceGroup object.
120    */
121   public SequenceGroup()
122   {
123     groupName = "JGroup:" + this.hashCode();
124   }
125
126   /**
127    * Creates a new SequenceGroup object.
128    * 
129    * @param sequences
130    * @param groupName
131    * @param scheme
132    * @param displayBoxes
133    * @param displayText
134    * @param colourText
135    * @param start
136    *          first column of group
137    * @param end
138    *          last column of group
139    */
140   public SequenceGroup(List<SequenceI> sequences, String groupName,
141           ColourSchemeI scheme, boolean displayBoxes, boolean displayText,
142           boolean colourText, int start, int end)
143   {
144     this.sequences = sequences;
145     this.groupName = groupName;
146     this.displayBoxes = displayBoxes;
147     this.displayText = displayText;
148     this.colourText = colourText;
149     this.cs = scheme;
150     startRes = start;
151     endRes = end;
152     recalcConservation();
153   }
154
155   /**
156    * copy constructor
157    * 
158    * @param seqsel
159    */
160   public SequenceGroup(SequenceGroup seqsel)
161   {
162     if (seqsel != null)
163     {
164       sequences = new ArrayList<SequenceI>();
165       sequences.addAll(seqsel.sequences);
166       if (seqsel.groupName != null)
167       {
168         groupName = new String(seqsel.groupName);
169       }
170       displayBoxes = seqsel.displayBoxes;
171       displayText = seqsel.displayText;
172       colourText = seqsel.colourText;
173       startRes = seqsel.startRes;
174       endRes = seqsel.endRes;
175       cs = seqsel.cs;
176       if (seqsel.description != null)
177       {
178         description = new String(seqsel.description);
179       }
180       hidecols = seqsel.hidecols;
181       hidereps = seqsel.hidereps;
182       idColour = seqsel.idColour;
183       outlineColour = seqsel.outlineColour;
184       seqrep = seqsel.seqrep;
185       textColour = seqsel.textColour;
186       textColour2 = seqsel.textColour2;
187       thresholdTextColour = seqsel.thresholdTextColour;
188       width = seqsel.width;
189       ignoreGapsInConsensus = seqsel.ignoreGapsInConsensus;
190       if (seqsel.conserve != null)
191       {
192         recalcConservation(); // safer than
193         // aaFrequency = (Vector) seqsel.aaFrequency.clone(); // ??
194       }
195     }
196   }
197
198   public SequenceI[] getSelectionAsNewSequences(AlignmentI align)
199   {
200     int iSize = sequences.size();
201     SequenceI[] seqs = new SequenceI[iSize];
202     SequenceI[] inorder = getSequencesInOrder(align);
203
204     for (int i = 0, ipos = 0; i < inorder.length; i++)
205     {
206       SequenceI seq = inorder[i];
207
208       seqs[ipos] = seq.getSubSequence(startRes, endRes + 1);
209       if (seqs[ipos] != null)
210       {
211         seqs[ipos].setDescription(seq.getDescription());
212         seqs[ipos].setDBRef(seq.getDBRef());
213         seqs[ipos].setSequenceFeatures(seq.getSequenceFeatures());
214         if (seq.getDatasetSequence() != null)
215         {
216           seqs[ipos].setDatasetSequence(seq.getDatasetSequence());
217         }
218
219         if (seq.getAnnotation() != null)
220         {
221           AlignmentAnnotation[] alann = align.getAlignmentAnnotation();
222           // Only copy annotation that is either a score or referenced by the
223           // alignment's annotation vector
224           for (int a = 0; a < seq.getAnnotation().length; a++)
225           {
226             AlignmentAnnotation tocopy = seq.getAnnotation()[a];
227             if (alann != null)
228             {
229               boolean found = false;
230               for (int pos = 0; pos < alann.length; pos++)
231               {
232                 if (alann[pos] == tocopy)
233                 {
234                   found = true;
235                   break;
236                 }
237               }
238               if (!found)
239               {
240                 continue;
241               }
242             }
243             AlignmentAnnotation newannot = new AlignmentAnnotation(
244                     seq.getAnnotation()[a]);
245             newannot.restrict(startRes, endRes);
246             newannot.setSequenceRef(seqs[ipos]);
247             newannot.adjustForAlignment();
248             seqs[ipos].addAlignmentAnnotation(newannot);
249           }
250         }
251         ipos++;
252       }
253       else
254       {
255         iSize--;
256       }
257     }
258     if (iSize != inorder.length)
259     {
260       SequenceI[] nseqs = new SequenceI[iSize];
261       System.arraycopy(seqs, 0, nseqs, 0, iSize);
262       seqs = nseqs;
263     }
264     return seqs;
265
266   }
267
268   /**
269    * If sequence ends in gaps, the end residue can be correctly calculated here
270    * 
271    * @param seq
272    *          SequenceI
273    * @return int
274    */
275   public int findEndRes(SequenceI seq)
276   {
277     int eres = 0;
278     char ch;
279
280     for (int j = 0; j < endRes + 1 && j < seq.getLength(); j++)
281     {
282       ch = seq.getCharAt(j);
283       if (!jalview.util.Comparison.isGap((ch)))
284       {
285         eres++;
286       }
287     }
288
289     if (eres > 0)
290     {
291       eres += seq.getStart() - 1;
292     }
293
294     return eres;
295   }
296
297   @Override
298   public List<SequenceI> getSequences()
299   {
300     return sequences;
301   }
302
303   @Override
304   public List<SequenceI> getSequences(
305           Map<SequenceI, SequenceCollectionI> hiddenReps)
306   {
307     if (hiddenReps == null)
308     {
309       // TODO: need a synchronizedCollection here ?
310       return sequences;
311     }
312     else
313     {
314       List<SequenceI> allSequences = new ArrayList<SequenceI>();
315       for (SequenceI seq : sequences)
316       {
317         allSequences.add(seq);
318         if (hiddenReps.containsKey(seq))
319         {
320           SequenceCollectionI hsg = hiddenReps.get(seq);
321           for (SequenceI seq2 : hsg.getSequences())
322           {
323             if (seq2 != seq && !allSequences.contains(seq2))
324             {
325               allSequences.add(seq2);
326             }
327           }
328         }
329       }
330
331       return allSequences;
332     }
333   }
334
335   public SequenceI[] getSequencesAsArray(
336           Map<SequenceI, SequenceCollectionI> map)
337   {
338     List<SequenceI> tmp = getSequences(map);
339     if (tmp == null)
340     {
341       return null;
342     }
343     return tmp.toArray(new SequenceI[tmp.size()]);
344   }
345
346   /**
347    * DOCUMENT ME!
348    * 
349    * @param col
350    *          DOCUMENT ME!
351    * 
352    * @return DOCUMENT ME!
353    */
354   public boolean adjustForRemoveLeft(int col)
355   {
356     // return value is true if the group still exists
357     if (startRes >= col)
358     {
359       startRes = startRes - col;
360     }
361
362     if (endRes >= col)
363     {
364       endRes = endRes - col;
365
366       if (startRes > endRes)
367       {
368         startRes = 0;
369       }
370     }
371     else
372     {
373       // must delete this group!!
374       return false;
375     }
376
377     return true;
378   }
379
380   /**
381    * DOCUMENT ME!
382    * 
383    * @param col
384    *          DOCUMENT ME!
385    * 
386    * @return DOCUMENT ME!
387    */
388   public boolean adjustForRemoveRight(int col)
389   {
390     if (startRes > col)
391     {
392       // delete this group
393       return false;
394     }
395
396     if (endRes >= col)
397     {
398       endRes = col;
399     }
400
401     return true;
402   }
403
404   /**
405    * DOCUMENT ME!
406    * 
407    * @return DOCUMENT ME!
408    */
409   public String getName()
410   {
411     return groupName;
412   }
413
414   public String getDescription()
415   {
416     return description;
417   }
418
419   /**
420    * DOCUMENT ME!
421    * 
422    * @param name
423    *          DOCUMENT ME!
424    */
425   public void setName(String name)
426   {
427     groupName = name;
428     // TODO: URGENT: update dependent objects (annotation row)
429   }
430
431   public void setDescription(String desc)
432   {
433     description = desc;
434   }
435
436   /**
437    * DOCUMENT ME!
438    * 
439    * @return DOCUMENT ME!
440    */
441   public Conservation getConservation()
442   {
443     return conserve;
444   }
445
446   /**
447    * DOCUMENT ME!
448    * 
449    * @param c
450    *          DOCUMENT ME!
451    */
452   public void setConservation(Conservation c)
453   {
454     conserve = c;
455   }
456
457   /**
458    * Add s to this sequence group. If aligment sequence is already contained in
459    * group, it will not be added again, but recalculation may happen if the flag
460    * is set.
461    * 
462    * @param s
463    *          alignment sequence to be added
464    * @param recalc
465    *          true means Group's conservation should be recalculated
466    */
467   public void addSequence(SequenceI s, boolean recalc)
468   {
469     synchronized (sequences)
470     {
471       if (s != null && !sequences.contains(s))
472       {
473         sequences.add(s);
474       }
475
476       if (recalc)
477       {
478         recalcConservation();
479       }
480     }
481   }
482
483   /**
484    * Max Gaps Threshold (percent) for performing a conservation calculation
485    */
486   private int consPercGaps = 25;
487
488   /**
489    * @return Max Gaps Threshold for performing a conservation calculation
490    */
491   public int getConsPercGaps()
492   {
493     return consPercGaps;
494   }
495
496   /**
497    * set Max Gaps Threshold (percent) for performing a conservation calculation
498    * 
499    * @param consPercGaps
500    */
501   public void setConsPercGaps(int consPercGaps)
502   {
503     this.consPercGaps = consPercGaps;
504   }
505
506   /**
507    * calculate residue conservation for group - but only if necessary.
508    */
509   public void recalcConservation()
510   {
511     if (cs == null && consensus == null && conservation == null)
512     {
513       return;
514     }
515     try
516     {
517       Hashtable cnsns[] = AAFrequency.calculate(sequences, startRes,
518               endRes + 1, showSequenceLogo);
519       if (consensus != null)
520       {
521         _updateConsensusRow(cnsns, sequences.size());
522       }
523       if (cs != null)
524       {
525         cs.setConsensus(cnsns);
526       }
527
528       if ((conservation != null)
529               || (cs != null && cs.conservationApplied()))
530       {
531         Conservation c = new Conservation(groupName,
532                 ResidueProperties.propHash, 3, sequences, startRes,
533                 endRes + 1);
534         c.calculate();
535         c.verdict(false, consPercGaps);
536         if (conservation != null)
537         {
538           _updateConservationRow(c);
539         }
540         if (cs != null)
541         {
542           if (cs.conservationApplied())
543           {
544             cs.setConservation(c);
545           }
546         }
547       }
548       if (cs != null)
549       {
550         cs.alignmentChanged(context != null ? context : this, null);
551       }
552     } catch (java.lang.OutOfMemoryError err)
553     {
554       // TODO: catch OOM
555       System.out.println("Out of memory loading groups: " + err);
556     }
557
558   }
559
560   private void _updateConservationRow(Conservation c)
561   {
562     if (conservation == null)
563     {
564       getConservation();
565     }
566     // update Labels
567     conservation.label = "Conservation for " + getName();
568     conservation.description = "Conservation for group " + getName()
569             + " less than " + consPercGaps + "% gaps";
570     // preserve width if already set
571     int aWidth = (conservation.annotations != null) ? (endRes < conservation.annotations.length ? conservation.annotations.length
572             : endRes + 1)
573             : endRes + 1;
574     conservation.annotations = null;
575     conservation.annotations = new Annotation[aWidth]; // should be alignment
576                                                        // width
577     c.completeAnnotations(conservation, null, startRes, endRes + 1);
578   }
579
580   public Hashtable[] consensusData = null;
581
582   private void _updateConsensusRow(Hashtable[] cnsns, long nseq)
583   {
584     if (consensus == null)
585     {
586       getConsensus();
587     }
588     consensus.label = "Consensus for " + getName();
589     consensus.description = "Percent Identity";
590     consensusData = cnsns;
591     // preserve width if already set
592     int aWidth = (consensus.annotations != null) ? (endRes < consensus.annotations.length ? consensus.annotations.length
593             : endRes + 1)
594             : endRes + 1;
595     consensus.annotations = null;
596     consensus.annotations = new Annotation[aWidth]; // should be alignment width
597
598     AAFrequency.completeConsensus(consensus, cnsns, startRes, endRes + 1,
599             ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO: setting
600                                                             // container
601     // for
602     // ignoreGapsInConsensusCalculation);
603   }
604
605   /**
606    * @param s
607    *          sequence to either add or remove from group
608    * @param recalc
609    *          flag passed to delete/addSequence to indicate if group properties
610    *          should be recalculated
611    */
612   public void addOrRemove(SequenceI s, boolean recalc)
613   {
614     synchronized (sequences)
615     {
616     if (sequences.contains(s))
617     {
618       deleteSequence(s, recalc);
619     }
620     else
621     {
622       addSequence(s, recalc);
623       }
624     }
625   }
626
627   /**
628    * remove
629    * 
630    * @param s
631    *          to be removed
632    * @param recalc
633    *          true means recalculate conservation
634    */
635   public void deleteSequence(SequenceI s, boolean recalc)
636   {
637     synchronized (sequences)
638     {
639       sequences.remove(s);
640
641       if (recalc)
642       {
643         recalcConservation();
644       }
645     }
646   }
647
648   /**
649    * 
650    * 
651    * @return the first column selected by this group. Runs from 0<=i<N_cols
652    */
653   @Override
654   public int getStartRes()
655   {
656     return startRes;
657   }
658
659   /**
660    * 
661    * @return the groups last selected column. Runs from 0<=i<N_cols
662    */
663   @Override
664   public int getEndRes()
665   {
666     return endRes;
667   }
668
669   /**
670    * Set the first column selected by this group. Runs from 0<=i<N_cols
671    * 
672    * @param i
673    */
674   public void setStartRes(int i)
675   {
676     startRes = i;
677   }
678
679   /**
680    * Set the groups last selected column. Runs from 0<=i<N_cols
681    * 
682    * @param i
683    */
684   public void setEndRes(int i)
685   {
686     endRes = i;
687   }
688
689   /**
690    * @return number of sequences in group
691    */
692   public int getSize()
693   {
694     return sequences.size();
695   }
696
697   /**
698    * @param i
699    * @return the ith sequence
700    */
701   public SequenceI getSequenceAt(int i)
702   {
703     return sequences.get(i);
704   }
705
706   /**
707    * @param state
708    *          colourText
709    */
710   public void setColourText(boolean state)
711   {
712     colourText = state;
713   }
714
715   /**
716    * DOCUMENT ME!
717    * 
718    * @return DOCUMENT ME!
719    */
720   public boolean getColourText()
721   {
722     return colourText;
723   }
724
725   /**
726    * DOCUMENT ME!
727    * 
728    * @param state
729    *          DOCUMENT ME!
730    */
731   public void setDisplayText(boolean state)
732   {
733     displayText = state;
734   }
735
736   /**
737    * DOCUMENT ME!
738    * 
739    * @return DOCUMENT ME!
740    */
741   public boolean getDisplayText()
742   {
743     return displayText;
744   }
745
746   /**
747    * DOCUMENT ME!
748    * 
749    * @param state
750    *          DOCUMENT ME!
751    */
752   public void setDisplayBoxes(boolean state)
753   {
754     displayBoxes = state;
755   }
756
757   /**
758    * DOCUMENT ME!
759    * 
760    * @return DOCUMENT ME!
761    */
762   public boolean getDisplayBoxes()
763   {
764     return displayBoxes;
765   }
766
767   /**
768    * computes the width of current set of sequences and returns it
769    * 
770    * @return DOCUMENT ME!
771    */
772   @Override
773   public int getWidth()
774   {
775     synchronized (sequences)
776     {
777       // MC This needs to get reset when characters are inserted and deleted
778       boolean first=true;
779       for (SequenceI seq:sequences) {
780         if (first || seq.getLength() > width)
781         {
782           width = seq.getLength();
783           first = false;
784         }
785       }
786       return width;
787     }
788   }
789
790   /**
791    * DOCUMENT ME!
792    * 
793    * @param c
794    *          DOCUMENT ME!
795    */
796   public void setOutlineColour(Color c)
797   {
798     outlineColour = c;
799   }
800
801   /**
802    * DOCUMENT ME!
803    * 
804    * @return DOCUMENT ME!
805    */
806   public Color getOutlineColour()
807   {
808     return outlineColour;
809   }
810
811   /**
812    * 
813    * returns the sequences in the group ordered by the ordering given by al.
814    * this used to return an array with null entries regardless, new behaviour is
815    * below. TODO: verify that this does not affect use in applet or application
816    * 
817    * @param al
818    *          Alignment
819    * @return SequenceI[] intersection of sequences in group with al, ordered by
820    *         al, or null if group does not intersect with al
821    */
822   public SequenceI[] getSequencesInOrder(AlignmentI al)
823   {
824     return getSequencesInOrder(al, true);
825   }
826
827   /**
828    * return an array representing the intersection of the group with al,
829    * optionally returning an array the size of al.getHeight() where nulls mark
830    * the non-intersected sequences
831    * 
832    * @param al
833    * @param trim
834    * @return null or array
835    */
836   public SequenceI[] getSequencesInOrder(AlignmentI al, boolean trim)
837   {
838     synchronized (sequences)
839     {
840       int sSize = sequences.size();
841       int alHeight = al.getHeight();
842
843       SequenceI[] seqs = new SequenceI[(trim) ? sSize : alHeight];
844
845       int index = 0;
846       for (int i = 0; i < alHeight && index < sSize; i++)
847       {
848         if (sequences.contains(al.getSequenceAt(i)))
849         {
850           seqs[(trim) ? index : i] = al.getSequenceAt(i);
851           index++;
852         }
853       }
854       if (index == 0)
855       {
856         return null;
857       }
858       if (!trim)
859       {
860         return seqs;
861       }
862       if (index < seqs.length)
863       {
864         SequenceI[] dummy = seqs;
865         seqs = new SequenceI[index];
866         while (--index >= 0)
867         {
868           seqs[index] = dummy[index];
869           dummy[index] = null;
870         }
871       }
872       return seqs;
873     }
874   }
875
876   /**
877    * @return the idColour
878    */
879   public Color getIdColour()
880   {
881     return idColour;
882   }
883
884   /**
885    * @param idColour
886    *          the idColour to set
887    */
888   public void setIdColour(Color idColour)
889   {
890     this.idColour = idColour;
891   }
892
893   /**
894    * @return the representative sequence for this group
895    */
896   public SequenceI getSeqrep()
897   {
898     return seqrep;
899   }
900
901   /**
902    * set the representative sequence for this group. Note - this affects the
903    * interpretation of the Hidereps attribute.
904    * 
905    * @param seqrep
906    *          the seqrep to set (null means no sequence representative)
907    */
908   public void setSeqrep(SequenceI seqrep)
909   {
910     this.seqrep = seqrep;
911   }
912
913   /**
914    * 
915    * @return true if group has a sequence representative
916    */
917   public boolean hasSeqrep()
918   {
919     return seqrep != null;
920   }
921
922   /**
923    * visibility of rows or represented rows covered by group
924    */
925   private boolean hidereps = false;
926
927   /**
928    * set visibility of sequences covered by (if no sequence representative is
929    * defined) or represented by this group.
930    * 
931    * @param visibility
932    */
933   public void setHidereps(boolean visibility)
934   {
935     hidereps = visibility;
936   }
937
938   /**
939    * 
940    * @return true if sequences represented (or covered) by this group should be
941    *         hidden
942    */
943   public boolean isHidereps()
944   {
945     return hidereps;
946   }
947
948   /**
949    * visibility of columns intersecting this group
950    */
951   private boolean hidecols = false;
952
953   /**
954    * set intended visibility of columns covered by this group
955    * 
956    * @param visibility
957    */
958   public void setHideCols(boolean visibility)
959   {
960     hidecols = visibility;
961   }
962
963   /**
964    * 
965    * @return true if columns covered by group should be hidden
966    */
967   public boolean isHideCols()
968   {
969     return hidecols;
970   }
971
972   /**
973    * create a new sequence group from the intersection of this group with an
974    * alignment Hashtable of hidden representatives
975    * 
976    * @param alignment
977    *          (may not be null)
978    * @param map
979    *          (may be null)
980    * @return new group containing sequences common to this group and alignment
981    */
982   public SequenceGroup intersect(AlignmentI alignment,
983           Map<SequenceI, SequenceCollectionI> map)
984   {
985     SequenceGroup sgroup = new SequenceGroup(this);
986     SequenceI[] insect = getSequencesInOrder(alignment);
987     sgroup.sequences = new ArrayList<SequenceI>();
988     for (int s = 0; insect != null && s < insect.length; s++)
989     {
990       if (map == null || map.containsKey(insect[s]))
991       {
992         sgroup.sequences.add(insect[s]);
993       }
994     }
995     return sgroup;
996   }
997
998   /**
999    * @return the showUnconserved
1000    */
1001   public boolean getShowNonconserved()
1002   {
1003     return showNonconserved;
1004   }
1005
1006   /**
1007    * @param showNonconserved
1008    *          the showUnconserved to set
1009    */
1010   public void setShowNonconserved(boolean displayNonconserved)
1011   {
1012     this.showNonconserved = displayNonconserved;
1013   }
1014
1015   AlignmentAnnotation consensus = null, conservation = null;
1016
1017   /**
1018    * flag indicating if consensus histogram should be rendered
1019    */
1020   private boolean showConsensusHistogram;
1021
1022   /**
1023    * set this alignmentAnnotation object as the one used to render consensus
1024    * annotation
1025    * 
1026    * @param aan
1027    */
1028   public void setConsensus(AlignmentAnnotation aan)
1029   {
1030     if (consensus == null)
1031     {
1032       consensus = aan;
1033     }
1034   }
1035
1036   /**
1037    * 
1038    * @return automatically calculated consensus row
1039    */
1040   public AlignmentAnnotation getConsensus()
1041   {
1042     // TODO get or calculate and get consensus annotation row for this group
1043     int aWidth = this.getWidth();
1044     // pointer
1045     // possibility
1046     // here.
1047     if (aWidth < 0)
1048     {
1049       return null;
1050     }
1051     if (consensus == null)
1052     {
1053       consensus = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1054               100f, AlignmentAnnotation.BAR_GRAPH);
1055       consensus.hasText = true;
1056       consensus.autoCalculated = true;
1057       consensus.groupRef = this;
1058       consensus.label = "Consensus for " + getName();
1059       consensus.description = "Percent Identity";
1060     }
1061     return consensus;
1062   }
1063
1064   /**
1065    * set this alignmentAnnotation object as the one used to render consensus
1066    * annotation
1067    * 
1068    * @param aan
1069    */
1070   public void setConservationRow(AlignmentAnnotation aan)
1071   {
1072     if (conservation == null)
1073     {
1074       conservation = aan;
1075     }
1076   }
1077
1078   /**
1079    * get the conservation annotation row for this group
1080    * 
1081    * @return autoCalculated annotation row
1082    */
1083   public AlignmentAnnotation getConservationRow()
1084   {
1085     if (conservation == null)
1086     {
1087       conservation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1088               11f, AlignmentAnnotation.BAR_GRAPH);
1089     }
1090
1091     conservation.hasText = true;
1092     conservation.autoCalculated = true;
1093     conservation.groupRef = this;
1094     conservation.label = "Conservation for " + getName();
1095     conservation.description = "Conservation for group " + getName()
1096             + " less than " + consPercGaps + "% gaps";
1097     return conservation;
1098   }
1099
1100   /**
1101    * 
1102    * @return true if annotation rows have been instantiated for this group
1103    */
1104   public boolean hasAnnotationRows()
1105   {
1106     return consensus != null || conservation != null;
1107   }
1108
1109   public SequenceI getConsensusSeq()
1110   {
1111     getConsensus();
1112     StringBuffer seqs = new StringBuffer();
1113     for (int i = 0; i < consensus.annotations.length; i++)
1114     {
1115       if (consensus.annotations[i] != null)
1116       {
1117         if (consensus.annotations[i].description.charAt(0) == '[')
1118         {
1119           seqs.append(consensus.annotations[i].description.charAt(1));
1120         }
1121         else
1122         {
1123           seqs.append(consensus.annotations[i].displayCharacter);
1124         }
1125       }
1126     }
1127
1128     SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1129             seqs.toString());
1130     sq.setDescription("Percentage Identity Consensus "
1131             + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1132     return sq;
1133   }
1134
1135   public void setIgnoreGapsConsensus(boolean state)
1136   {
1137     if (this.ignoreGapsInConsensus != state && consensus != null)
1138     {
1139       ignoreGapsInConsensus = state;
1140       recalcConservation();
1141     }
1142     ignoreGapsInConsensus = state;
1143   }
1144
1145   public boolean getIgnoreGapsConsensus()
1146   {
1147     return ignoreGapsInConsensus;
1148   }
1149
1150   /**
1151    * @param showSequenceLogo
1152    *          indicates if a sequence logo is shown for consensus annotation
1153    */
1154   public void setshowSequenceLogo(boolean showSequenceLogo)
1155   {
1156     // TODO: decouple calculation from settings update
1157     if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1158     {
1159       this.showSequenceLogo = showSequenceLogo;
1160       recalcConservation();
1161     }
1162     this.showSequenceLogo = showSequenceLogo;
1163   }
1164
1165   /**
1166    * 
1167    * @param showConsHist
1168    *          flag indicating if the consensus histogram for this group should
1169    *          be rendered
1170    */
1171   public void setShowConsensusHistogram(boolean showConsHist)
1172   {
1173
1174     if (showConsensusHistogram != showConsHist && consensus != null)
1175     {
1176       this.showConsensusHistogram = showConsHist;
1177       recalcConservation();
1178     }
1179     this.showConsensusHistogram = showConsHist;
1180   }
1181
1182   /**
1183    * @return the showConsensusHistogram
1184    */
1185   public boolean isShowConsensusHistogram()
1186   {
1187     return showConsensusHistogram;
1188   }
1189
1190   /**
1191    * set flag indicating if logo should be normalised when rendered
1192    * 
1193    * @param norm
1194    */
1195   public void setNormaliseSequenceLogo(boolean norm)
1196   {
1197     normaliseSequenceLogo = norm;
1198   }
1199
1200   public boolean isNormaliseSequenceLogo()
1201   {
1202     return normaliseSequenceLogo;
1203   }
1204
1205   @Override
1206   /**
1207    * returns a new array with all annotation involving this group
1208    */
1209   public AlignmentAnnotation[] getAlignmentAnnotation()
1210   {
1211     // TODO add in other methods like 'getAlignmentAnnotation(String label),
1212     // etc'
1213     ArrayList<AlignmentAnnotation> annot = new ArrayList<AlignmentAnnotation>();
1214     synchronized (sequences)
1215     {
1216       for (SequenceI seq : sequences)
1217       {
1218         AlignmentAnnotation[] aa = seq.getAnnotation();
1219         if (aa != null)
1220         {
1221           for (AlignmentAnnotation al : aa)
1222           {
1223             if (al.groupRef == this)
1224             {
1225               annot.add(al);
1226             }
1227           }
1228         }
1229       }
1230       if (consensus != null)
1231       {
1232         annot.add(consensus);
1233       }
1234       if (conservation != null)
1235       {
1236         annot.add(conservation);
1237       }
1238     }
1239     return annot.toArray(new AlignmentAnnotation[0]);
1240   }
1241
1242   @Override
1243   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1244   {
1245     ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1246     for (AlignmentAnnotation a : getAlignmentAnnotation())
1247     {
1248       if (a.getCalcId() == calcId)
1249       {
1250         aa.add(a);
1251       }
1252     }
1253     return aa;
1254   }
1255
1256   /**
1257    * Returns a list of annotations that match the specified sequenceRef, calcId
1258    * and label, ignoring null values.
1259    * 
1260    * @return list of AlignmentAnnotation objects
1261    */
1262   @Override
1263   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1264           String calcId, String label)
1265   {
1266     ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1267     for (AlignmentAnnotation ann : getAlignmentAnnotation())
1268     {
1269       if (ann.getCalcId() != null && ann.getCalcId().equals(calcId)
1270               && ann.sequenceRef != null && ann.sequenceRef == seq
1271               && ann.label != null && ann.label.equals(label))
1272       {
1273         aa.add(ann);
1274       }
1275     }
1276     return aa;
1277   }
1278
1279   /**
1280    * Answer true if any annotation matches the calcId passed in (if not null).
1281    * 
1282    * @param calcId
1283    * @return
1284    */
1285   public boolean hasAnnotation(String calcId)
1286   {
1287     if (calcId != null && !"".equals(calcId))
1288     {
1289       for (AlignmentAnnotation a : getAlignmentAnnotation())
1290       {
1291         if (a.getCalcId() == calcId)
1292         {
1293           return true;
1294         }
1295       }
1296     }
1297     return false;
1298   }
1299
1300   /**
1301    * Remove all sequences from the group (leaving other properties unchanged).
1302    */
1303   public void clear()
1304   {
1305     synchronized (sequences)
1306     {
1307       sequences.clear();
1308     }
1309   }
1310
1311   private AnnotatedCollectionI context;
1312
1313   /**
1314    * set the alignment or group context for this group
1315    * 
1316    * @param context
1317    */
1318   public void setContext(AnnotatedCollectionI context)
1319   {
1320     this.context = context;
1321   }
1322
1323   /*
1324    * (non-Javadoc)
1325    * 
1326    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1327    */
1328   @Override
1329   public AnnotatedCollectionI getContext()
1330   {
1331     return context;
1332   }
1333 }