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