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 * @return the includeAllConsSymbols
116 public boolean isShowSequenceLogo()
118 return showSequenceLogo;
122 * Creates a new SequenceGroup object.
124 public SequenceGroup()
126 groupName = "JGroup:" + this.hashCode();
127 cs = new ResidueShader();
131 * Creates a new SequenceGroup object.
136 * @param displayBoxes
140 * first column of group
142 * last column of group
144 public SequenceGroup(List<SequenceI> sequences, String groupName,
145 ColourSchemeI scheme, boolean displayBoxes, boolean displayText,
146 boolean colourText, int start, int end)
149 this.sequences = sequences;
150 this.groupName = groupName;
151 this.displayBoxes = displayBoxes;
152 this.displayText = displayText;
153 this.colourText = colourText;
154 this.cs = new ResidueShader(scheme);
157 recalcConservation();
165 public SequenceGroup(SequenceGroup seqsel)
170 sequences = new ArrayList<>();
171 sequences.addAll(seqsel.sequences);
172 if (seqsel.groupName != null)
174 groupName = new String(seqsel.groupName);
176 displayBoxes = seqsel.displayBoxes;
177 displayText = seqsel.displayText;
178 colourText = seqsel.colourText;
179 startRes = seqsel.startRes;
180 endRes = seqsel.endRes;
182 if (seqsel.description != null)
184 description = new String(seqsel.description);
186 hidecols = seqsel.hidecols;
187 hidereps = seqsel.hidereps;
188 idColour = seqsel.idColour;
189 outlineColour = seqsel.outlineColour;
190 seqrep = seqsel.seqrep;
191 textColour = seqsel.textColour;
192 textColour2 = seqsel.textColour2;
193 thresholdTextColour = seqsel.thresholdTextColour;
194 width = seqsel.width;
195 ignoreGapsInConsensus = seqsel.ignoreGapsInConsensus;
196 if (seqsel.conserve != null)
198 recalcConservation(); // safer than
199 // aaFrequency = (Vector) seqsel.aaFrequency.clone(); // ??
204 public SequenceI[] getSelectionAsNewSequences(AlignmentI align)
206 int iSize = sequences.size();
207 SequenceI[] seqs = new SequenceI[iSize];
208 SequenceI[] inorder = getSequencesInOrder(align);
210 for (int i = 0, ipos = 0; i < inorder.length; i++)
212 SequenceI seq = inorder[i];
214 seqs[ipos] = seq.getSubSequence(startRes, endRes + 1);
215 if (seqs[ipos] != null)
217 seqs[ipos].setDescription(seq.getDescription());
218 seqs[ipos].setDBRefs(seq.getDBRefs());
219 seqs[ipos].setSequenceFeatures(seq.getSequenceFeatures());
220 if (seq.getDatasetSequence() != null)
222 seqs[ipos].setDatasetSequence(seq.getDatasetSequence());
225 if (seq.getAnnotation() != null)
227 AlignmentAnnotation[] alann = align.getAlignmentAnnotation();
228 // Only copy annotation that is either a score or referenced by the
229 // alignment's annotation vector
230 for (int a = 0; a < seq.getAnnotation().length; a++)
232 AlignmentAnnotation tocopy = seq.getAnnotation()[a];
235 boolean found = false;
236 for (int pos = 0; pos < alann.length; pos++)
238 if (alann[pos] == tocopy)
249 AlignmentAnnotation newannot = new AlignmentAnnotation(
250 seq.getAnnotation()[a]);
251 newannot.restrict(startRes, endRes);
252 newannot.setSequenceRef(seqs[ipos]);
253 newannot.adjustForAlignment();
254 seqs[ipos].addAlignmentAnnotation(newannot);
264 if (iSize != inorder.length)
266 SequenceI[] nseqs = new SequenceI[iSize];
267 System.arraycopy(seqs, 0, nseqs, 0, iSize);
275 * If sequence ends in gaps, the end residue can be correctly calculated here
281 public int findEndRes(SequenceI seq)
286 for (int j = 0; j < endRes + 1 && j < seq.getLength(); j++)
288 ch = seq.getCharAt(j);
289 if (!jalview.util.Comparison.isGap((ch)))
297 eres += seq.getStart() - 1;
304 public List<SequenceI> getSequences()
310 public List<SequenceI> getSequences(
311 Map<SequenceI, SequenceCollectionI> hiddenReps)
313 if (hiddenReps == null)
315 // TODO: need a synchronizedCollection here ?
320 List<SequenceI> allSequences = new ArrayList<>();
321 for (SequenceI seq : sequences)
323 allSequences.add(seq);
324 if (hiddenReps.containsKey(seq))
326 SequenceCollectionI hsg = hiddenReps.get(seq);
327 for (SequenceI seq2 : hsg.getSequences())
329 if (seq2 != seq && !allSequences.contains(seq2))
331 allSequences.add(seq2);
341 public SequenceI[] getSequencesAsArray(
342 Map<SequenceI, SequenceCollectionI> map)
344 List<SequenceI> tmp = getSequences(map);
349 return tmp.toArray(new SequenceI[tmp.size()]);
358 * @return DOCUMENT ME!
360 public boolean adjustForRemoveLeft(int col)
362 // return value is true if the group still exists
365 startRes = startRes - col;
370 endRes = endRes - col;
372 if (startRes > endRes)
379 // must delete this group!!
392 * @return DOCUMENT ME!
394 public boolean adjustForRemoveRight(int col)
413 * @return DOCUMENT ME!
415 public String getName()
420 public String getDescription()
431 public void setName(String name)
434 // TODO: URGENT: update dependent objects (annotation row)
437 public void setDescription(String desc)
445 * @return DOCUMENT ME!
447 public Conservation getConservation()
458 public void setConservation(Conservation c)
464 * Add s to this sequence group. If aligment sequence is already contained in
465 * group, it will not be added again, but recalculation may happen if the flag
469 * alignment sequence to be added
471 * true means Group's conservation should be recalculated
473 public void addSequence(SequenceI s, boolean recalc)
475 synchronized (sequences)
477 if (s != null && !sequences.contains(s))
484 recalcConservation();
490 * Max Gaps Threshold (percent) for performing a conservation calculation
492 private int consPercGaps = 25;
495 * @return Max Gaps Threshold for performing a conservation calculation
497 public int getConsPercGaps()
503 * set Max Gaps Threshold (percent) for performing a conservation calculation
505 * @param consPercGaps
507 public void setConsPercGaps(int consPercGaps)
509 this.consPercGaps = consPercGaps;
513 * calculate residue conservation and colourschemes for group - but only if
514 * necessary. returns true if the calculation resulted in a visible change to
517 public boolean recalcConservation()
519 return recalcConservation(false);
523 * calculate residue conservation for group - but only if necessary. returns
524 * true if the calculation resulted in a visible change to group
527 * when set, colourschemes for this group are not refreshed after
530 public boolean recalcConservation(boolean defer)
532 if (cs == null && consensus == null && conservation == null)
536 // TODO: try harder to detect changes in state in order to minimise
537 // recalculation effort
541 ProfilesI cnsns = AAFrequency.calculate(sequences, startRes,
542 endRes + 1, showSequenceLogo);
543 if (consensus != null)
545 _updateConsensusRow(cnsns, sequences.size());
550 cs.setConsensus(cnsns);
554 if ((conservation != null)
555 || (cs != null && cs.conservationApplied()))
557 Conservation c = new Conservation(groupName, sequences, startRes,
560 c.verdict(false, consPercGaps);
561 if (conservation != null)
563 _updateConservationRow(c);
567 if (cs.conservationApplied())
569 cs.setConservation(c);
572 // eager update - will cause a refresh of overview regardless
575 if (cs != null && !defer)
577 // TODO: JAL-2034 should cs.alignmentChanged modify return state
578 cs.alignmentChanged(context != null ? context : this, null);
585 } catch (java.lang.OutOfMemoryError err)
588 System.out.println("Out of memory loading groups: " + err);
593 private void _updateConservationRow(Conservation c)
595 if (conservation == null)
600 conservation.label = "Conservation for " + getName();
601 conservation.description = "Conservation for group " + getName()
602 + " less than " + consPercGaps + "% gaps";
603 // preserve width if already set
604 int aWidth = (conservation.annotations != null) ? (endRes < conservation.annotations.length ? conservation.annotations.length
607 conservation.annotations = null;
608 conservation.annotations = new Annotation[aWidth]; // should be alignment
610 c.completeAnnotations(conservation, null, startRes, endRes + 1);
613 public ProfilesI consensusData = null;
615 private void _updateConsensusRow(ProfilesI cnsns, long nseq)
617 if (consensus == null)
621 consensus.label = "Consensus for " + getName();
622 consensus.description = "Percent Identity";
623 consensusData = cnsns;
624 // preserve width if already set
625 int aWidth = (consensus.annotations != null) ? (endRes < consensus.annotations.length ? consensus.annotations.length
628 consensus.annotations = null;
629 consensus.annotations = new Annotation[aWidth]; // should be alignment width
631 AAFrequency.completeConsensus(consensus, cnsns, startRes, endRes + 1,
632 ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO: setting
635 // ignoreGapsInConsensusCalculation);
640 * sequence to either add or remove from group
642 * flag passed to delete/addSequence to indicate if group properties
643 * should be recalculated
645 public void addOrRemove(SequenceI s, boolean recalc)
647 synchronized (sequences)
649 if (sequences.contains(s))
651 deleteSequence(s, recalc);
655 addSequence(s, recalc);
666 * true means recalculate conservation
668 public void deleteSequence(SequenceI s, boolean recalc)
670 synchronized (sequences)
676 recalcConservation();
684 * @return the first column selected by this group. Runs from 0<=i<N_cols
687 public int getStartRes()
694 * @return the groups last selected column. Runs from 0<=i<N_cols
697 public int getEndRes()
703 * Set the first column selected by this group. Runs from 0<=i<N_cols
707 public void setStartRes(int i)
713 * Set the groups last selected column. Runs from 0<=i<N_cols
717 public void setEndRes(int i)
723 * @return number of sequences in group
727 return sequences.size();
732 * @return the ith sequence
734 public SequenceI getSequenceAt(int i)
736 return sequences.get(i);
743 public void setColourText(boolean state)
751 * @return DOCUMENT ME!
753 public boolean getColourText()
764 public void setDisplayText(boolean state)
772 * @return DOCUMENT ME!
774 public boolean getDisplayText()
785 public void setDisplayBoxes(boolean state)
787 displayBoxes = state;
793 * @return DOCUMENT ME!
795 public boolean getDisplayBoxes()
801 * computes the width of current set of sequences and returns it
803 * @return DOCUMENT ME!
806 public int getWidth()
808 synchronized (sequences)
810 // MC This needs to get reset when characters are inserted and deleted
811 boolean first = true;
812 for (SequenceI seq : sequences)
814 if (first || seq.getLength() > width)
816 width = seq.getLength();
830 public void setOutlineColour(Color c)
838 * @return DOCUMENT ME!
840 public Color getOutlineColour()
842 return outlineColour;
847 * returns the sequences in the group ordered by the ordering given by al.
848 * this used to return an array with null entries regardless, new behaviour is
849 * below. TODO: verify that this does not affect use in applet or application
853 * @return SequenceI[] intersection of sequences in group with al, ordered by
854 * al, or null if group does not intersect with al
856 public SequenceI[] getSequencesInOrder(AlignmentI al)
858 return getSequencesInOrder(al, true);
862 * return an array representing the intersection of the group with al,
863 * optionally returning an array the size of al.getHeight() where nulls mark
864 * the non-intersected sequences
868 * @return null or array
870 public SequenceI[] getSequencesInOrder(AlignmentI al, boolean trim)
872 synchronized (sequences)
874 int sSize = sequences.size();
875 int alHeight = al.getHeight();
877 SequenceI[] seqs = new SequenceI[(trim) ? sSize : alHeight];
880 for (int i = 0; i < alHeight && index < sSize; i++)
882 if (sequences.contains(al.getSequenceAt(i)))
884 seqs[(trim) ? index : i] = al.getSequenceAt(i);
896 if (index < seqs.length)
898 SequenceI[] dummy = seqs;
899 seqs = new SequenceI[index];
902 seqs[index] = dummy[index];
911 * @return the idColour
913 public Color getIdColour()
920 * the idColour to set
922 public void setIdColour(Color idColour)
924 this.idColour = idColour;
928 * @return the representative sequence for this group
931 public SequenceI getSeqrep()
937 * set the representative sequence for this group. Note - this affects the
938 * interpretation of the Hidereps attribute.
941 * the seqrep to set (null means no sequence representative)
944 public void setSeqrep(SequenceI seqrep)
946 this.seqrep = seqrep;
951 * @return true if group has a sequence representative
954 public boolean hasSeqrep()
956 return seqrep != null;
960 * visibility of rows or represented rows covered by group
962 private boolean hidereps = false;
965 * set visibility of sequences covered by (if no sequence representative is
966 * defined) or represented by this group.
970 public void setHidereps(boolean visibility)
972 hidereps = visibility;
977 * @return true if sequences represented (or covered) by this group should be
980 public boolean isHidereps()
986 * visibility of columns intersecting this group
988 private boolean hidecols = false;
991 * set intended visibility of columns covered by this group
995 public void setHideCols(boolean visibility)
997 hidecols = visibility;
1002 * @return true if columns covered by group should be hidden
1004 public boolean isHideCols()
1010 * create a new sequence group from the intersection of this group with an
1011 * alignment Hashtable of hidden representatives
1017 * @return new group containing sequences common to this group and alignment
1019 public SequenceGroup intersect(AlignmentI alignment,
1020 Map<SequenceI, SequenceCollectionI> map)
1022 SequenceGroup sgroup = new SequenceGroup(this);
1023 SequenceI[] insect = getSequencesInOrder(alignment);
1024 sgroup.sequences = new ArrayList<>();
1025 for (int s = 0; insect != null && s < insect.length; s++)
1027 if (map == null || map.containsKey(insect[s]))
1029 sgroup.sequences.add(insect[s]);
1036 * @return the showUnconserved
1038 public boolean getShowNonconserved()
1040 return showNonconserved;
1044 * @param showNonconserved
1045 * the showUnconserved to set
1047 public void setShowNonconserved(boolean displayNonconserved)
1049 this.showNonconserved = displayNonconserved;
1052 AlignmentAnnotation consensus = null, conservation = null;
1055 * flag indicating if consensus histogram should be rendered
1057 private boolean showConsensusHistogram;
1060 * set this alignmentAnnotation object as the one used to render consensus
1065 public void setConsensus(AlignmentAnnotation aan)
1067 if (consensus == null)
1075 * @return automatically calculated consensus row note: the row is a stub if a
1076 * consensus calculation has not yet been performed on the group
1078 public AlignmentAnnotation getConsensus()
1080 // TODO get or calculate and get consensus annotation row for this group
1081 int aWidth = this.getWidth();
1089 if (consensus == null)
1091 consensus = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1092 100f, AlignmentAnnotation.BAR_GRAPH);
1093 consensus.hasText = true;
1094 consensus.autoCalculated = true;
1095 consensus.groupRef = this;
1096 consensus.label = "Consensus for " + getName();
1097 consensus.description = "Percent Identity";
1103 * set this alignmentAnnotation object as the one used to render consensus
1108 public void setConservationRow(AlignmentAnnotation aan)
1110 if (conservation == null)
1117 * get the conservation annotation row for this group
1119 * @return autoCalculated annotation row
1121 public AlignmentAnnotation getConservationRow()
1123 if (conservation == null)
1125 conservation = new AlignmentAnnotation("", "", new Annotation[1], 0f,
1126 11f, AlignmentAnnotation.BAR_GRAPH);
1129 conservation.hasText = true;
1130 conservation.autoCalculated = true;
1131 conservation.groupRef = this;
1132 conservation.label = "Conservation for " + getName();
1133 conservation.description = "Conservation for group " + getName()
1134 + " less than " + consPercGaps + "% gaps";
1135 return conservation;
1140 * @return true if annotation rows have been instantiated for this group
1142 public boolean hasAnnotationRows()
1144 return consensus != null || conservation != null;
1147 public SequenceI getConsensusSeq()
1150 StringBuffer seqs = new StringBuffer();
1151 for (int i = 0; i < consensus.annotations.length; i++)
1153 if (consensus.annotations[i] != null)
1155 if (consensus.annotations[i].description.charAt(0) == '[')
1157 seqs.append(consensus.annotations[i].description.charAt(1));
1161 seqs.append(consensus.annotations[i].displayCharacter);
1166 SequenceI sq = new Sequence("Group" + getName() + " Consensus",
1168 sq.setDescription("Percentage Identity Consensus "
1169 + ((ignoreGapsInConsensus) ? " without gaps" : ""));
1173 public void setIgnoreGapsConsensus(boolean state)
1175 if (this.ignoreGapsInConsensus != state && consensus != null)
1177 ignoreGapsInConsensus = state;
1178 recalcConservation();
1180 ignoreGapsInConsensus = state;
1183 public boolean getIgnoreGapsConsensus()
1185 return ignoreGapsInConsensus;
1189 * @param showSequenceLogo
1190 * indicates if a sequence logo is shown for consensus annotation
1192 public void setshowSequenceLogo(boolean showSequenceLogo)
1194 // TODO: decouple calculation from settings update
1195 if (this.showSequenceLogo != showSequenceLogo && consensus != null)
1197 this.showSequenceLogo = showSequenceLogo;
1198 recalcConservation();
1200 this.showSequenceLogo = showSequenceLogo;
1205 * @param showConsHist
1206 * flag indicating if the consensus histogram for this group should
1209 public void setShowConsensusHistogram(boolean showConsHist)
1212 if (showConsensusHistogram != showConsHist && consensus != null)
1214 this.showConsensusHistogram = showConsHist;
1215 recalcConservation();
1217 this.showConsensusHistogram = showConsHist;
1221 * @return the showConsensusHistogram
1223 public boolean isShowConsensusHistogram()
1225 return showConsensusHistogram;
1229 * set flag indicating if logo should be normalised when rendered
1233 public void setNormaliseSequenceLogo(boolean norm)
1235 normaliseSequenceLogo = norm;
1238 public boolean isNormaliseSequenceLogo()
1240 return normaliseSequenceLogo;
1245 * returns a new array with all annotation involving this group
1247 public AlignmentAnnotation[] getAlignmentAnnotation()
1249 // TODO add in other methods like 'getAlignmentAnnotation(String label),
1251 ArrayList<AlignmentAnnotation> annot = new ArrayList<>();
1252 synchronized (sequences)
1254 for (SequenceI seq : sequences)
1256 AlignmentAnnotation[] aa = seq.getAnnotation();
1259 for (AlignmentAnnotation al : aa)
1261 if (al.groupRef == this)
1268 if (consensus != null)
1270 annot.add(consensus);
1272 if (conservation != null)
1274 annot.add(conservation);
1277 return annot.toArray(new AlignmentAnnotation[0]);
1281 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1283 List<AlignmentAnnotation> aa = new ArrayList<>();
1288 for (AlignmentAnnotation a : getAlignmentAnnotation())
1290 if (calcId.equals(a.getCalcId()))
1299 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1300 String calcId, String label)
1302 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1303 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1305 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1307 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1308 && (label == null || (ann.label != null && ann.label
1318 * Answer true if any annotation matches the calcId passed in (if not null).
1323 public boolean hasAnnotation(String calcId)
1325 if (calcId != null && !"".equals(calcId))
1327 for (AlignmentAnnotation a : getAlignmentAnnotation())
1329 if (a.getCalcId() == calcId)
1339 * Remove all sequences from the group (leaving other properties unchanged).
1343 synchronized (sequences)
1349 private AnnotatedCollectionI context;
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);