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