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