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