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