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