JAL-2629 tidy unit tests, constants etc
[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
49   // subclass of ViewportProperties similarly to ViewportRanges. Done here as
50   // quick fix for JAL-2665
51   public static final String SEQ_GROUP_CHANGED = "Sequence group changed";
52
53   protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
54           this);
55
56   public void addPropertyChangeListener(PropertyChangeListener listener)
57   {
58     changeSupport.addPropertyChangeListener(listener);
59   }
60
61   public void removePropertyChangeListener(PropertyChangeListener listener)
62   {
63     changeSupport.removePropertyChangeListener(listener);
64   }
65   // end of event notification functionality initialisation
66
67   String groupName;
68
69   String description;
70
71   Conservation conserve;
72
73   boolean displayBoxes = true;
74
75   boolean displayText = true;
76
77   boolean colourText = false;
78
79   /**
80    * True if the group is defined as a group on the alignment, false if it is
81    * just a selection.
82    */
83   boolean isDefined = false;
84
85   /**
86    * after Olivier's non-conserved only character display
87    */
88   boolean showNonconserved = false;
89
90   /**
91    * group members
92    */
93   private List<SequenceI> sequences = new ArrayList<>();
94
95   /**
96    * representative sequence for this group (if any)
97    */
98   private SequenceI seqrep = null;
99
100   int width = -1;
101
102   /**
103    * Colourscheme applied to group if any
104    */
105   public ResidueShaderI cs;
106
107   // start column (base 0)
108   int startRes = 0;
109
110   // end column (base 0)
111   int endRes = 0;
112
113   public Color outlineColour = Color.black;
114
115   public Color idColour = null;
116
117   public int thresholdTextColour = 0;
118
119   public Color textColour = Color.black;
120
121   public Color textColour2 = Color.white;
122
123   /**
124    * consensus calculation property
125    */
126   private boolean ignoreGapsInConsensus = true;
127
128   private boolean ignoreBelowBackground = true;
129
130   private boolean infoLetterHeight = false;
131
132   /**
133    * consensus calculation property
134    */
135   private boolean showSequenceLogo = false;
136
137   /**
138    * flag indicating if logo should be rendered normalised
139    */
140   private boolean normaliseSequenceLogo;
141
142   /*
143    * visibility of rows or represented rows covered by group
144    */
145   private boolean hidereps = false;
146
147   /*
148    * visibility of columns intersecting this group
149    */
150   private boolean hidecols = false;
151
152   AlignmentAnnotation consensus = null;
153
154   AlignmentAnnotation conservation = null;
155
156   AlignmentAnnotation information = null;
157
158   private boolean showConsensusHistogram;
159
160   private AnnotatedCollectionI context;
161
162   private boolean showHMMSequenceLogo;
163
164   private boolean normaliseHMMSequenceLogo;
165
166   private boolean showInformationHistogram;
167
168   /**
169    * Creates a new SequenceGroup object.
170    */
171   public SequenceGroup()
172   {
173     groupName = "JGroup:" + this.hashCode();
174     cs = new ResidueShader();
175   }
176
177   /**
178    * Creates a new SequenceGroup object.
179    * 
180    * @param sequences
181    * @param groupName
182    * @param scheme
183    * @param displayBoxes
184    * @param displayText
185    * @param colourText
186    * @param start
187    *          first column of group
188    * @param end
189    *          last column of group
190    */
191   public SequenceGroup(List<SequenceI> sequences, String groupName,
192           ColourSchemeI scheme, boolean displayBoxes, boolean displayText,
193           boolean colourText, int start, int end)
194   {
195     this();
196     this.sequences = sequences;
197     this.groupName = groupName;
198     this.displayBoxes = displayBoxes;
199     this.displayText = displayText;
200     this.colourText = colourText;
201     this.cs = new ResidueShader(scheme);
202     startRes = start;
203     endRes = end;
204     recalcConservation();
205   }
206
207   /**
208    * copy constructor
209    * 
210    * @param seqsel
211    */
212   public SequenceGroup(SequenceGroup seqsel)
213   {
214     this();
215     if (seqsel != null)
216     {
217       sequences = new ArrayList<>();
218       sequences.addAll(seqsel.sequences);
219       if (seqsel.groupName != null)
220       {
221         groupName = new String(seqsel.groupName);
222       }
223       displayBoxes = seqsel.displayBoxes;
224       displayText = seqsel.displayText;
225       colourText = seqsel.colourText;
226       startRes = seqsel.startRes;
227       endRes = seqsel.endRes;
228       cs = new ResidueShader((ResidueShader) seqsel.cs);
229       if (seqsel.description != null)
230       {
231         description = new String(seqsel.description);
232       }
233       hidecols = seqsel.hidecols;
234       hidereps = seqsel.hidereps;
235       showNonconserved = seqsel.showNonconserved;
236       showSequenceLogo = seqsel.showSequenceLogo;
237       normaliseSequenceLogo = seqsel.normaliseSequenceLogo;
238       showConsensusHistogram = seqsel.showConsensusHistogram;
239       showHMMSequenceLogo = seqsel.showHMMSequenceLogo;
240       normaliseHMMSequenceLogo = seqsel.normaliseHMMSequenceLogo;
241       showInformationHistogram = seqsel.showInformationHistogram;
242       idColour = seqsel.idColour;
243       outlineColour = seqsel.outlineColour;
244       seqrep = seqsel.seqrep;
245       textColour = seqsel.textColour;
246       textColour2 = seqsel.textColour2;
247       thresholdTextColour = seqsel.thresholdTextColour;
248       width = seqsel.width;
249       ignoreGapsInConsensus = seqsel.ignoreGapsInConsensus;
250       ignoreBelowBackground = seqsel.ignoreBelowBackground;
251       infoLetterHeight = seqsel.infoLetterHeight;
252       if (seqsel.conserve != null)
253       {
254         recalcConservation(); // safer than
255         // aaFrequency = (Vector) seqsel.aaFrequency.clone(); // ??
256       }
257     }
258   }
259
260   public boolean isShowSequenceLogo()
261   {
262     return showSequenceLogo;
263   }
264
265   public SequenceI[] getSelectionAsNewSequences(AlignmentI align)
266   {
267     int iSize = sequences.size();
268     SequenceI[] seqs = new SequenceI[iSize];
269     SequenceI[] inorder = getSequencesInOrder(align);
270
271     for (int i = 0, ipos = 0; i < inorder.length; i++)
272     {
273       SequenceI seq = inorder[i];
274
275       seqs[ipos] = seq.getSubSequence(startRes, endRes + 1);
276       if (seqs[ipos] != null)
277       {
278         seqs[ipos].setDescription(seq.getDescription());
279         seqs[ipos].setDBRefs(seq.getDBRefs());
280         seqs[ipos].setSequenceFeatures(seq.getSequenceFeatures());
281         if (seq.getDatasetSequence() != null)
282         {
283           seqs[ipos].setDatasetSequence(seq.getDatasetSequence());
284         }
285
286         if (seq.getAnnotation() != null)
287         {
288           AlignmentAnnotation[] alann = align.getAlignmentAnnotation();
289           // Only copy annotation that is either a score or referenced by the
290           // alignment's annotation vector
291           for (int a = 0; a < seq.getAnnotation().length; a++)
292           {
293             AlignmentAnnotation tocopy = seq.getAnnotation()[a];
294             if (alann != null)
295             {
296               boolean found = false;
297               for (int pos = 0; pos < alann.length; pos++)
298               {
299                 if (alann[pos] == tocopy)
300                 {
301                   found = true;
302                   break;
303                 }
304               }
305               if (!found)
306               {
307                 continue;
308               }
309             }
310             AlignmentAnnotation newannot = new AlignmentAnnotation(
311                     seq.getAnnotation()[a]);
312             newannot.restrict(startRes, endRes);
313             newannot.setSequenceRef(seqs[ipos]);
314             newannot.adjustForAlignment();
315             seqs[ipos].addAlignmentAnnotation(newannot);
316           }
317         }
318         ipos++;
319       }
320       else
321       {
322         iSize--;
323       }
324     }
325     if (iSize != inorder.length)
326     {
327       SequenceI[] nseqs = new SequenceI[iSize];
328       System.arraycopy(seqs, 0, nseqs, 0, iSize);
329       seqs = nseqs;
330     }
331     return seqs;
332
333   }
334
335   /**
336    * If sequence ends in gaps, the end residue can be correctly calculated here
337    * 
338    * @param seq
339    *          SequenceI
340    * @return int
341    */
342   public int findEndRes(SequenceI seq)
343   {
344     int eres = 0;
345     char ch;
346
347     for (int j = 0; j < endRes + 1 && j < seq.getLength(); j++)
348     {
349       ch = seq.getCharAt(j);
350       if (!jalview.util.Comparison.isGap((ch)))
351       {
352         eres++;
353       }
354     }
355
356     if (eres > 0)
357     {
358       eres += seq.getStart() - 1;
359     }
360
361     return eres;
362   }
363
364   @Override
365   public List<SequenceI> getSequences()
366   {
367     return sequences;
368   }
369
370   @Override
371   public List<SequenceI> getSequences(
372           Map<SequenceI, SequenceCollectionI> hiddenReps)
373   {
374     if (hiddenReps == null)
375     {
376       // TODO: need a synchronizedCollection here ?
377       return sequences;
378     }
379     else
380     {
381       List<SequenceI> allSequences = new ArrayList<>();
382       for (SequenceI seq : sequences)
383       {
384         allSequences.add(seq);
385         if (hiddenReps.containsKey(seq))
386         {
387           SequenceCollectionI hsg = hiddenReps.get(seq);
388           for (SequenceI seq2 : hsg.getSequences())
389           {
390             if (seq2 != seq && !allSequences.contains(seq2))
391             {
392               allSequences.add(seq2);
393             }
394           }
395         }
396       }
397
398       return allSequences;
399     }
400   }
401
402   public SequenceI[] getSequencesAsArray(
403           Map<SequenceI, SequenceCollectionI> map)
404   {
405     List<SequenceI> tmp = getSequences(map);
406     if (tmp == null)
407     {
408       return null;
409     }
410     return tmp.toArray(new SequenceI[tmp.size()]);
411   }
412
413   /**
414    * DOCUMENT ME!
415    * 
416    * @param col
417    *          DOCUMENT ME!
418    * 
419    * @return DOCUMENT ME!
420    */
421   public boolean adjustForRemoveLeft(int col)
422   {
423     // return value is true if the group still exists
424     if (startRes >= col)
425     {
426       startRes = startRes - col;
427     }
428
429     if (endRes >= col)
430     {
431       endRes = endRes - col;
432
433       if (startRes > endRes)
434       {
435         startRes = 0;
436       }
437     }
438     else
439     {
440       // must delete this group!!
441       return false;
442     }
443
444     return true;
445   }
446
447   /**
448    * DOCUMENT ME!
449    * 
450    * @param col
451    *          DOCUMENT ME!
452    * 
453    * @return DOCUMENT ME!
454    */
455   public boolean adjustForRemoveRight(int col)
456   {
457     if (startRes > col)
458     {
459       // delete this group
460       return false;
461     }
462
463     if (endRes >= col)
464     {
465       endRes = col;
466     }
467
468     return true;
469   }
470
471   /**
472    * DOCUMENT ME!
473    * 
474    * @return DOCUMENT ME!
475    */
476   public String getName()
477   {
478     return groupName;
479   }
480
481   public String getDescription()
482   {
483     return description;
484   }
485
486   /**
487    * DOCUMENT ME!
488    * 
489    * @param name
490    *          DOCUMENT ME!
491    */
492   public void setName(String name)
493   {
494     groupName = name;
495     // TODO: URGENT: update dependent objects (annotation row)
496   }
497
498   public void setDescription(String desc)
499   {
500     description = desc;
501   }
502
503   /**
504    * DOCUMENT ME!
505    * 
506    * @return DOCUMENT ME!
507    */
508   public Conservation getConservation()
509   {
510     return conserve;
511   }
512
513   /**
514    * DOCUMENT ME!
515    * 
516    * @param c
517    *          DOCUMENT ME!
518    */
519   public void setConservation(Conservation c)
520   {
521     conserve = c;
522   }
523
524   /**
525    * Add s to this sequence group. If aligment sequence is already contained in
526    * group, it will not be added again, but recalculation may happen if the flag
527    * is set.
528    * 
529    * @param s
530    *          alignment sequence to be added
531    * @param recalc
532    *          true means Group's conservation should be recalculated
533    */
534   public void addSequence(SequenceI s, boolean recalc)
535   {
536     synchronized (sequences)
537     {
538       if (s != null && !sequences.contains(s))
539       {
540         sequences.add(s);
541         changeSupport.firePropertyChange(SEQ_GROUP_CHANGED,
542                 sequences.size() - 1, sequences.size());
543       }
544
545       if (recalc)
546       {
547         recalcConservation();
548       }
549     }
550   }
551
552   /**
553    * Max Gaps Threshold (percent) for performing a conservation calculation
554    */
555   private int consPercGaps = 25;
556
557   /**
558    * @return Max Gaps Threshold for performing a conservation calculation
559    */
560   public int getConsPercGaps()
561   {
562     return consPercGaps;
563   }
564
565   /**
566    * set Max Gaps Threshold (percent) for performing a conservation calculation
567    * 
568    * @param consPercGaps
569    */
570   public void setConsPercGaps(int consPercGaps)
571   {
572     this.consPercGaps = consPercGaps;
573   }
574
575   /**
576    * calculate residue conservation and colourschemes for group - but only if
577    * necessary. returns true if the calculation resulted in a visible change to
578    * group
579    */
580   public boolean recalcConservation()
581   {
582     return recalcConservation(false);
583   }
584
585   /**
586    * calculate residue conservation for group - but only if necessary. returns
587    * true if the calculation resulted in a visible change to group
588    * 
589    * @param defer
590    *          when set, colourschemes for this group are not refreshed after
591    *          recalculation
592    */
593   public boolean recalcConservation(boolean defer)
594   {
595     if (cs == null && consensus == null && conservation == null
596             && information == null)
597     {
598       return false;
599     }
600     // TODO: try harder to detect changes in state in order to minimise
601     // recalculation effort
602     boolean upd = false;
603     try
604     {
605       ProfilesI cnsns = AAFrequency.calculate(sequences, startRes,
606               endRes + 1, showSequenceLogo);
607       if (information != null)
608       {
609         HiddenMarkovModel hmm = information.sequenceRef.getHMM();
610
611         ProfilesI info = AAFrequency.calculateHMMProfiles(hmm,
612                 (endRes + 1) - startRes, startRes, endRes + 1,
613                 showHMMSequenceLogo, ignoreBelowBackground,
614                 infoLetterHeight);
615         _updateInformationRow(info, sequences.size());
616         upd = true;
617       }
618       if (consensus != null)
619       {
620         _updateConsensusRow(cnsns, sequences.size());
621         upd = true;
622       }
623       if (cs != null)
624       {
625         cs.setConsensus(cnsns);
626         upd = true;
627       }
628
629       if ((conservation != null)
630               || (cs != null && cs.conservationApplied()))
631       {
632         Conservation c = new Conservation(groupName, sequences, startRes,
633                 endRes + 1);
634         c.calculate();
635         c.verdict(false, consPercGaps);
636         if (conservation != null)
637         {
638           _updateConservationRow(c);
639         }
640         if (cs != null)
641         {
642           if (cs.conservationApplied())
643           {
644             cs.setConservation(c);
645           }
646         }
647         // eager update - will cause a refresh of overview regardless
648         upd = true;
649       }
650       if (cs != null && !defer)
651       {
652         // TODO: JAL-2034 should cs.alignmentChanged modify return state
653         cs.alignmentChanged(context != null ? context : this, null);
654         return true;
655       }
656       else
657       {
658         return upd;
659       }
660     } catch (java.lang.OutOfMemoryError err)
661     {
662       // TODO: catch OOM
663       System.out.println("Out of memory loading groups: " + err);
664     }
665     return upd;
666   }
667
668   private void _updateConservationRow(Conservation c)
669   {
670     if (conservation == null)
671     {
672       getConservation();
673     }
674     // update Labels
675     conservation.label = "Conservation for " + getName();
676     conservation.description = "Conservation for group " + getName()
677             + " less than " + consPercGaps + "% gaps";
678     // preserve width if already set
679     int aWidth = (conservation.annotations != null)
680             ? (endRes < conservation.annotations.length
681                     ? conservation.annotations.length
682                     : endRes + 1)
683             : endRes + 1;
684     conservation.annotations = null;
685     conservation.annotations = new Annotation[aWidth]; // should be alignment
686                                                        // width
687     c.completeAnnotations(conservation, null, startRes, endRes + 1);
688   }
689
690   public ProfilesI consensusData = null;
691
692   public ProfilesI informationData = null;
693
694   private void _updateConsensusRow(ProfilesI cnsns, long nseq)
695   {
696     if (consensus == null)
697     {
698       getConsensus();
699     }
700     consensus.label = "Consensus for " + getName();
701     consensus.description = "Percent Identity";
702     consensusData = cnsns;
703     // preserve width if already set
704     int aWidth = (consensus.annotations != null)
705             ? (endRes < consensus.annotations.length
706                     ? consensus.annotations.length
707                     : endRes + 1)
708             : endRes + 1;
709     consensus.annotations = null;
710     consensus.annotations = new Annotation[aWidth]; // should be alignment width
711
712     AAFrequency.completeConsensus(consensus, cnsns, startRes, endRes + 1,
713             ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO: setting
714                                                             // container
715     // for
716     // ignoreGapsInConsensusCalculation);
717   }
718
719   /**
720    * Recalculates the information content on the HMM annotation.
721    * 
722    * @param cnsns
723    * @param nseq
724    */
725   private void _updateInformationRow(ProfilesI cnsns, long nseq)
726   {
727     if (information == null)
728     {
729       getInformation();
730     }
731     information.description = MessageManager
732             .getString("label.information_description");
733     informationData = cnsns;
734     // preserve width if already set
735     int aWidth = (information.annotations != null)
736             ? (endRes < information.annotations.length
737                     ? information.annotations.length : endRes + 1)
738             : endRes + 1;
739     information.annotations = null;
740     information.annotations = new Annotation[aWidth]; // should be alignment
741                                                       // width
742     information.setCalcId(InformationThread.HMM_CALC_ID);
743     AAFrequency.completeInformation(information, cnsns, startRes,
744             endRes + 1, nseq, 0f);
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    * Answers the Hidden Markov Model annotation for this group (creating it if
1202    * necessary)
1203    * 
1204    * @return
1205    */
1206   public AlignmentAnnotation getInformation()
1207   {
1208     if (information == null)
1209     {
1210       information = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1211               6.25f, AlignmentAnnotation.BAR_GRAPH);
1212       information.hasText = true;
1213       information.autoCalculated = false;
1214       information.groupRef = this;
1215       information.label = getName();
1216       information.description = MessageManager
1217               .getString("label.information_description");
1218       information.setCalcId(InformationThread.HMM_CALC_ID);
1219     }
1220     return information;
1221   }
1222
1223   /**
1224    * set this alignmentAnnotation object as the one used to render consensus
1225    * annotation
1226    * 
1227    * @param aan
1228    */
1229   public void setConservationRow(AlignmentAnnotation aan)
1230   {
1231     if (conservation == null)
1232     {
1233       conservation = aan;
1234     }
1235   }
1236
1237   /**
1238    * get the conservation annotation row for this group
1239    * 
1240    * @return autoCalculated annotation row
1241    */
1242   public AlignmentAnnotation getConservationRow()
1243   {
1244     if (conservation == null)
1245     {
1246       conservation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1247               11f, AlignmentAnnotation.BAR_GRAPH);
1248     }
1249
1250     conservation.hasText = true;
1251     conservation.autoCalculated = true;
1252     conservation.groupRef = this;
1253     conservation.label = "Conservation for " + getName();
1254     conservation.description = "Conservation for group " + getName()
1255             + " less than " + consPercGaps + "% gaps";
1256     return conservation;
1257   }
1258
1259   /**
1260    * 
1261    * @return true if annotation rows have been instantiated for this group
1262    */
1263   public boolean hasAnnotationRows()
1264   {
1265     return consensus != null || conservation != null;
1266   }
1267
1268   public SequenceI getConsensusSeq()
1269   {
1270     getConsensus();
1271     StringBuffer seqs = new StringBuffer();
1272     for (int i = 0; i < consensus.annotations.length; i++)
1273     {
1274       if (consensus.annotations[i] != null)
1275       {
1276         if (consensus.annotations[i].description.charAt(0) == '[')
1277         {
1278           seqs.append(consensus.annotations[i].description.charAt(1));
1279         }
1280         else
1281         {
1282           seqs.append(consensus.annotations[i].displayCharacter);
1283         }
1284       }
1285     }
1286
1287     SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1288             seqs.toString());
1289     sq.setDescription("Percentage Identity Consensus "
1290             + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1291     return sq;
1292   }
1293
1294   public void setIgnoreGapsConsensus(boolean state)
1295   {
1296     if (this.ignoreGapsInConsensus != state && consensus != null)
1297     {
1298       ignoreGapsInConsensus = state;
1299       recalcConservation();
1300     }
1301     ignoreGapsInConsensus = state;
1302   }
1303
1304   public boolean getIgnoreGapsConsensus()
1305   {
1306     return ignoreGapsInConsensus;
1307   }
1308
1309   public void setIgnoreBelowBackground(boolean state)
1310   {
1311     if (this.ignoreBelowBackground != state)
1312     {
1313       ignoreBelowBackground = state;
1314     }
1315     ignoreBelowBackground = state;
1316   }
1317
1318   public boolean getIgnoreBelowBackground()
1319   {
1320     return ignoreBelowBackground;
1321   }
1322
1323   public void setInfoLetterHeight(boolean state)
1324   {
1325     if (this.infoLetterHeight != state)
1326     {
1327       infoLetterHeight = state;
1328     }
1329     infoLetterHeight = state;
1330   }
1331
1332   public boolean getInfoLetterHeight()
1333   {
1334     return infoLetterHeight;
1335   }
1336
1337   /**
1338    * @param showSequenceLogo
1339    *          indicates if a sequence logo is shown for consensus annotation
1340    */
1341   public void setshowSequenceLogo(boolean showSequenceLogo)
1342   {
1343     // TODO: decouple calculation from settings update
1344     if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1345     {
1346       this.showSequenceLogo = showSequenceLogo;
1347       recalcConservation();
1348     }
1349     this.showSequenceLogo = showSequenceLogo;
1350   }
1351
1352   /**
1353    * 
1354    * @param showConsHist
1355    *          flag indicating if the consensus histogram for this group should
1356    *          be rendered
1357    */
1358   public void setShowConsensusHistogram(boolean showConsHist)
1359   {
1360
1361     if (showConsensusHistogram != showConsHist && consensus != null)
1362     {
1363       this.showConsensusHistogram = showConsHist;
1364       recalcConservation();
1365     }
1366     this.showConsensusHistogram = showConsHist;
1367   }
1368
1369   /**
1370    * @return the showConsensusHistogram
1371    */
1372   public boolean isShowConsensusHistogram()
1373   {
1374     return showConsensusHistogram;
1375   }
1376
1377   /**
1378    * set flag indicating if logo should be normalised when rendered
1379    * 
1380    * @param norm
1381    */
1382   public void setNormaliseSequenceLogo(boolean norm)
1383   {
1384     normaliseSequenceLogo = norm;
1385   }
1386
1387   public boolean isNormaliseSequenceLogo()
1388   {
1389     return normaliseSequenceLogo;
1390   }
1391
1392   @Override
1393   /**
1394    * returns a new array with all annotation involving this group
1395    */
1396   public AlignmentAnnotation[] getAlignmentAnnotation()
1397   {
1398     // TODO add in other methods like 'getAlignmentAnnotation(String label),
1399     // etc'
1400     ArrayList<AlignmentAnnotation> annot = new ArrayList<>();
1401     synchronized (sequences)
1402     {
1403       for (SequenceI seq : sequences)
1404       {
1405         AlignmentAnnotation[] aa = seq.getAnnotation();
1406         if (aa != null)
1407         {
1408           for (AlignmentAnnotation al : aa)
1409           {
1410             if (al.groupRef == this)
1411             {
1412               annot.add(al);
1413             }
1414           }
1415         }
1416       }
1417       if (consensus != null)
1418       {
1419         annot.add(consensus);
1420       }
1421       if (conservation != null)
1422       {
1423         annot.add(conservation);
1424       }
1425     }
1426     return annot.toArray(new AlignmentAnnotation[0]);
1427   }
1428
1429   @Override
1430   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1431   {
1432     return AlignmentAnnotation.findAnnotation(
1433             Arrays.asList(getAlignmentAnnotation()), calcId);
1434   }
1435
1436   @Override
1437   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1438           String calcId, String label)
1439   {
1440     return AlignmentAnnotation.findAnnotations(
1441             Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1442   }
1443
1444   /**
1445    * Answer true if any annotation matches the calcId passed in (if not null).
1446    * 
1447    * @param calcId
1448    * @return
1449    */
1450   public boolean hasAnnotation(String calcId)
1451   {
1452     return AlignmentAnnotation
1453             .hasAnnotation(Arrays.asList(getAlignmentAnnotation()), calcId);
1454   }
1455
1456   /**
1457    * Remove all sequences from the group (leaving other properties unchanged).
1458    */
1459   public void clear()
1460   {
1461     synchronized (sequences)
1462     {
1463       int before = sequences.size();
1464       sequences.clear();
1465       changeSupport.firePropertyChange(SEQ_GROUP_CHANGED, before,
1466               sequences.size());
1467     }
1468   }
1469
1470   /**
1471    * Sets the alignment or group context for this group, and whether it is
1472    * defined as a group
1473    * 
1474    * @param ctx
1475    *          the context for the group
1476    * @param defined
1477    *          whether the group is defined on the alignment or is just a
1478    *          selection
1479    * @throws IllegalArgumentException
1480    *           if setting the context would result in a circular reference chain
1481    */
1482   public void setContext(AnnotatedCollectionI ctx, boolean defined)
1483   {
1484     setContext(ctx);
1485     this.isDefined = defined;
1486   }
1487
1488   /**
1489    * Sets the alignment or group context for this group
1490    * 
1491    * @param ctx
1492    *          the context for the group
1493    * @throws IllegalArgumentException
1494    *           if setting the context would result in a circular reference chain
1495    */
1496   public void setContext(AnnotatedCollectionI ctx)
1497   {
1498     AnnotatedCollectionI ref = ctx;
1499     while (ref != null)
1500     {
1501       if (ref == this || ref.getContext() == ctx)
1502       {
1503         throw new IllegalArgumentException(
1504                 "Circular reference in SequenceGroup.context");
1505       }
1506       ref = ref.getContext();
1507     }
1508     this.context = ctx;
1509   }
1510
1511   /*
1512    * (non-Javadoc)
1513    * 
1514    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1515    */
1516   @Override
1517   public AnnotatedCollectionI getContext()
1518   {
1519     return context;
1520   }
1521
1522   public boolean isDefined()
1523   {
1524     return isDefined;
1525   }
1526
1527   public void setColourScheme(ColourSchemeI scheme)
1528   {
1529     if (cs == null)
1530     {
1531       cs = new ResidueShader();
1532     }
1533     cs.setColourScheme(scheme);
1534   }
1535
1536   public void setGroupColourScheme(ResidueShaderI scheme)
1537   {
1538     cs = scheme;
1539   }
1540
1541   public ColourSchemeI getColourScheme()
1542   {
1543     return cs == null ? null : cs.getColourScheme();
1544   }
1545
1546   public ResidueShaderI getGroupColourScheme()
1547   {
1548     return cs;
1549   }
1550
1551   @Override
1552   public boolean isNucleotide()
1553   {
1554     if (context != null)
1555     {
1556       return context.isNucleotide();
1557     }
1558     return false;
1559   }
1560
1561   /**
1562    * @param seq
1563    * @return true if seq is a member of the group
1564    */
1565
1566   public boolean contains(SequenceI seq1)
1567   {
1568     return sequences.contains(seq1);
1569   }
1570
1571   /**
1572    * @param seq
1573    * @param apos
1574    * @return true if startRes<=apos and endRes>=apos and seq is in the group
1575    */
1576   public boolean contains(SequenceI seq, int apos)
1577   {
1578     return (startRes <= apos && endRes >= apos) && sequences.contains(seq);
1579   }
1580
1581   public boolean isShowInformationHistogram()
1582   {
1583     return showInformationHistogram;
1584   }
1585
1586   public void setShowInformationHistogram(boolean state)
1587   {
1588     if (showInformationHistogram != state && information != null)
1589     {
1590       this.showInformationHistogram = state;
1591       // recalcConservation(); TODO don't know what to do here next
1592     }
1593     this.showInformationHistogram = state;
1594
1595   }
1596
1597   public boolean isShowHMMSequenceLogo()
1598   {
1599     return showHMMSequenceLogo;
1600   }
1601
1602   public void setshowHMMSequenceLogo(boolean state)
1603   {
1604     showHMMSequenceLogo = state;
1605
1606   }
1607
1608   public boolean isNormaliseHMMSequenceLogo()
1609   {
1610     return normaliseHMMSequenceLogo;
1611   }
1612
1613   public void setNormaliseHMMSequenceLogo(boolean state)
1614   {
1615     normaliseSequenceLogo = state;
1616   }
1617
1618   /**
1619    * Returns all HMM consensus sequences. This will not return real sequences
1620    * with HMMs.
1621    */
1622   @Override
1623   public List<SequenceI> getHMMConsensusSequences()
1624   {
1625     List<SequenceI> seqs = new ArrayList<>();
1626
1627     for (int position = 0; position < sequences.size(); position++)
1628     {
1629       SequenceI seq = sequences.get(position);
1630       if (seq.isHMMConsensusSequence())
1631       {
1632         seqs.add(seq);
1633       }
1634     }
1635     return seqs;
1636   }
1637
1638 }