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