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