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