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