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