JAL-2629 add ability to build a HMM from a group
[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.calculateInformation(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   private void _updateInformationRow(ProfilesI cnsns, long nseq)
685   {
686     if (information == null)
687     {
688       getInformation();
689     }
690     information.label = "Information for " + getName();
691     information.description = "Percent Identity";
692     informationData = cnsns;
693     // preserve width if already set
694     int aWidth = (information.annotations != null)
695             ? (endRes < information.annotations.length
696                     ? information.annotations.length : endRes + 1)
697             : endRes + 1;
698     information.annotations = null;
699     information.annotations = new Annotation[aWidth]; // should be alignment
700                                                       // width
701
702     AAFrequency.completeInformation(information, cnsns, startRes,
703             endRes + 1, ignoreBelowBackground, showSequenceLogo, nseq); // TODO:
704                                                                         // setting
705                                                             // container
706     // for
707     // ignoreGapsInInformationCalculation);
708   }
709
710   /**
711    * @param s
712    *          sequence to either add or remove from group
713    * @param recalc
714    *          flag passed to delete/addSequence to indicate if group properties
715    *          should be recalculated
716    */
717   public void addOrRemove(SequenceI s, boolean recalc)
718   {
719     synchronized (sequences)
720     {
721       if (sequences.contains(s))
722       {
723         deleteSequence(s, recalc);
724       }
725       else
726       {
727         addSequence(s, recalc);
728       }
729     }
730   }
731
732   /**
733    * remove
734    * 
735    * @param s
736    *          to be removed
737    * @param recalc
738    *          true means recalculate conservation
739    */
740   public void deleteSequence(SequenceI s, boolean recalc)
741   {
742     synchronized (sequences)
743     {
744       sequences.remove(s);
745
746       if (recalc)
747       {
748         recalcConservation();
749       }
750     }
751   }
752
753   /**
754    * 
755    * 
756    * @return the first column selected by this group. Runs from 0<=i<N_cols
757    */
758   @Override
759   public int getStartRes()
760   {
761     return startRes;
762   }
763
764   /**
765    * 
766    * @return the groups last selected column. Runs from 0<=i<N_cols
767    */
768   @Override
769   public int getEndRes()
770   {
771     return endRes;
772   }
773
774   /**
775    * Set the first column selected by this group. Runs from 0<=i<N_cols
776    * 
777    * @param i
778    */
779   public void setStartRes(int i)
780   {
781     startRes = i;
782   }
783
784   /**
785    * Set the groups last selected column. Runs from 0<=i<N_cols
786    * 
787    * @param i
788    */
789   public void setEndRes(int i)
790   {
791     endRes = i;
792   }
793
794   /**
795    * @return number of sequences in group
796    */
797   public int getSize()
798   {
799     return sequences.size();
800   }
801
802   /**
803    * @param i
804    * @return the ith sequence
805    */
806   public SequenceI getSequenceAt(int i)
807   {
808     return sequences.get(i);
809   }
810
811   /**
812    * @param state
813    *          colourText
814    */
815   public void setColourText(boolean state)
816   {
817     colourText = state;
818   }
819
820   /**
821    * DOCUMENT ME!
822    * 
823    * @return DOCUMENT ME!
824    */
825   public boolean getColourText()
826   {
827     return colourText;
828   }
829
830   /**
831    * DOCUMENT ME!
832    * 
833    * @param state
834    *          DOCUMENT ME!
835    */
836   public void setDisplayText(boolean state)
837   {
838     displayText = state;
839   }
840
841   /**
842    * DOCUMENT ME!
843    * 
844    * @return DOCUMENT ME!
845    */
846   public boolean getDisplayText()
847   {
848     return displayText;
849   }
850
851   /**
852    * DOCUMENT ME!
853    * 
854    * @param state
855    *          DOCUMENT ME!
856    */
857   public void setDisplayBoxes(boolean state)
858   {
859     displayBoxes = state;
860   }
861
862   /**
863    * DOCUMENT ME!
864    * 
865    * @return DOCUMENT ME!
866    */
867   public boolean getDisplayBoxes()
868   {
869     return displayBoxes;
870   }
871
872   /**
873    * computes the width of current set of sequences and returns it
874    * 
875    * @return DOCUMENT ME!
876    */
877   @Override
878   public int getWidth()
879   {
880     synchronized (sequences)
881     {
882       // MC This needs to get reset when characters are inserted and deleted
883       boolean first = true;
884       for (SequenceI seq : sequences)
885       {
886         if (first || seq.getLength() > width)
887         {
888           width = seq.getLength();
889           first = false;
890         }
891       }
892       return width;
893     }
894   }
895
896   /**
897    * DOCUMENT ME!
898    * 
899    * @param c
900    *          DOCUMENT ME!
901    */
902   public void setOutlineColour(Color c)
903   {
904     outlineColour = c;
905   }
906
907   /**
908    * DOCUMENT ME!
909    * 
910    * @return DOCUMENT ME!
911    */
912   public Color getOutlineColour()
913   {
914     return outlineColour;
915   }
916
917   /**
918    * 
919    * returns the sequences in the group ordered by the ordering given by al.
920    * this used to return an array with null entries regardless, new behaviour is
921    * below. TODO: verify that this does not affect use in applet or application
922    * 
923    * @param al
924    *          Alignment
925    * @return SequenceI[] intersection of sequences in group with al, ordered by
926    *         al, or null if group does not intersect with al
927    */
928   public SequenceI[] getSequencesInOrder(AlignmentI al)
929   {
930     return getSequencesInOrder(al, true);
931   }
932
933   /**
934    * return an array representing the intersection of the group with al,
935    * optionally returning an array the size of al.getHeight() where nulls mark
936    * the non-intersected sequences
937    * 
938    * @param al
939    * @param trim
940    * @return null or array
941    */
942   public SequenceI[] getSequencesInOrder(AlignmentI al, boolean trim)
943   {
944     synchronized (sequences)
945     {
946       int sSize = sequences.size();
947       int alHeight = al.getHeight();
948
949       SequenceI[] seqs = new SequenceI[(trim) ? sSize : alHeight];
950
951       int index = 0;
952       for (int i = 0; i < alHeight && index < sSize; i++)
953       {
954         if (sequences.contains(al.getSequenceAt(i)))
955         {
956           seqs[(trim) ? index : i] = al.getSequenceAt(i);
957           index++;
958         }
959       }
960       if (index == 0)
961       {
962         return null;
963       }
964       if (!trim)
965       {
966         return seqs;
967       }
968       if (index < seqs.length)
969       {
970         SequenceI[] dummy = seqs;
971         seqs = new SequenceI[index];
972         while (--index >= 0)
973         {
974           seqs[index] = dummy[index];
975           dummy[index] = null;
976         }
977       }
978       return seqs;
979     }
980   }
981
982   /**
983    * @return the idColour
984    */
985   public Color getIdColour()
986   {
987     return idColour;
988   }
989
990   /**
991    * @param idColour
992    *          the idColour to set
993    */
994   public void setIdColour(Color idColour)
995   {
996     this.idColour = idColour;
997   }
998
999   /**
1000    * @return the representative sequence for this group
1001    */
1002   @Override
1003   public SequenceI getSeqrep()
1004   {
1005     return seqrep;
1006   }
1007
1008   /**
1009    * set the representative sequence for this group. Note - this affects the
1010    * interpretation of the Hidereps attribute.
1011    * 
1012    * @param seqrep
1013    *          the seqrep to set (null means no sequence representative)
1014    */
1015   @Override
1016   public void setSeqrep(SequenceI seqrep)
1017   {
1018     this.seqrep = seqrep;
1019   }
1020
1021   /**
1022    * 
1023    * @return true if group has a sequence representative
1024    */
1025   @Override
1026   public boolean hasSeqrep()
1027   {
1028     return seqrep != null;
1029   }
1030
1031   /**
1032    * set visibility of sequences covered by (if no sequence representative is
1033    * defined) or represented by this group.
1034    * 
1035    * @param visibility
1036    */
1037   public void setHidereps(boolean visibility)
1038   {
1039     hidereps = visibility;
1040   }
1041
1042   /**
1043    * 
1044    * @return true if sequences represented (or covered) by this group should be
1045    *         hidden
1046    */
1047   public boolean isHidereps()
1048   {
1049     return hidereps;
1050   }
1051
1052   /**
1053    * set intended visibility of columns covered by this group
1054    * 
1055    * @param visibility
1056    */
1057   public void setHideCols(boolean visibility)
1058   {
1059     hidecols = visibility;
1060   }
1061
1062   /**
1063    * 
1064    * @return true if columns covered by group should be hidden
1065    */
1066   public boolean isHideCols()
1067   {
1068     return hidecols;
1069   }
1070
1071   /**
1072    * create a new sequence group from the intersection of this group with an
1073    * alignment Hashtable of hidden representatives
1074    * 
1075    * @param alignment
1076    *          (may not be null)
1077    * @param map
1078    *          (may be null)
1079    * @return new group containing sequences common to this group and alignment
1080    */
1081   public SequenceGroup intersect(AlignmentI alignment,
1082           Map<SequenceI, SequenceCollectionI> map)
1083   {
1084     SequenceGroup sgroup = new SequenceGroup(this);
1085     SequenceI[] insect = getSequencesInOrder(alignment);
1086     sgroup.sequences = new ArrayList<>();
1087     for (int s = 0; insect != null && s < insect.length; s++)
1088     {
1089       if (map == null || map.containsKey(insect[s]))
1090       {
1091         sgroup.sequences.add(insect[s]);
1092       }
1093     }
1094     return sgroup;
1095   }
1096
1097   /**
1098    * @return the showUnconserved
1099    */
1100   public boolean getShowNonconserved()
1101   {
1102     return showNonconserved;
1103   }
1104
1105   /**
1106    * @param showNonconserved
1107    *          the showUnconserved to set
1108    */
1109   public void setShowNonconserved(boolean displayNonconserved)
1110   {
1111     this.showNonconserved = displayNonconserved;
1112   }
1113
1114   /**
1115    * set this alignmentAnnotation object as the one used to render consensus
1116    * annotation
1117    * 
1118    * @param aan
1119    */
1120   public void setConsensus(AlignmentAnnotation aan)
1121   {
1122     if (consensus == null)
1123     {
1124       consensus = aan;
1125     }
1126   }
1127
1128   /**
1129    * 
1130    * @return automatically calculated consensus row note: the row is a stub if a
1131    *         consensus calculation has not yet been performed on the group
1132    */
1133   public AlignmentAnnotation getConsensus()
1134   {
1135     // TODO get or calculate and get consensus annotation row for this group
1136     int aWidth = this.getWidth();
1137     // pointer
1138     // possibility
1139     // here.
1140     if (aWidth < 0)
1141     {
1142       return null;
1143     }
1144     if (consensus == null)
1145     {
1146       consensus = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1147               100f, AlignmentAnnotation.BAR_GRAPH);
1148       consensus.hasText = true;
1149       consensus.autoCalculated = true;
1150       consensus.groupRef = this;
1151       consensus.label = "Consensus for " + getName();
1152       consensus.description = "Percent Identity";
1153     }
1154     return consensus;
1155   }
1156
1157   /**
1158    * 
1159    * @return information content annotation.
1160    */
1161   public AlignmentAnnotation getInformation()
1162   {
1163     // TODO get or calculate and get information annotation row for this group
1164     int aWidth = this.getWidth();
1165     // pointer
1166     // possibility
1167     // here.
1168     if (aWidth < 0)
1169     {
1170       return null;
1171     }
1172     if (information == null)
1173     {
1174       information = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1175               6.25f, AlignmentAnnotation.BAR_GRAPH);
1176       information.hasText = true;
1177       information.autoCalculated = false;
1178       information.groupRef = this;
1179       information.label = getName() + "_HMM";
1180       information.description = "Information content, measured in bits";
1181     }
1182     return information;
1183   }
1184
1185   /**
1186    * set this alignmentAnnotation object as the one used to render consensus
1187    * annotation
1188    * 
1189    * @param aan
1190    */
1191   public void setConservationRow(AlignmentAnnotation aan)
1192   {
1193     if (conservation == null)
1194     {
1195       conservation = aan;
1196     }
1197   }
1198
1199   /**
1200    * get the conservation annotation row for this group
1201    * 
1202    * @return autoCalculated annotation row
1203    */
1204   public AlignmentAnnotation getConservationRow()
1205   {
1206     if (conservation == null)
1207     {
1208       conservation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1209               11f, AlignmentAnnotation.BAR_GRAPH);
1210     }
1211
1212     conservation.hasText = true;
1213     conservation.autoCalculated = true;
1214     conservation.groupRef = this;
1215     conservation.label = "Conservation for " + getName();
1216     conservation.description = "Conservation for group " + getName()
1217             + " less than " + consPercGaps + "% gaps";
1218     return conservation;
1219   }
1220
1221   /**
1222    * 
1223    * @return true if annotation rows have been instantiated for this group
1224    */
1225   public boolean hasAnnotationRows()
1226   {
1227     return consensus != null || conservation != null;
1228   }
1229
1230   public SequenceI getConsensusSeq()
1231   {
1232     getConsensus();
1233     StringBuffer seqs = new StringBuffer();
1234     for (int i = 0; i < consensus.annotations.length; i++)
1235     {
1236       if (consensus.annotations[i] != null)
1237       {
1238         if (consensus.annotations[i].description.charAt(0) == '[')
1239         {
1240           seqs.append(consensus.annotations[i].description.charAt(1));
1241         }
1242         else
1243         {
1244           seqs.append(consensus.annotations[i].displayCharacter);
1245         }
1246       }
1247     }
1248
1249     SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1250             seqs.toString());
1251     sq.setDescription("Percentage Identity Consensus "
1252             + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1253     return sq;
1254   }
1255
1256   public void setIgnoreGapsConsensus(boolean state)
1257   {
1258     if (this.ignoreGapsInConsensus != state && consensus != null)
1259     {
1260       ignoreGapsInConsensus = state;
1261       recalcConservation();
1262     }
1263     ignoreGapsInConsensus = state;
1264   }
1265
1266   public boolean getIgnoreGapsConsensus()
1267   {
1268     return ignoreGapsInConsensus;
1269   }
1270
1271   public void setIgnoreBelowBackground(boolean state)
1272   {
1273     if (this.ignoreBelowBackground != state)
1274     {
1275       ignoreBelowBackground = state;
1276     }
1277     ignoreBelowBackground = state;
1278   }
1279
1280   public boolean getIgnoreBelowBackground()
1281   {
1282     return true;
1283   }
1284
1285   /**
1286    * @param showSequenceLogo
1287    *          indicates if a sequence logo is shown for consensus annotation
1288    */
1289   public void setshowSequenceLogo(boolean showSequenceLogo)
1290   {
1291     // TODO: decouple calculation from settings update
1292     if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1293     {
1294       this.showSequenceLogo = showSequenceLogo;
1295       recalcConservation();
1296     }
1297     this.showSequenceLogo = showSequenceLogo;
1298   }
1299
1300   /**
1301    * 
1302    * @param showConsHist
1303    *          flag indicating if the consensus histogram for this group should
1304    *          be rendered
1305    */
1306   public void setShowConsensusHistogram(boolean showConsHist)
1307   {
1308
1309     if (showConsensusHistogram != showConsHist && consensus != null)
1310     {
1311       this.showConsensusHistogram = showConsHist;
1312       recalcConservation();
1313     }
1314     this.showConsensusHistogram = showConsHist;
1315   }
1316
1317   /**
1318    * @return the showConsensusHistogram
1319    */
1320   public boolean isShowConsensusHistogram()
1321   {
1322     return showConsensusHistogram;
1323   }
1324
1325   /**
1326    * set flag indicating if logo should be normalised when rendered
1327    * 
1328    * @param norm
1329    */
1330   public void setNormaliseSequenceLogo(boolean norm)
1331   {
1332     normaliseSequenceLogo = norm;
1333   }
1334
1335   public boolean isNormaliseSequenceLogo()
1336   {
1337     return normaliseSequenceLogo;
1338   }
1339
1340   @Override
1341   /**
1342    * returns a new array with all annotation involving this group
1343    */
1344   public AlignmentAnnotation[] getAlignmentAnnotation()
1345   {
1346     // TODO add in other methods like 'getAlignmentAnnotation(String label),
1347     // etc'
1348     ArrayList<AlignmentAnnotation> annot = new ArrayList<>();
1349     synchronized (sequences)
1350     {
1351       for (SequenceI seq : sequences)
1352       {
1353         AlignmentAnnotation[] aa = seq.getAnnotation();
1354         if (aa != null)
1355         {
1356           for (AlignmentAnnotation al : aa)
1357           {
1358             if (al.groupRef == this)
1359             {
1360               annot.add(al);
1361             }
1362           }
1363         }
1364       }
1365       if (consensus != null)
1366       {
1367         annot.add(consensus);
1368       }
1369       if (conservation != null)
1370       {
1371         annot.add(conservation);
1372       }
1373     }
1374     return annot.toArray(new AlignmentAnnotation[0]);
1375   }
1376
1377   @Override
1378   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1379   {
1380     List<AlignmentAnnotation> aa = new ArrayList<>();
1381     if (calcId == null)
1382     {
1383       return aa;
1384     }
1385     for (AlignmentAnnotation a : getAlignmentAnnotation())
1386     {
1387       if (calcId.equals(a.getCalcId()))
1388       {
1389         aa.add(a);
1390       }
1391     }
1392     return aa;
1393   }
1394
1395   @Override
1396   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1397           String calcId, String label)
1398   {
1399     ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1400     for (AlignmentAnnotation ann : getAlignmentAnnotation())
1401     {
1402       if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1403               .equals(calcId)))
1404               && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1405               && (label == null || (ann.label != null && ann.label
1406                       .equals(label))))
1407       {
1408         aa.add(ann);
1409       }
1410     }
1411     return aa;
1412   }
1413
1414   /**
1415    * Answer true if any annotation matches the calcId passed in (if not null).
1416    * 
1417    * @param calcId
1418    * @return
1419    */
1420   public boolean hasAnnotation(String calcId)
1421   {
1422     if (calcId != null && !"".equals(calcId))
1423     {
1424       for (AlignmentAnnotation a : getAlignmentAnnotation())
1425       {
1426         if (a.getCalcId() == calcId)
1427         {
1428           return true;
1429         }
1430       }
1431     }
1432     return false;
1433   }
1434
1435   /**
1436    * Remove all sequences from the group (leaving other properties unchanged).
1437    */
1438   public void clear()
1439   {
1440     synchronized (sequences)
1441     {
1442       sequences.clear();
1443     }
1444   }
1445
1446   /**
1447    * Sets the alignment or group context for this group, and whether it is
1448    * defined as a group
1449    * 
1450    * @param ctx
1451    *          the context for the group
1452    * @param defined
1453    *          whether the group is defined on the alignment or is just a
1454    *          selection
1455    * @throws IllegalArgumentException
1456    *           if setting the context would result in a circular reference chain
1457    */
1458   public void setContext(AnnotatedCollectionI ctx, boolean defined)
1459   {
1460     setContext(ctx);
1461     this.isDefined = defined;
1462   }
1463
1464   /**
1465    * Sets the alignment or group context for this group
1466    * 
1467    * @param ctx
1468    *          the context for the group
1469    * @throws IllegalArgumentException
1470    *           if setting the context would result in a circular reference chain
1471    */
1472   public void setContext(AnnotatedCollectionI ctx)
1473   {
1474     AnnotatedCollectionI ref = ctx;
1475     while (ref != null)
1476     {
1477       if (ref == this || ref.getContext() == ctx)
1478       {
1479         throw new IllegalArgumentException(
1480                 "Circular reference in SequenceGroup.context");
1481       }
1482       ref = ref.getContext();
1483     }
1484     this.context = ctx;
1485   }
1486
1487   /*
1488    * (non-Javadoc)
1489    * 
1490    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1491    */
1492   @Override
1493   public AnnotatedCollectionI getContext()
1494   {
1495     return context;
1496   }
1497
1498   public boolean isDefined()
1499   {
1500     return isDefined;
1501   }
1502
1503   public void setColourScheme(ColourSchemeI scheme)
1504   {
1505     if (cs == null)
1506     {
1507       cs = new ResidueShader();
1508     }
1509     cs.setColourScheme(scheme);
1510   }
1511
1512   public void setGroupColourScheme(ResidueShaderI scheme)
1513   {
1514     cs = scheme;
1515   }
1516
1517   public ColourSchemeI getColourScheme()
1518   {
1519     return cs == null ? null : cs.getColourScheme();
1520   }
1521
1522   public ResidueShaderI getGroupColourScheme()
1523   {
1524     return cs;
1525   }
1526
1527   @Override
1528   public boolean isNucleotide()
1529   {
1530     if (context != null) {
1531       return context.isNucleotide();
1532     }
1533     return false;
1534   }
1535
1536   /**
1537    * @param seq
1538    * @return true if seq is a member of the group
1539    */
1540
1541   public boolean contains(SequenceI seq1)
1542   {
1543     return sequences.contains(seq1);
1544   }
1545
1546   /**
1547    * @param seq
1548    * @param apos
1549    * @return true if startRes<=apos and endRes>=apos and seq is in the group
1550    */
1551   public boolean contains(SequenceI seq, int apos)
1552   {
1553     return (startRes <= apos && endRes >= apos) && sequences.contains(seq);
1554   }
1555
1556   public boolean isShowInformationHistogram()
1557   {
1558     return showInformationHistogram;
1559   }
1560
1561   public void setShowInformationHistogram(boolean state)
1562   {
1563     if (showInformationHistogram != state && information != null)
1564     {
1565       this.showInformationHistogram = state;
1566       // recalcConservation(); TODO don't know what to do here next
1567     }
1568     this.showInformationHistogram = state;
1569
1570   }
1571
1572   public boolean isShowHMMSequenceLogo()
1573   {
1574     // TODO Auto-generated method stub
1575     return showHMMSequenceLogo;
1576   }
1577
1578   public void setshowHMMSequenceLogo(boolean state)
1579   {
1580     showHMMSequenceLogo = state;
1581
1582   }
1583
1584   public boolean isNormaliseHMMSequenceLogo()
1585   {
1586     // TODO Auto-generated method stub
1587     return normaliseHMMSequenceLogo;
1588   }
1589
1590   public void setNormaliseHMMSequenceLogo(boolean state)
1591   {
1592     normaliseSequenceLogo = state;
1593   }
1594
1595 }