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