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