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