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