JAL-2418 source formatting
[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)
624             ? (endRes < conservation.annotations.length
625                     ? conservation.annotations.length
626                     : endRes + 1)
627             : endRes + 1;
628     conservation.annotations = null;
629     conservation.annotations = new Annotation[aWidth]; // should be alignment
630                                                        // width
631     c.completeAnnotations(conservation, null, startRes, endRes + 1);
632   }
633
634   public ProfilesI consensusData = null;
635
636   private void _updateConsensusRow(ProfilesI cnsns, long nseq)
637   {
638     if (consensus == null)
639     {
640       getConsensus();
641     }
642     consensus.label = "Consensus for " + getName();
643     consensus.description = "Percent Identity";
644     consensusData = cnsns;
645     // preserve width if already set
646     int aWidth = (consensus.annotations != null)
647             ? (endRes < consensus.annotations.length
648                     ? consensus.annotations.length
649                     : endRes + 1)
650             : endRes + 1;
651     consensus.annotations = null;
652     consensus.annotations = new Annotation[aWidth]; // should be alignment width
653
654     AAFrequency.completeConsensus(consensus, cnsns, startRes, endRes + 1,
655             ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO: setting
656                                                             // container
657     // for
658     // ignoreGapsInConsensusCalculation);
659   }
660
661   /**
662    * @param s
663    *          sequence to either add or remove from group
664    * @param recalc
665    *          flag passed to delete/addSequence to indicate if group properties
666    *          should be recalculated
667    */
668   public void addOrRemove(SequenceI s, boolean recalc)
669   {
670     synchronized (sequences)
671     {
672       if (sequences.contains(s))
673       {
674         deleteSequence(s, recalc);
675       }
676       else
677       {
678         addSequence(s, recalc);
679       }
680     }
681   }
682
683   /**
684    * remove
685    * 
686    * @param s
687    *          to be removed
688    * @param recalc
689    *          true means recalculate conservation
690    */
691   public void deleteSequence(SequenceI s, boolean recalc)
692   {
693     synchronized (sequences)
694     {
695       sequences.remove(s);
696
697       if (recalc)
698       {
699         recalcConservation();
700       }
701     }
702   }
703
704   /**
705    * 
706    * 
707    * @return the first column selected by this group. Runs from 0<=i<N_cols
708    */
709   @Override
710   public int getStartRes()
711   {
712     return startRes;
713   }
714
715   /**
716    * 
717    * @return the groups last selected column. Runs from 0<=i<N_cols
718    */
719   @Override
720   public int getEndRes()
721   {
722     return endRes;
723   }
724
725   /**
726    * Set the first column selected by this group. Runs from 0<=i<N_cols
727    * 
728    * @param i
729    */
730   public void setStartRes(int i)
731   {
732     startRes = i;
733   }
734
735   /**
736    * Set the groups last selected column. Runs from 0<=i<N_cols
737    * 
738    * @param i
739    */
740   public void setEndRes(int i)
741   {
742     endRes = i;
743   }
744
745   /**
746    * @return number of sequences in group
747    */
748   public int getSize()
749   {
750     return sequences.size();
751   }
752
753   /**
754    * @param i
755    * @return the ith sequence
756    */
757   public SequenceI getSequenceAt(int i)
758   {
759     return sequences.get(i);
760   }
761
762   /**
763    * @param state
764    *          colourText
765    */
766   public void setColourText(boolean state)
767   {
768     colourText = state;
769   }
770
771   /**
772    * DOCUMENT ME!
773    * 
774    * @return DOCUMENT ME!
775    */
776   public boolean getColourText()
777   {
778     return colourText;
779   }
780
781   /**
782    * DOCUMENT ME!
783    * 
784    * @param state
785    *          DOCUMENT ME!
786    */
787   public void setDisplayText(boolean state)
788   {
789     displayText = state;
790   }
791
792   /**
793    * DOCUMENT ME!
794    * 
795    * @return DOCUMENT ME!
796    */
797   public boolean getDisplayText()
798   {
799     return displayText;
800   }
801
802   /**
803    * DOCUMENT ME!
804    * 
805    * @param state
806    *          DOCUMENT ME!
807    */
808   public void setDisplayBoxes(boolean state)
809   {
810     displayBoxes = state;
811   }
812
813   /**
814    * DOCUMENT ME!
815    * 
816    * @return DOCUMENT ME!
817    */
818   public boolean getDisplayBoxes()
819   {
820     return displayBoxes;
821   }
822
823   /**
824    * computes the width of current set of sequences and returns it
825    * 
826    * @return DOCUMENT ME!
827    */
828   @Override
829   public int getWidth()
830   {
831     synchronized (sequences)
832     {
833       // MC This needs to get reset when characters are inserted and deleted
834       boolean first = true;
835       for (SequenceI seq : sequences)
836       {
837         if (first || seq.getLength() > width)
838         {
839           width = seq.getLength();
840           first = false;
841         }
842       }
843       return width;
844     }
845   }
846
847   /**
848    * DOCUMENT ME!
849    * 
850    * @param c
851    *          DOCUMENT ME!
852    */
853   public void setOutlineColour(Color c)
854   {
855     outlineColour = c;
856   }
857
858   /**
859    * DOCUMENT ME!
860    * 
861    * @return DOCUMENT ME!
862    */
863   public Color getOutlineColour()
864   {
865     return outlineColour;
866   }
867
868   /**
869    * 
870    * returns the sequences in the group ordered by the ordering given by al.
871    * this used to return an array with null entries regardless, new behaviour is
872    * below. TODO: verify that this does not affect use in applet or application
873    * 
874    * @param al
875    *          Alignment
876    * @return SequenceI[] intersection of sequences in group with al, ordered by
877    *         al, or null if group does not intersect with al
878    */
879   public SequenceI[] getSequencesInOrder(AlignmentI al)
880   {
881     return getSequencesInOrder(al, true);
882   }
883
884   /**
885    * return an array representing the intersection of the group with al,
886    * optionally returning an array the size of al.getHeight() where nulls mark
887    * the non-intersected sequences
888    * 
889    * @param al
890    * @param trim
891    * @return null or array
892    */
893   public SequenceI[] getSequencesInOrder(AlignmentI al, boolean trim)
894   {
895     synchronized (sequences)
896     {
897       int sSize = sequences.size();
898       int alHeight = al.getHeight();
899
900       SequenceI[] seqs = new SequenceI[(trim) ? sSize : alHeight];
901
902       int index = 0;
903       for (int i = 0; i < alHeight && index < sSize; i++)
904       {
905         if (sequences.contains(al.getSequenceAt(i)))
906         {
907           seqs[(trim) ? index : i] = al.getSequenceAt(i);
908           index++;
909         }
910       }
911       if (index == 0)
912       {
913         return null;
914       }
915       if (!trim)
916       {
917         return seqs;
918       }
919       if (index < seqs.length)
920       {
921         SequenceI[] dummy = seqs;
922         seqs = new SequenceI[index];
923         while (--index >= 0)
924         {
925           seqs[index] = dummy[index];
926           dummy[index] = null;
927         }
928       }
929       return seqs;
930     }
931   }
932
933   /**
934    * @return the idColour
935    */
936   public Color getIdColour()
937   {
938     return idColour;
939   }
940
941   /**
942    * @param idColour
943    *          the idColour to set
944    */
945   public void setIdColour(Color idColour)
946   {
947     this.idColour = idColour;
948   }
949
950   /**
951    * @return the representative sequence for this group
952    */
953   @Override
954   public SequenceI getSeqrep()
955   {
956     return seqrep;
957   }
958
959   /**
960    * set the representative sequence for this group. Note - this affects the
961    * interpretation of the Hidereps attribute.
962    * 
963    * @param seqrep
964    *          the seqrep to set (null means no sequence representative)
965    */
966   @Override
967   public void setSeqrep(SequenceI seqrep)
968   {
969     this.seqrep = seqrep;
970   }
971
972   /**
973    * 
974    * @return true if group has a sequence representative
975    */
976   @Override
977   public boolean hasSeqrep()
978   {
979     return seqrep != null;
980   }
981
982   /**
983    * set visibility of sequences covered by (if no sequence representative is
984    * defined) or represented by this group.
985    * 
986    * @param visibility
987    */
988   public void setHidereps(boolean visibility)
989   {
990     hidereps = visibility;
991   }
992
993   /**
994    * 
995    * @return true if sequences represented (or covered) by this group should be
996    *         hidden
997    */
998   public boolean isHidereps()
999   {
1000     return hidereps;
1001   }
1002
1003   /**
1004    * set intended visibility of columns covered by this group
1005    * 
1006    * @param visibility
1007    */
1008   public void setHideCols(boolean visibility)
1009   {
1010     hidecols = visibility;
1011   }
1012
1013   /**
1014    * 
1015    * @return true if columns covered by group should be hidden
1016    */
1017   public boolean isHideCols()
1018   {
1019     return hidecols;
1020   }
1021
1022   /**
1023    * create a new sequence group from the intersection of this group with an
1024    * alignment Hashtable of hidden representatives
1025    * 
1026    * @param alignment
1027    *          (may not be null)
1028    * @param map
1029    *          (may be null)
1030    * @return new group containing sequences common to this group and alignment
1031    */
1032   public SequenceGroup intersect(AlignmentI alignment,
1033           Map<SequenceI, SequenceCollectionI> map)
1034   {
1035     SequenceGroup sgroup = new SequenceGroup(this);
1036     SequenceI[] insect = getSequencesInOrder(alignment);
1037     sgroup.sequences = new ArrayList<>();
1038     for (int s = 0; insect != null && s < insect.length; s++)
1039     {
1040       if (map == null || map.containsKey(insect[s]))
1041       {
1042         sgroup.sequences.add(insect[s]);
1043       }
1044     }
1045     return sgroup;
1046   }
1047
1048   /**
1049    * @return the showUnconserved
1050    */
1051   public boolean getShowNonconserved()
1052   {
1053     return showNonconserved;
1054   }
1055
1056   /**
1057    * @param showNonconserved
1058    *          the showUnconserved to set
1059    */
1060   public void setShowNonconserved(boolean displayNonconserved)
1061   {
1062     this.showNonconserved = displayNonconserved;
1063   }
1064
1065   /**
1066    * set this alignmentAnnotation object as the one used to render consensus
1067    * annotation
1068    * 
1069    * @param aan
1070    */
1071   public void setConsensus(AlignmentAnnotation aan)
1072   {
1073     if (consensus == null)
1074     {
1075       consensus = aan;
1076     }
1077   }
1078
1079   /**
1080    * 
1081    * @return automatically calculated consensus row note: the row is a stub if a
1082    *         consensus calculation has not yet been performed on the group
1083    */
1084   public AlignmentAnnotation getConsensus()
1085   {
1086     // TODO get or calculate and get consensus annotation row for this group
1087     int aWidth = this.getWidth();
1088     // pointer
1089     // possibility
1090     // here.
1091     if (aWidth < 0)
1092     {
1093       return null;
1094     }
1095     if (consensus == null)
1096     {
1097       consensus = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1098               100f, AlignmentAnnotation.BAR_GRAPH);
1099       consensus.hasText = true;
1100       consensus.autoCalculated = true;
1101       consensus.groupRef = this;
1102       consensus.label = "Consensus for " + getName();
1103       consensus.description = "Percent Identity";
1104     }
1105     return consensus;
1106   }
1107
1108   /**
1109    * set this alignmentAnnotation object as the one used to render consensus
1110    * annotation
1111    * 
1112    * @param aan
1113    */
1114   public void setConservationRow(AlignmentAnnotation aan)
1115   {
1116     if (conservation == null)
1117     {
1118       conservation = aan;
1119     }
1120   }
1121
1122   /**
1123    * get the conservation annotation row for this group
1124    * 
1125    * @return autoCalculated annotation row
1126    */
1127   public AlignmentAnnotation getConservationRow()
1128   {
1129     if (conservation == null)
1130     {
1131       conservation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1132               11f, AlignmentAnnotation.BAR_GRAPH);
1133     }
1134
1135     conservation.hasText = true;
1136     conservation.autoCalculated = true;
1137     conservation.groupRef = this;
1138     conservation.label = "Conservation for " + getName();
1139     conservation.description = "Conservation for group " + getName()
1140             + " less than " + consPercGaps + "% gaps";
1141     return conservation;
1142   }
1143
1144   /**
1145    * 
1146    * @return true if annotation rows have been instantiated for this group
1147    */
1148   public boolean hasAnnotationRows()
1149   {
1150     return consensus != null || conservation != null;
1151   }
1152
1153   public SequenceI getConsensusSeq()
1154   {
1155     getConsensus();
1156     StringBuffer seqs = new StringBuffer();
1157     for (int i = 0; i < consensus.annotations.length; i++)
1158     {
1159       if (consensus.annotations[i] != null)
1160       {
1161         if (consensus.annotations[i].description.charAt(0) == '[')
1162         {
1163           seqs.append(consensus.annotations[i].description.charAt(1));
1164         }
1165         else
1166         {
1167           seqs.append(consensus.annotations[i].displayCharacter);
1168         }
1169       }
1170     }
1171
1172     SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1173             seqs.toString());
1174     sq.setDescription("Percentage Identity Consensus "
1175             + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1176     return sq;
1177   }
1178
1179   public void setIgnoreGapsConsensus(boolean state)
1180   {
1181     if (this.ignoreGapsInConsensus != state && consensus != null)
1182     {
1183       ignoreGapsInConsensus = state;
1184       recalcConservation();
1185     }
1186     ignoreGapsInConsensus = state;
1187   }
1188
1189   public boolean getIgnoreGapsConsensus()
1190   {
1191     return ignoreGapsInConsensus;
1192   }
1193
1194   /**
1195    * @param showSequenceLogo
1196    *          indicates if a sequence logo is shown for consensus annotation
1197    */
1198   public void setshowSequenceLogo(boolean showSequenceLogo)
1199   {
1200     // TODO: decouple calculation from settings update
1201     if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1202     {
1203       this.showSequenceLogo = showSequenceLogo;
1204       recalcConservation();
1205     }
1206     this.showSequenceLogo = showSequenceLogo;
1207   }
1208
1209   /**
1210    * 
1211    * @param showConsHist
1212    *          flag indicating if the consensus histogram for this group should
1213    *          be rendered
1214    */
1215   public void setShowConsensusHistogram(boolean showConsHist)
1216   {
1217
1218     if (showConsensusHistogram != showConsHist && consensus != null)
1219     {
1220       this.showConsensusHistogram = showConsHist;
1221       recalcConservation();
1222     }
1223     this.showConsensusHistogram = showConsHist;
1224   }
1225
1226   /**
1227    * @return the showConsensusHistogram
1228    */
1229   public boolean isShowConsensusHistogram()
1230   {
1231     return showConsensusHistogram;
1232   }
1233
1234   /**
1235    * set flag indicating if logo should be normalised when rendered
1236    * 
1237    * @param norm
1238    */
1239   public void setNormaliseSequenceLogo(boolean norm)
1240   {
1241     normaliseSequenceLogo = norm;
1242   }
1243
1244   public boolean isNormaliseSequenceLogo()
1245   {
1246     return normaliseSequenceLogo;
1247   }
1248
1249   @Override
1250   /**
1251    * returns a new array with all annotation involving this group
1252    */
1253   public AlignmentAnnotation[] getAlignmentAnnotation()
1254   {
1255     // TODO add in other methods like 'getAlignmentAnnotation(String label),
1256     // etc'
1257     ArrayList<AlignmentAnnotation> annot = new ArrayList<>();
1258     synchronized (sequences)
1259     {
1260       for (SequenceI seq : sequences)
1261       {
1262         AlignmentAnnotation[] aa = seq.getAnnotation();
1263         if (aa != null)
1264         {
1265           for (AlignmentAnnotation al : aa)
1266           {
1267             if (al.groupRef == this)
1268             {
1269               annot.add(al);
1270             }
1271           }
1272         }
1273       }
1274       if (consensus != null)
1275       {
1276         annot.add(consensus);
1277       }
1278       if (conservation != null)
1279       {
1280         annot.add(conservation);
1281       }
1282     }
1283     return annot.toArray(new AlignmentAnnotation[0]);
1284   }
1285
1286   @Override
1287   public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1288   {
1289     List<AlignmentAnnotation> aa = new ArrayList<>();
1290     if (calcId == null)
1291     {
1292       return aa;
1293     }
1294     for (AlignmentAnnotation a : getAlignmentAnnotation())
1295     {
1296       if (calcId.equals(a.getCalcId()))
1297       {
1298         aa.add(a);
1299       }
1300     }
1301     return aa;
1302   }
1303
1304   @Override
1305   public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1306           String calcId, String label)
1307   {
1308     ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1309     for (AlignmentAnnotation ann : getAlignmentAnnotation())
1310     {
1311       if ((calcId == null || (ann.getCalcId() != null
1312               && ann.getCalcId().equals(calcId)))
1313               && (seq == null || (ann.sequenceRef != null
1314                       && ann.sequenceRef == seq))
1315               && (label == null
1316                       || (ann.label != null && ann.label.equals(label))))
1317       {
1318         aa.add(ann);
1319       }
1320     }
1321     return aa;
1322   }
1323
1324   /**
1325    * Answer true if any annotation matches the calcId passed in (if not null).
1326    * 
1327    * @param calcId
1328    * @return
1329    */
1330   public boolean hasAnnotation(String calcId)
1331   {
1332     if (calcId != null && !"".equals(calcId))
1333     {
1334       for (AlignmentAnnotation a : getAlignmentAnnotation())
1335       {
1336         if (a.getCalcId() == calcId)
1337         {
1338           return true;
1339         }
1340       }
1341     }
1342     return false;
1343   }
1344
1345   /**
1346    * Remove all sequences from the group (leaving other properties unchanged).
1347    */
1348   public void clear()
1349   {
1350     synchronized (sequences)
1351     {
1352       sequences.clear();
1353     }
1354   }
1355
1356   /**
1357    * Sets the alignment or group context for this group, and whether it is
1358    * defined as a group
1359    * 
1360    * @param ctx
1361    *          the context for the group
1362    * @param defined
1363    *          whether the group is defined on the alignment or is just a
1364    *          selection
1365    * @throws IllegalArgumentException
1366    *           if setting the context would result in a circular reference chain
1367    */
1368   public void setContext(AnnotatedCollectionI ctx, boolean defined)
1369   {
1370     setContext(ctx);
1371     this.isDefined = defined;
1372   }
1373
1374   /**
1375    * Sets the alignment or group context for this group
1376    * 
1377    * @param ctx
1378    *          the context for the group
1379    * @throws IllegalArgumentException
1380    *           if setting the context would result in a circular reference chain
1381    */
1382   public void setContext(AnnotatedCollectionI ctx)
1383   {
1384     AnnotatedCollectionI ref = ctx;
1385     while (ref != null)
1386     {
1387       if (ref == this || ref.getContext() == ctx)
1388       {
1389         throw new IllegalArgumentException(
1390                 "Circular reference in SequenceGroup.context");
1391       }
1392       ref = ref.getContext();
1393     }
1394     this.context = ctx;
1395   }
1396
1397   /*
1398    * (non-Javadoc)
1399    * 
1400    * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1401    */
1402   @Override
1403   public AnnotatedCollectionI getContext()
1404   {
1405     return context;
1406   }
1407
1408   public boolean isDefined()
1409   {
1410     return isDefined;
1411   }
1412
1413   public void setColourScheme(ColourSchemeI scheme)
1414   {
1415     if (cs == null)
1416     {
1417       cs = new ResidueShader();
1418     }
1419     cs.setColourScheme(scheme);
1420   }
1421
1422   public void setGroupColourScheme(ResidueShaderI scheme)
1423   {
1424     cs = scheme;
1425   }
1426
1427   public ColourSchemeI getColourScheme()
1428   {
1429     return cs == null ? null : cs.getColourScheme();
1430   }
1431
1432   public ResidueShaderI getGroupColourScheme()
1433   {
1434     return cs;
1435   }
1436
1437   @Override
1438   public boolean isNucleotide()
1439   {
1440     if (context != null)
1441     {
1442       return context.isNucleotide();
1443     }
1444     return false;
1445   }
1446
1447   /**
1448    * @param seq
1449    * @return true if seq is a member of the group
1450    */
1451
1452   public boolean contains(SequenceI seq1)
1453   {
1454     return sequences.contains(seq1);
1455   }
1456
1457   /**
1458    * @param seq
1459    * @param apos
1460    * @return true if startRes<=apos and endRes>=apos and seq is in the group
1461    */
1462   public boolean contains(SequenceI seq, int apos)
1463   {
1464     return (startRes <= apos && endRes >= apos) && sequences.contains(seq);
1465   }
1466 }