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