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