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