2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.datamodel;
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;
29 import java.awt.Color;
30 import java.util.ArrayList;
31 import java.util.List;
35 * Collects a set contiguous ranges on a set of sequences
40 public class SequenceGroup implements AnnotatedCollectionI
46 Conservation conserve;
48 boolean displayBoxes = true;
50 boolean displayText = true;
52 boolean colourText = false;
55 * True if the group is defined as a group on the alignment, false if it is
58 boolean isDefined = false;
61 * after Olivier's non-conserved only character display
63 boolean showNonconserved = false;
68 private List<SequenceI> sequences = new ArrayList<>();
71 * representative sequence for this group (if any)
73 private SequenceI seqrep = null;
78 * Colourscheme applied to group if any
80 public ResidueShaderI cs;
82 // start column (base 0)
85 // end column (base 0)
88 public Color outlineColour = Color.black;
90 public Color idColour = null;
92 public int thresholdTextColour = 0;
94 public Color textColour = Color.black;
96 public Color textColour2 = Color.white;
99 * consensus calculation property
101 private boolean ignoreGapsInConsensus = true;
104 * consensus calculation property
106 private boolean showSequenceLogo = false;
109 * flag indicating if logo should be rendered normalised
111 private boolean normaliseSequenceLogo;
114 * visibility of rows or represented rows covered by group
116 private boolean hidereps = false;
119 * visibility of columns intersecting this group
121 private boolean hidecols = false;
123 AlignmentAnnotation consensus = null;
125 AlignmentAnnotation conservation = null;
127 private boolean showConsensusHistogram;
129 private AnnotatedCollectionI context;
132 * Creates a new SequenceGroup object.
134 public SequenceGroup()
136 groupName = "JGroup:" + this.hashCode();
137 cs = new ResidueShader();
141 * Creates a new SequenceGroup object.
146 * @param displayBoxes
150 * first column of group
152 * last column of group
154 public SequenceGroup(List<SequenceI> sequences, String groupName,
155 ColourSchemeI scheme, boolean displayBoxes, boolean displayText,
156 boolean colourText, int start, int end)
159 this.sequences = sequences;
160 this.groupName = groupName;
161 this.displayBoxes = displayBoxes;
162 this.displayText = displayText;
163 this.colourText = colourText;
164 this.cs = new ResidueShader(scheme);
167 recalcConservation();
175 public SequenceGroup(SequenceGroup seqsel)
180 sequences = new ArrayList<>();
181 sequences.addAll(seqsel.sequences);
182 if (seqsel.groupName != null)
184 groupName = new String(seqsel.groupName);
186 displayBoxes = seqsel.displayBoxes;
187 displayText = seqsel.displayText;
188 colourText = seqsel.colourText;
189 startRes = seqsel.startRes;
190 endRes = seqsel.endRes;
191 cs = new ResidueShader(seqsel.getColourScheme());
192 if (seqsel.description != null)
194 description = new String(seqsel.description);
196 hidecols = seqsel.hidecols;
197 hidereps = seqsel.hidereps;
198 showNonconserved = seqsel.showNonconserved;
199 showSequenceLogo = seqsel.showSequenceLogo;
200 normaliseSequenceLogo = seqsel.normaliseSequenceLogo;
201 showConsensusHistogram = seqsel.showConsensusHistogram;
202 idColour = seqsel.idColour;
203 outlineColour = seqsel.outlineColour;
204 seqrep = seqsel.seqrep;
205 textColour = seqsel.textColour;
206 textColour2 = seqsel.textColour2;
207 thresholdTextColour = seqsel.thresholdTextColour;
208 width = seqsel.width;
209 ignoreGapsInConsensus = seqsel.ignoreGapsInConsensus;
210 if (seqsel.conserve != null)
212 recalcConservation(); // safer than
213 // aaFrequency = (Vector) seqsel.aaFrequency.clone(); // ??
218 public boolean isShowSequenceLogo()
220 return showSequenceLogo;
223 public SequenceI[] getSelectionAsNewSequences(AlignmentI align)
225 int iSize = sequences.size();
226 SequenceI[] seqs = new SequenceI[iSize];
227 SequenceI[] inorder = getSequencesInOrder(align);
229 for (int i = 0, ipos = 0; i < inorder.length; i++)
231 SequenceI seq = inorder[i];
233 seqs[ipos] = seq.getSubSequence(startRes, endRes + 1);
234 if (seqs[ipos] != null)
236 seqs[ipos].setDescription(seq.getDescription());
237 seqs[ipos].setDBRefs(seq.getDBRefs());
238 seqs[ipos].setSequenceFeatures(seq.getSequenceFeatures());
239 if (seq.getDatasetSequence() != null)
241 seqs[ipos].setDatasetSequence(seq.getDatasetSequence());
244 if (seq.getAnnotation() != null)
246 AlignmentAnnotation[] alann = align.getAlignmentAnnotation();
247 // Only copy annotation that is either a score or referenced by the
248 // alignment's annotation vector
249 for (int a = 0; a < seq.getAnnotation().length; a++)
251 AlignmentAnnotation tocopy = seq.getAnnotation()[a];
254 boolean found = false;
255 for (int pos = 0; pos < alann.length; pos++)
257 if (alann[pos] == tocopy)
268 AlignmentAnnotation newannot = new AlignmentAnnotation(
269 seq.getAnnotation()[a]);
270 newannot.restrict(startRes, endRes);
271 newannot.setSequenceRef(seqs[ipos]);
272 newannot.adjustForAlignment();
273 seqs[ipos].addAlignmentAnnotation(newannot);
283 if (iSize != inorder.length)
285 SequenceI[] nseqs = new SequenceI[iSize];
286 System.arraycopy(seqs, 0, nseqs, 0, iSize);
294 * If sequence ends in gaps, the end residue can be correctly calculated here
300 public int findEndRes(SequenceI seq)
305 for (int j = 0; j < endRes + 1 && j < seq.getLength(); j++)
307 ch = seq.getCharAt(j);
308 if (!jalview.util.Comparison.isGap((ch)))
316 eres += seq.getStart() - 1;
323 public List<SequenceI> getSequences()
329 public List<SequenceI> getSequences(
330 Map<SequenceI, SequenceCollectionI> hiddenReps)
332 if (hiddenReps == null)
334 // TODO: need a synchronizedCollection here ?
339 List<SequenceI> allSequences = new ArrayList<>();
340 for (SequenceI seq : sequences)
342 allSequences.add(seq);
343 if (hiddenReps.containsKey(seq))
345 SequenceCollectionI hsg = hiddenReps.get(seq);
346 for (SequenceI seq2 : hsg.getSequences())
348 if (seq2 != seq && !allSequences.contains(seq2))
350 allSequences.add(seq2);
360 public SequenceI[] getSequencesAsArray(
361 Map<SequenceI, SequenceCollectionI> map)
363 List<SequenceI> tmp = getSequences(map);
368 return tmp.toArray(new SequenceI[tmp.size()]);
377 * @return DOCUMENT ME!
379 public boolean adjustForRemoveLeft(int col)
381 // return value is true if the group still exists
384 startRes = startRes - col;
389 endRes = endRes - col;
391 if (startRes > endRes)
398 // must delete this group!!
411 * @return DOCUMENT ME!
413 public boolean adjustForRemoveRight(int col)
432 * @return DOCUMENT ME!
434 public String getName()
439 public String getDescription()
450 public void setName(String name)
453 // TODO: URGENT: update dependent objects (annotation row)
456 public void setDescription(String desc)
464 * @return DOCUMENT ME!
466 public Conservation getConservation()
477 public void setConservation(Conservation c)
483 * Add s to this sequence group. If aligment sequence is already contained in
484 * group, it will not be added again, but recalculation may happen if the flag
488 * alignment sequence to be added
490 * true means Group's conservation should be recalculated
492 public void addSequence(SequenceI s, boolean recalc)
494 synchronized (sequences)
496 if (s != null && !sequences.contains(s))
503 recalcConservation();
509 * Max Gaps Threshold (percent) for performing a conservation calculation
511 private int consPercGaps = 25;
514 * @return Max Gaps Threshold for performing a conservation calculation
516 public int getConsPercGaps()
522 * set Max Gaps Threshold (percent) for performing a conservation calculation
524 * @param consPercGaps
526 public void setConsPercGaps(int consPercGaps)
528 this.consPercGaps = consPercGaps;
532 * calculate residue conservation and colourschemes for group - but only if
533 * necessary. returns true if the calculation resulted in a visible change to
536 public boolean recalcConservation()
538 return recalcConservation(false);
542 * calculate residue conservation for group - but only if necessary. returns
543 * true if the calculation resulted in a visible change to group
546 * when set, colourschemes for this group are not refreshed after
549 public boolean recalcConservation(boolean defer)
551 if (cs == null && consensus == null && conservation == null)
555 // TODO: try harder to detect changes in state in order to minimise
556 // recalculation effort
560 ProfilesI cnsns = AAFrequency.calculate(sequences, startRes,
561 endRes + 1, showSequenceLogo);
562 if (consensus != null)
564 _updateConsensusRow(cnsns, sequences.size());
569 cs.setConsensus(cnsns);
573 if ((conservation != null)
574 || (cs != null && cs.conservationApplied()))
576 Conservation c = new Conservation(groupName, sequences, startRes,
579 c.verdict(false, consPercGaps);
580 if (conservation != null)
582 _updateConservationRow(c);
586 if (cs.conservationApplied())
588 cs.setConservation(c);
591 // eager update - will cause a refresh of overview regardless
594 if (cs != null && !defer)
596 // TODO: JAL-2034 should cs.alignmentChanged modify return state
597 cs.alignmentChanged(context != null ? context : this, null);
604 } catch (java.lang.OutOfMemoryError err)
607 System.out.println("Out of memory loading groups: " + err);
612 private void _updateConservationRow(Conservation c)
614 if (conservation == null)
619 conservation.label = "Conservation for " + getName();
620 conservation.description = "Conservation for group " + getName()
621 + " less than " + consPercGaps + "% gaps";
622 // preserve width if already set
623 int aWidth = (conservation.annotations != null) ? (endRes < conservation.annotations.length ? conservation.annotations.length
626 conservation.annotations = null;
627 conservation.annotations = new Annotation[aWidth]; // should be alignment
629 c.completeAnnotations(conservation, null, startRes, endRes + 1);
632 public ProfilesI consensusData = null;
634 private void _updateConsensusRow(ProfilesI cnsns, long nseq)
636 if (consensus == null)
640 consensus.label = "Consensus for " + getName();
641 consensus.description = "Percent Identity";
642 consensusData = cnsns;
643 // preserve width if already set
644 int aWidth = (consensus.annotations != null) ? (endRes < consensus.annotations.length ? consensus.annotations.length
647 consensus.annotations = null;
648 consensus.annotations = new Annotation[aWidth]; // should be alignment width
650 AAFrequency.completeConsensus(consensus, cnsns, startRes, endRes + 1,
651 ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO: setting
654 // ignoreGapsInConsensusCalculation);
659 * sequence to either add or remove from group
661 * flag passed to delete/addSequence to indicate if group properties
662 * should be recalculated
664 public void addOrRemove(SequenceI s, boolean recalc)
666 synchronized (sequences)
668 if (sequences.contains(s))
670 deleteSequence(s, recalc);
674 addSequence(s, recalc);
685 * true means recalculate conservation
687 public void deleteSequence(SequenceI s, boolean recalc)
689 synchronized (sequences)
695 recalcConservation();
703 * @return the first column selected by this group. Runs from 0<=i<N_cols
706 public int getStartRes()
713 * @return the groups last selected column. Runs from 0<=i<N_cols
716 public int getEndRes()
722 * Set the first column selected by this group. Runs from 0<=i<N_cols
726 public void setStartRes(int i)
732 * Set the groups last selected column. Runs from 0<=i<N_cols
736 public void setEndRes(int i)
742 * @return number of sequences in group
746 return sequences.size();
751 * @return the ith sequence
753 public SequenceI getSequenceAt(int i)
755 return sequences.get(i);
762 public void setColourText(boolean state)
770 * @return DOCUMENT ME!
772 public boolean getColourText()
783 public void setDisplayText(boolean state)
791 * @return DOCUMENT ME!
793 public boolean getDisplayText()
804 public void setDisplayBoxes(boolean state)
806 displayBoxes = state;
812 * @return DOCUMENT ME!
814 public boolean getDisplayBoxes()
820 * computes the width of current set of sequences and returns it
822 * @return DOCUMENT ME!
825 public int getWidth()
827 synchronized (sequences)
829 // MC This needs to get reset when characters are inserted and deleted
830 boolean first = true;
831 for (SequenceI seq : sequences)
833 if (first || seq.getLength() > width)
835 width = seq.getLength();
849 public void setOutlineColour(Color c)
857 * @return DOCUMENT ME!
859 public Color getOutlineColour()
861 return outlineColour;
866 * returns the sequences in the group ordered by the ordering given by al.
867 * this used to return an array with null entries regardless, new behaviour is
868 * below. TODO: verify that this does not affect use in applet or application
872 * @return SequenceI[] intersection of sequences in group with al, ordered by
873 * al, or null if group does not intersect with al
875 public SequenceI[] getSequencesInOrder(AlignmentI al)
877 return getSequencesInOrder(al, true);
881 * return an array representing the intersection of the group with al,
882 * optionally returning an array the size of al.getHeight() where nulls mark
883 * the non-intersected sequences
887 * @return null or array
889 public SequenceI[] getSequencesInOrder(AlignmentI al, boolean trim)
891 synchronized (sequences)
893 int sSize = sequences.size();
894 int alHeight = al.getHeight();
896 SequenceI[] seqs = new SequenceI[(trim) ? sSize : alHeight];
899 for (int i = 0; i < alHeight && index < sSize; i++)
901 if (sequences.contains(al.getSequenceAt(i)))
903 seqs[(trim) ? index : i] = al.getSequenceAt(i);
915 if (index < seqs.length)
917 SequenceI[] dummy = seqs;
918 seqs = new SequenceI[index];
921 seqs[index] = dummy[index];
930 * @return the idColour
932 public Color getIdColour()
939 * the idColour to set
941 public void setIdColour(Color idColour)
943 this.idColour = idColour;
947 * @return the representative sequence for this group
950 public SequenceI getSeqrep()
956 * set the representative sequence for this group. Note - this affects the
957 * interpretation of the Hidereps attribute.
960 * the seqrep to set (null means no sequence representative)
963 public void setSeqrep(SequenceI seqrep)
965 this.seqrep = seqrep;
970 * @return true if group has a sequence representative
973 public boolean hasSeqrep()
975 return seqrep != null;
979 * set visibility of sequences covered by (if no sequence representative is
980 * defined) or represented by this group.
984 public void setHidereps(boolean visibility)
986 hidereps = visibility;
991 * @return true if sequences represented (or covered) by this group should be
994 public boolean isHidereps()
1000 * set intended visibility of columns covered by this group
1004 public void setHideCols(boolean visibility)
1006 hidecols = visibility;
1011 * @return true if columns covered by group should be hidden
1013 public boolean isHideCols()
1019 * create a new sequence group from the intersection of this group with an
1020 * alignment Hashtable of hidden representatives
1026 * @return new group containing sequences common to this group and alignment
1028 public SequenceGroup intersect(AlignmentI alignment,
1029 Map<SequenceI, SequenceCollectionI> map)
1031 SequenceGroup sgroup = new SequenceGroup(this);
1032 SequenceI[] insect = getSequencesInOrder(alignment);
1033 sgroup.sequences = new ArrayList<>();
1034 for (int s = 0; insect != null && s < insect.length; s++)
1036 if (map == null || map.containsKey(insect[s]))
1038 sgroup.sequences.add(insect[s]);
1045 * @return the showUnconserved
1047 public boolean getShowNonconserved()
1049 return showNonconserved;
1053 * @param showNonconserved
1054 * the showUnconserved to set
1056 public void setShowNonconserved(boolean displayNonconserved)
1058 this.showNonconserved = displayNonconserved;
1062 * set this alignmentAnnotation object as the one used to render consensus
1067 public void setConsensus(AlignmentAnnotation aan)
1069 if (consensus == null)
1077 * @return automatically calculated consensus row note: the row is a stub if a
1078 * consensus calculation has not yet been performed on the group
1080 public AlignmentAnnotation getConsensus()
1082 // TODO get or calculate and get consensus annotation row for this group
1083 int aWidth = this.getWidth();
1091 if (consensus == null)
1093 consensus = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1094 100f, AlignmentAnnotation.BAR_GRAPH);
1095 consensus.hasText = true;
1096 consensus.autoCalculated = true;
1097 consensus.groupRef = this;
1098 consensus.label = "Consensus for " + getName();
1099 consensus.description = "Percent Identity";
1105 * set this alignmentAnnotation object as the one used to render consensus
1110 public void setConservationRow(AlignmentAnnotation aan)
1112 if (conservation == null)
1119 * get the conservation annotation row for this group
1121 * @return autoCalculated annotation row
1123 public AlignmentAnnotation getConservationRow()
1125 if (conservation == null)
1127 conservation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1128 11f, AlignmentAnnotation.BAR_GRAPH);
1131 conservation.hasText = true;
1132 conservation.autoCalculated = true;
1133 conservation.groupRef = this;
1134 conservation.label = "Conservation for " + getName();
1135 conservation.description = "Conservation for group " + getName()
1136 + " less than " + consPercGaps + "% gaps";
1137 return conservation;
1142 * @return true if annotation rows have been instantiated for this group
1144 public boolean hasAnnotationRows()
1146 return consensus != null || conservation != null;
1149 public SequenceI getConsensusSeq()
1152 StringBuffer seqs = new StringBuffer();
1153 for (int i = 0; i < consensus.annotations.length; i++)
1155 if (consensus.annotations[i] != null)
1157 if (consensus.annotations[i].description.charAt(0) == '[')
1159 seqs.append(consensus.annotations[i].description.charAt(1));
1163 seqs.append(consensus.annotations[i].displayCharacter);
1168 SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1170 sq.setDescription("Percentage Identity Consensus "
1171 + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1175 public void setIgnoreGapsConsensus(boolean state)
1177 if (this.ignoreGapsInConsensus != state && consensus != null)
1179 ignoreGapsInConsensus = state;
1180 recalcConservation();
1182 ignoreGapsInConsensus = state;
1185 public boolean getIgnoreGapsConsensus()
1187 return ignoreGapsInConsensus;
1191 * @param showSequenceLogo
1192 * indicates if a sequence logo is shown for consensus annotation
1194 public void setshowSequenceLogo(boolean showSequenceLogo)
1196 // TODO: decouple calculation from settings update
1197 if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1199 this.showSequenceLogo = showSequenceLogo;
1200 recalcConservation();
1202 this.showSequenceLogo = showSequenceLogo;
1207 * @param showConsHist
1208 * flag indicating if the consensus histogram for this group should
1211 public void setShowConsensusHistogram(boolean showConsHist)
1214 if (showConsensusHistogram != showConsHist && consensus != null)
1216 this.showConsensusHistogram = showConsHist;
1217 recalcConservation();
1219 this.showConsensusHistogram = showConsHist;
1223 * @return the showConsensusHistogram
1225 public boolean isShowConsensusHistogram()
1227 return showConsensusHistogram;
1231 * set flag indicating if logo should be normalised when rendered
1235 public void setNormaliseSequenceLogo(boolean norm)
1237 normaliseSequenceLogo = norm;
1240 public boolean isNormaliseSequenceLogo()
1242 return normaliseSequenceLogo;
1247 * returns a new array with all annotation involving this group
1249 public AlignmentAnnotation[] getAlignmentAnnotation()
1251 // TODO add in other methods like 'getAlignmentAnnotation(String label),
1253 ArrayList<AlignmentAnnotation> annot = new ArrayList<>();
1254 synchronized (sequences)
1256 for (SequenceI seq : sequences)
1258 AlignmentAnnotation[] aa = seq.getAnnotation();
1261 for (AlignmentAnnotation al : aa)
1263 if (al.groupRef == this)
1270 if (consensus != null)
1272 annot.add(consensus);
1274 if (conservation != null)
1276 annot.add(conservation);
1279 return annot.toArray(new AlignmentAnnotation[0]);
1283 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1285 List<AlignmentAnnotation> aa = new ArrayList<>();
1290 for (AlignmentAnnotation a : getAlignmentAnnotation())
1292 if (calcId.equals(a.getCalcId()))
1301 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1302 String calcId, String label)
1304 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1305 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1307 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1309 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1310 && (label == null || (ann.label != null && ann.label
1320 * Answer true if any annotation matches the calcId passed in (if not null).
1325 public boolean hasAnnotation(String calcId)
1327 if (calcId != null && !"".equals(calcId))
1329 for (AlignmentAnnotation a : getAlignmentAnnotation())
1331 if (a.getCalcId() == calcId)
1341 * Remove all sequences from the group (leaving other properties unchanged).
1345 synchronized (sequences)
1352 * Sets the alignment or group context for this group, and whether it is
1353 * defined as a group
1356 * the context for the group
1358 * whether the group is defined on the alignment or is just a
1360 * @throws IllegalArgumentException
1361 * if setting the context would result in a circular reference chain
1363 public void setContext(AnnotatedCollectionI ctx, boolean defined)
1366 this.isDefined = defined;
1370 * Sets the alignment or group context for this group
1373 * the context for the group
1374 * @throws IllegalArgumentException
1375 * if setting the context would result in a circular reference chain
1377 public void setContext(AnnotatedCollectionI ctx)
1379 AnnotatedCollectionI ref = ctx;
1382 if (ref == this || ref.getContext() == ctx)
1384 throw new IllegalArgumentException(
1385 "Circular reference in SequenceGroup.context");
1387 ref = ref.getContext();
1395 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1398 public AnnotatedCollectionI getContext()
1403 public boolean isDefined()
1408 public void setColourScheme(ColourSchemeI scheme)
1412 cs = new ResidueShader();
1414 cs.setColourScheme(scheme);
1417 public void setGroupColourScheme(ResidueShaderI scheme)
1422 public ColourSchemeI getColourScheme()
1424 return cs == null ? null : cs.getColourScheme();
1427 public ResidueShaderI getGroupColourScheme()
1433 public boolean isNucleotide()
1435 if (context != null) {
1436 return context.isNucleotide();
1443 * @return true if seq is a member of the group
1446 public boolean contains(SequenceI seq1)
1448 return sequences.contains(seq1);
1454 * @return true if startRes<=apos and endRes>=apos and seq is in the group
1456 public boolean contains(SequenceI seq, int apos)
1458 return (startRes <= apos && endRes >= apos) && sequences.contains(seq);