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