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