JAL-2750 startRes now directly assigned
[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.List;
34 import java.util.Map;
35
36 /**
37  * Collects a set contiguous ranges on a set of sequences
38  * 
39  * @author $author$
40  * @version $Revision$
41  */
42 public class SequenceGroup implements AnnotatedCollectionI
43 {
44   // TODO ideally this event notification functionality should be separated into
45   // a
46   // subclass of ViewportProperties similarly to ViewportRanges. Done here as
47   // quick fix for JAL-2665
48   public static final String SEQ_GROUP_CHANGED = "Sequence group changed";
49
50   protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
51           this);
52
53   public void addPropertyChangeListener(PropertyChangeListener listener)
54   {
55     changeSupport.addPropertyChangeListener(listener);
56   }
57
58   public void removePropertyChangeListener(PropertyChangeListener listener)
59   {
60     changeSupport.removePropertyChangeListener(listener);
61   }
62   // end of event notification functionality initialisation
63
64   String groupName;
65
66   String description;
67
68   Conservation conserve;
69
70   boolean displayBoxes = true;
71
72   boolean displayText = true;
73
74   boolean colourText = false;
75
76   /**
77    * True if the group is defined as a group on the alignment, false if it is
78    * just a selection.
79    */
80   boolean isDefined = false;
81
82   /**
83    * after Olivier's non-conserved only character display
84    */
85   boolean showNonconserved = false;
86
87   /**
88    * group members
89    */
90   private List<SequenceI> sequences = new ArrayList<>();
91
92   /**
93    * representative sequence for this group (if any)
94    */
95   private SequenceI seqrep = null;
96
97   int width = -1;
98
99   /**
100    * Colourscheme applied to group if any
101    */
102   public ResidueShaderI cs;
103
104   /**
105    * start column (base 0)
106    */
107   private int startRes = 0;
108
109   /**
110    *  end column (base 0)
111    */
112   private int endRes = 0;
113
114   public Color outlineColour = Color.black;
115
116   public Color idColour = null;
117
118   public int thresholdTextColour = 0;
119
120   public Color textColour = Color.black;
121
122   public Color textColour2 = Color.white;
123
124   /**
125    * consensus calculation property
126    */
127   private boolean ignoreGapsInConsensus = true;
128
129   /**
130    * consensus calculation property
131    */
132   private boolean showSequenceLogo = false;
133
134   /**
135    * flag indicating if logo should be rendered normalised
136    */
137   private boolean normaliseSequenceLogo;
138
139   /*
140    * visibility of rows or represented rows covered by group
141    */
142   private boolean hidereps = false;
143
144   /*
145    * visibility of columns intersecting this group
146    */
147   private boolean hidecols = false;
148
149   AlignmentAnnotation consensus = null;
150
151   AlignmentAnnotation conservation = null;
152
153   private boolean showConsensusHistogram;
154
155   private AnnotatedCollectionI context;
156
157   /**
158    * Creates a new SequenceGroup object.
159    */
160   public SequenceGroup()
161   {
162     groupName = "JGroup:" + this.hashCode();
163     cs = new ResidueShader();
164   }
165
166   /**
167    * Creates a new SequenceGroup object.
168    * 
169    * @param sequences
170    * @param groupName
171    * @param scheme
172    * @param displayBoxes
173    * @param displayText
174    * @param colourText
175    * @param start
176    *          first column of group
177    * @param end
178    *          last column of group
179    */
180   public SequenceGroup(List<SequenceI> sequences, String groupName,
181           ColourSchemeI scheme, boolean displayBoxes, boolean displayText,
182           boolean colourText, int start, int end)
183   {
184     this();
185     this.sequences = sequences;
186     this.groupName = groupName;
187     this.displayBoxes = displayBoxes;
188     this.displayText = displayText;
189     this.colourText = colourText;
190     this.cs = new ResidueShader(scheme);
191     startRes = start;
192     endRes = end;
193     recalcConservation();
194   }
195
196   /**
197    * copy constructor
198    * 
199    * @param seqsel
200    */
201   public SequenceGroup(SequenceGroup seqsel)
202   {
203     this();
204     if (seqsel != null)
205     {
206       sequences = new ArrayList<>();
207       sequences.addAll(seqsel.sequences);
208       if (seqsel.groupName != null)
209       {
210         groupName = new String(seqsel.groupName);
211       }
212       displayBoxes = seqsel.displayBoxes;
213       displayText = seqsel.displayText;
214       colourText = seqsel.colourText;
215       
216       startRes = seqsel.startRes;
217       endRes = seqsel.endRes;
218       cs = new ResidueShader((ResidueShader) seqsel.cs);
219       if (seqsel.description != null)
220       {
221         description = new String(seqsel.description);
222       }
223       hidecols = seqsel.hidecols;
224       hidereps = seqsel.hidereps;
225       showNonconserved = seqsel.showNonconserved;
226       showSequenceLogo = seqsel.showSequenceLogo;
227       normaliseSequenceLogo = seqsel.normaliseSequenceLogo;
228       showConsensusHistogram = seqsel.showConsensusHistogram;
229       idColour = seqsel.idColour;
230       outlineColour = seqsel.outlineColour;
231       seqrep = seqsel.seqrep;
232       textColour = seqsel.textColour;
233       textColour2 = seqsel.textColour2;
234       thresholdTextColour = seqsel.thresholdTextColour;
235       width = seqsel.width;
236       ignoreGapsInConsensus = seqsel.ignoreGapsInConsensus;
237       if (seqsel.conserve != null)
238       {
239         recalcConservation(); // safer than
240         // aaFrequency = (Vector) seqsel.aaFrequency.clone(); // ??
241       }
242     }
243   }
244
245   public boolean isShowSequenceLogo()
246   {
247     return showSequenceLogo;
248   }
249
250   public SequenceI[] getSelectionAsNewSequences(AlignmentI align)
251   {
252     int iSize = sequences.size();
253     SequenceI[] seqs = new SequenceI[iSize];
254     SequenceI[] inorder = getSequencesInOrder(align);
255
256     for (int i = 0, ipos = 0; i < inorder.length; i++)
257     {
258       SequenceI seq = inorder[i];
259
260       seqs[ipos] = seq.getSubSequence(startRes, endRes + 1);
261       if (seqs[ipos] != null)
262       {
263         seqs[ipos].setDescription(seq.getDescription());
264         seqs[ipos].setDBRefs(seq.getDBRefs());
265         seqs[ipos].setSequenceFeatures(seq.getSequenceFeatures());
266         if (seq.getDatasetSequence() != null)
267         {
268           seqs[ipos].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; pos < alann.length; 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             seqs[ipos].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         if (consensus.annotations[i].description.charAt(0) == '[')
1200         {
1201           seqs.append(consensus.annotations[i].description.charAt(1));
1202         }
1203         else
1204         {
1205           seqs.append(consensus.annotations[i].displayCharacter);
1206         }
1207       }
1208     }
1209
1210     SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1211             seqs.toString());
1212     sq.setDescription("Percentage Identity Consensus "
1213             + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1214     return sq;
1215   }
1216
1217   public void setIgnoreGapsConsensus(boolean state)
1218   {
1219     if (this.ignoreGapsInConsensus != state && consensus != null)
1220     {
1221       ignoreGapsInConsensus = state;
1222       recalcConservation();
1223     }
1224     ignoreGapsInConsensus = state;
1225   }
1226
1227   public boolean getIgnoreGapsConsensus()
1228   {
1229     return ignoreGapsInConsensus;
1230   }
1231
1232   /**
1233    * @param showSequenceLogo
1234    *          indicates if a sequence logo is shown for consensus annotation
1235    */
1236   public void setshowSequenceLogo(boolean showSequenceLogo)
1237   {
1238     // TODO: decouple calculation from settings update
1239     if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1240     {
1241       this.showSequenceLogo = showSequenceLogo;
1242       recalcConservation();
1243     }
1244     this.showSequenceLogo = showSequenceLogo;
1245   }
1246
1247   /**
1248    * 
1249    * @param showConsHist
1250    *          flag indicating if the consensus histogram for this group should
1251    *          be rendered
1252    */
1253   public void setShowConsensusHistogram(boolean showConsHist)
1254   {
1255
1256     if (showConsensusHistogram != showConsHist && consensus != null)
1257     {
1258       this.showConsensusHistogram = showConsHist;
1259       recalcConservation();
1260     }
1261     this.showConsensusHistogram = showConsHist;
1262   }
1263
1264   /**
1265    * @return the showConsensusHistogram
1266    */
1267   public boolean isShowConsensusHistogram()
1268   {
1269     return showConsensusHistogram;
1270   }
1271
1272   /**
1273    * set flag indicating if logo should be normalised when rendered
1274    * 
1275    * @param norm
1276    */
1277   public void setNormaliseSequenceLogo(boolean norm)
1278   {
1279     normaliseSequenceLogo = norm;
1280   }
1281
1282   public boolean isNormaliseSequenceLogo()
1283   {
1284     return normaliseSequenceLogo;
1285   }
1286
1287   @Override
1288   /**
1289    * returns a new array with all annotation involving this group
1290    */
1291   public AlignmentAnnotation[] getAlignmentAnnotation()
1292   {
1293     // TODO add in other methods like 'getAlignmentAnnotation(String label),
1294     // etc'
1295     ArrayList<AlignmentAnnotation> annot = new ArrayList<>();
1296     synchronized (sequences)
1297     {
1298       for (SequenceI seq : sequences)
1299       {
1300         AlignmentAnnotation[] aa = seq.getAnnotation();
1301         if (aa != null)
1302         {
1303           for (AlignmentAnnotation al : aa)
1304           {
1305             if (al.groupRef == this)
1306             {
1307               annot.add(al);
1308             }
1309           }
1310         }
1311       }
1312       if (consensus != null)
1313       {
1314         annot.add(consensus);
1315       }
1316       if (conservation != null)
1317       {
1318         annot.add(conservation);
1319       }
1320     }
1321     return annot.toArray(new AlignmentAnnotation[0]);
1322   }
1323
1324   @Override
1325   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1326   {
1327     List<AlignmentAnnotation> aa = new ArrayList<>();
1328     if (calcId == null)
1329     {
1330       return aa;
1331     }
1332     for (AlignmentAnnotation a : getAlignmentAnnotation())
1333     {
1334       if (calcId.equals(a.getCalcId()))
1335       {
1336         aa.add(a);
1337       }
1338     }
1339     return aa;
1340   }
1341
1342   @Override
1343   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1344           String calcId, String label)
1345   {
1346     ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1347     for (AlignmentAnnotation ann : getAlignmentAnnotation())
1348     {
1349       if ((calcId == null || (ann.getCalcId() != null
1350               && ann.getCalcId().equals(calcId)))
1351               && (seq == null || (ann.sequenceRef != null
1352                       && ann.sequenceRef == seq))
1353               && (label == null
1354                       || (ann.label != null && ann.label.equals(label))))
1355       {
1356         aa.add(ann);
1357       }
1358     }
1359     return aa;
1360   }
1361
1362   /**
1363    * Answer true if any annotation matches the calcId passed in (if not null).
1364    * 
1365    * @param calcId
1366    * @return
1367    */
1368   public boolean hasAnnotation(String calcId)
1369   {
1370     if (calcId != null && !"".equals(calcId))
1371     {
1372       for (AlignmentAnnotation a : getAlignmentAnnotation())
1373       {
1374         if (a.getCalcId() == calcId)
1375         {
1376           return true;
1377         }
1378       }
1379     }
1380     return false;
1381   }
1382
1383   /**
1384    * Remove all sequences from the group (leaving other properties unchanged).
1385    */
1386   public void clear()
1387   {
1388     synchronized (sequences)
1389     {
1390       int before = sequences.size();
1391       sequences.clear();
1392       changeSupport.firePropertyChange(SEQ_GROUP_CHANGED, before,
1393               sequences.size());
1394     }
1395   }
1396
1397   /**
1398    * Sets the alignment or group context for this group, and whether it is
1399    * defined as a group
1400    * 
1401    * @param ctx
1402    *          the context for the group
1403    * @param defined
1404    *          whether the group is defined on the alignment or is just a
1405    *          selection
1406    * @throws IllegalArgumentException
1407    *           if setting the context would result in a circular reference chain
1408    */
1409   public void setContext(AnnotatedCollectionI ctx, boolean defined)
1410   {
1411     setContext(ctx);
1412     this.isDefined = defined;
1413   }
1414
1415   /**
1416    * Sets the alignment or group context for this group
1417    * 
1418    * @param ctx
1419    *          the context for the group
1420    * @throws IllegalArgumentException
1421    *           if setting the context would result in a circular reference chain
1422    */
1423   public void setContext(AnnotatedCollectionI ctx)
1424   {
1425     AnnotatedCollectionI ref = ctx;
1426     while (ref != null)
1427     {
1428       if (ref == this || ref.getContext() == ctx)
1429       {
1430         throw new IllegalArgumentException(
1431                 "Circular reference in SequenceGroup.context");
1432       }
1433       ref = ref.getContext();
1434     }
1435     this.context = ctx;
1436   }
1437
1438   /*
1439    * (non-Javadoc)
1440    * 
1441    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1442    */
1443   @Override
1444   public AnnotatedCollectionI getContext()
1445   {
1446     return context;
1447   }
1448
1449   public boolean isDefined()
1450   {
1451     return isDefined;
1452   }
1453
1454   public void setColourScheme(ColourSchemeI scheme)
1455   {
1456     if (cs == null)
1457     {
1458       cs = new ResidueShader();
1459     }
1460     cs.setColourScheme(scheme);
1461   }
1462
1463   public void setGroupColourScheme(ResidueShaderI scheme)
1464   {
1465     cs = scheme;
1466   }
1467
1468   public ColourSchemeI getColourScheme()
1469   {
1470     return cs == null ? null : cs.getColourScheme();
1471   }
1472
1473   public ResidueShaderI getGroupColourScheme()
1474   {
1475     return cs;
1476   }
1477
1478   @Override
1479   public boolean isNucleotide()
1480   {
1481     if (context != null)
1482     {
1483       return context.isNucleotide();
1484     }
1485     return false;
1486   }
1487
1488   /**
1489    * @param seq
1490    * @return true if seq is a member of the group
1491    */
1492
1493   public boolean contains(SequenceI seq1)
1494   {
1495     return sequences.contains(seq1);
1496   }
1497
1498   /**
1499    * @param seq
1500    * @param apos
1501    * @return true if startRes<=apos and endRes>=apos and seq is in the group
1502    */
1503   public boolean contains(SequenceI seq, int apos)
1504   {
1505     return (startRes <= apos && endRes >= apos) && sequences.contains(seq);
1506   }
1507 }