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