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