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