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