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.AlignmentUtils;
24 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
25 import jalview.io.FastaFile;
26 import jalview.util.Comparison;
27 import jalview.util.LinkedIdentityHashSet;
28 import jalview.util.MessageManager;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.BitSet;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.HashSet;
36 import java.util.Hashtable;
37 import java.util.Iterator;
38 import java.util.List;
41 import java.util.Vector;
44 * Data structure to hold and manipulate a multiple sequence alignment
50 public class Alignment implements AlignmentI, AutoCloseable
52 private Alignment dataset;
54 private List<SequenceI> sequences;
56 protected List<SequenceGroup> groups;
58 protected char gapCharacter = '-';
60 private boolean nucleotide = true;
62 public boolean hasRNAStructure = false;
64 public AlignmentAnnotation[] annotations;
66 HiddenSequences hiddenSequences;
68 HiddenColumns hiddenCols;
70 public Hashtable alignmentProperties;
72 private List<AlignedCodonFrame> codonFrameList;
74 private void initAlignment(SequenceI[] seqs)
76 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
77 hiddenSequences = new HiddenSequences(this);
78 hiddenCols = new HiddenColumns();
79 codonFrameList = new ArrayList<>();
81 nucleotide = Comparison.isNucleotide(seqs);
83 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
85 for (int i = 0; i < seqs.length; i++)
87 sequences.add(seqs[i]);
93 * Make a 'copy' alignment - sequences have new copies of features and
94 * annotations, but share the original dataset sequences.
96 public Alignment(AlignmentI al)
98 SequenceI[] seqs = al.getSequencesArray();
99 for (int i = 0; i < seqs.length; i++)
101 seqs[i] = new Sequence(seqs[i]);
107 * Share the same dataset sequence mappings (if any).
109 if (dataset == null && al.getDataset() == null)
111 this.setCodonFrames(al.getCodonFrames());
116 * Make an alignment from an array of Sequences.
120 public Alignment(SequenceI[] seqs)
126 * Make a new alignment from an array of SeqCigars
131 public Alignment(SeqCigar[] alseqs)
133 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
134 gapCharacter, new HiddenColumns(), null);
139 * Make a new alignment from an CigarArray JBPNote - can only do this when
140 * compactAlignment does not contain hidden regions. JBPNote - must also check
141 * that compactAlignment resolves to a set of SeqCigars - or construct them
144 * @param compactAlignment
147 public static AlignmentI createAlignment(CigarArray compactAlignment)
149 throw new Error(MessageManager
150 .getString("error.alignment_cigararray_not_implemented"));
151 // this(compactAlignment.refCigars);
155 public List<SequenceI> getSequences()
161 public List<SequenceI> getSequences(
162 Map<SequenceI, SequenceCollectionI> hiddenReps)
164 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
170 public SequenceI[] getSequencesArray()
172 if (sequences == null)
176 synchronized (sequences)
178 return sequences.toArray(new SequenceI[sequences.size()]);
183 * Returns a map of lists of sequences keyed by sequence name.
188 public Map<String, List<SequenceI>> getSequencesByName()
190 return AlignmentUtils.getSequencesByName(this);
194 public SequenceI getSequenceAt(int i)
196 synchronized (sequences)
199 if (i > -1 && i < sequences.size())
201 return sequences.get(i);
209 public SequenceI getSequenceAtAbsoluteIndex(int i)
211 SequenceI seq = null;
212 if (getHiddenSequences().getSize() > 0)
214 seq = getHiddenSequences().getHiddenSequence(i);
217 // didn't find the sequence in the hidden sequences, get it from the
219 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
220 seq = getSequenceAt(index);
225 seq = getSequenceAt(i);
231 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
232 * this currently does not recalculate whether or not the alignment is
233 * nucleotide, so mixed alignments may have undefined behaviour.
238 public void addSequence(SequenceI snew)
243 // maintain dataset integrity
244 SequenceI dsseq = snew.getDatasetSequence();
247 // derive new sequence
248 SequenceI adding = snew.deriveSequence();
250 dsseq = snew.getDatasetSequence();
252 if (getDataset().findIndex(dsseq) == -1)
254 getDataset().addSequence(dsseq);
258 if (sequences == null)
260 initAlignment(new SequenceI[] { snew });
264 synchronized (sequences)
269 if (hiddenSequences != null)
271 hiddenSequences.adjustHeightSequenceAdded();
276 public SequenceI replaceSequenceAt(int i, SequenceI snew)
278 synchronized (sequences)
280 if (sequences.size() > i)
282 return sequences.set(i, snew);
288 hiddenSequences.adjustHeightSequenceAdded();
297 * @return DOCUMENT ME!
300 public List<SequenceGroup> getGroups()
308 if (getDataset() != null)
312 getDataset().removeAlignmentRef();
313 } catch (Throwable e)
323 * Defensively nulls out references in case this object is not garbage
326 void nullReferences()
332 hiddenSequences = null;
336 * decrement the alignmentRefs counter by one and null references if it goes
341 private void removeAlignmentRef() throws Throwable
343 if (--alignmentRefs == 0)
350 public void deleteSequence(SequenceI s)
352 synchronized (sequences)
354 deleteSequence(findIndex(s));
359 public void deleteSequence(int i)
361 synchronized (sequences)
363 if (i > -1 && i < getHeight())
366 hiddenSequences.adjustHeightSequenceDeleted(i);
372 public void deleteHiddenSequence(int i)
374 synchronized (sequences)
376 if (i > -1 && i < getHeight())
386 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
389 public SequenceGroup findGroup(SequenceI seq, int position)
391 synchronized (groups)
393 for (SequenceGroup sg : groups)
395 if (sg.getSequences(null).contains(seq))
397 if (position >= sg.getStartRes() && position <= sg.getEndRes())
411 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
414 public SequenceGroup[] findAllGroups(SequenceI s)
416 ArrayList<SequenceGroup> temp = new ArrayList<>();
418 synchronized (groups)
420 int gSize = groups.size();
421 for (int i = 0; i < gSize; i++)
423 SequenceGroup sg = groups.get(i);
424 if (sg == null || sg.getSequences() == null)
426 this.deleteGroup(sg);
431 if (sg.getSequences().contains(s))
437 SequenceGroup[] ret = new SequenceGroup[temp.size()];
438 return temp.toArray(ret);
443 public void addGroup(SequenceGroup sg)
445 synchronized (groups)
447 if (!groups.contains(sg))
449 if (hiddenSequences.getSize() > 0)
451 int i, iSize = sg.getSize();
452 for (i = 0; i < iSize; i++)
454 if (!sequences.contains(sg.getSequenceAt(i)))
456 sg.deleteSequence(sg.getSequenceAt(i), false);
462 if (sg.getSize() < 1)
467 sg.setContext(this, true);
474 * remove any annotation that references gp
477 * (if null, removes all group associated annotation)
479 private void removeAnnotationForGroup(SequenceGroup gp)
481 if (annotations == null || annotations.length == 0)
485 // remove annotation very quickly
486 AlignmentAnnotation[] t,
487 todelete = new AlignmentAnnotation[annotations.length],
488 tokeep = new AlignmentAnnotation[annotations.length];
492 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
494 if (annotations[i].groupRef != null)
496 todelete[p++] = annotations[i];
500 tokeep[k++] = annotations[i];
506 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
508 if (annotations[i].groupRef == gp)
510 todelete[p++] = annotations[i];
514 tokeep[k++] = annotations[i];
520 // clear out the group associated annotation.
521 for (i = 0; i < p; i++)
523 unhookAnnotation(todelete[i]);
526 t = new AlignmentAnnotation[k];
527 for (i = 0; i < k; i++)
536 public void deleteAllGroups()
538 synchronized (groups)
540 if (annotations != null)
542 removeAnnotationForGroup(null);
544 for (SequenceGroup sg : groups)
546 sg.setContext(null, false);
554 public void deleteGroup(SequenceGroup g)
556 synchronized (groups)
558 if (groups.contains(g))
560 removeAnnotationForGroup(g);
562 g.setContext(null, false);
569 public SequenceI findName(String name)
571 return findName(name, false);
577 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
580 public SequenceI findName(String token, boolean b)
582 return findName(null, token, b);
588 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
592 public SequenceI findName(SequenceI startAfter, String token, boolean b)
597 String sqname = null;
598 int nseq = sequences.size();
599 if (startAfter != null)
601 // try to find the sequence in the alignment
602 boolean matched = false;
605 if (getSequenceAt(i++) == startAfter)
618 sq = getSequenceAt(i);
619 sqname = sq.getName();
620 if (sqname.equals(token) // exact match
621 || (b && // allow imperfect matches - case varies
622 (sqname.equalsIgnoreCase(token))))
624 return getSequenceAt(i);
634 public SequenceI[] findSequenceMatch(String name)
636 Vector matches = new Vector();
639 while (i < sequences.size())
641 if (getSequenceAt(i).getName().equals(name))
643 matches.addElement(getSequenceAt(i));
648 SequenceI[] result = new SequenceI[matches.size()];
649 for (i = 0; i < result.length; i++)
651 result[i] = (SequenceI) matches.elementAt(i);
661 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
664 public int findIndex(SequenceI s)
668 while (i < sequences.size())
670 if (s == getSequenceAt(i))
685 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
688 public int findIndex(SearchResultsI results)
692 while (i < sequences.size())
694 if (results.involvesSequence(getSequenceAt(i)))
704 public int getHeight()
706 return sequences.size();
710 public int getAbsoluteHeight()
712 return sequences.size() + getHiddenSequences().getSize();
716 public int getWidth()
720 for (int i = 0; i < sequences.size(); i++)
722 maxLength = Math.max(maxLength, getSequenceAt(i).getLength());
728 public int getVisibleWidth()
731 if (hiddenCols != null)
733 w -= hiddenCols.getSize();
745 public void setGapCharacter(char gc)
748 synchronized (sequences)
750 for (SequenceI seq : sequences)
752 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
753 .replace('-', gc).replace(' ', gc));
761 * @return DOCUMENT ME!
764 public char getGapCharacter()
772 * @see jalview.datamodel.AlignmentI#isAligned()
775 public boolean isAligned()
777 return isAligned(false);
783 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
786 public boolean isAligned(boolean includeHidden)
788 int width = getWidth();
789 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
791 includeHidden = true; // no hidden sequences to check against.
793 for (int i = 0; i < sequences.size(); i++)
795 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
797 if (getSequenceAt(i).getLength() != width)
808 public boolean isHidden(int alignmentIndex)
810 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
814 * Delete all annotations, including auto-calculated if the flag is set true.
815 * Returns true if at least one annotation was deleted, else false.
817 * @param includingAutoCalculated
821 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
823 boolean result = false;
824 for (AlignmentAnnotation alan : getAlignmentAnnotation())
826 if (!alan.autoCalculated || includingAutoCalculated)
828 deleteAnnotation(alan);
838 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
839 * AlignmentAnnotation)
842 public boolean deleteAnnotation(AlignmentAnnotation aa)
844 return deleteAnnotation(aa, true);
848 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
852 if (annotations != null)
854 aSize = annotations.length;
862 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
864 boolean swap = false;
867 for (int i = 0; i < aSize; i++)
869 if (annotations[i] == aa)
874 if (tIndex < temp.length)
876 temp[tIndex++] = annotations[i];
885 unhookAnnotation(aa);
892 * remove any object references associated with this annotation
896 private void unhookAnnotation(AlignmentAnnotation aa)
898 if (aa.sequenceRef != null)
900 aa.sequenceRef.removeAlignmentAnnotation(aa);
902 if (aa.groupRef != null)
904 // probably need to do more here in the future (post 2.5.0)
912 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
913 * AlignmentAnnotation)
916 public void addAnnotation(AlignmentAnnotation aa)
918 addAnnotation(aa, -1);
924 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
925 * AlignmentAnnotation, int)
928 public void addAnnotation(AlignmentAnnotation aa, int pos)
930 if (aa.getRNAStruc() != null)
932 hasRNAStructure = true;
936 if (annotations != null)
938 aSize = annotations.length + 1;
941 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
943 if (pos == -1 || pos >= aSize)
945 temp[aSize - 1] = aa;
954 for (i = 0; i < (aSize - 1); i++, p++)
962 temp[p] = annotations[i];
971 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
973 if (aa == null || annotations == null || annotations.length - 1 < index)
978 int aSize = annotations.length;
979 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
983 for (int i = 0; i < aSize; i++)
992 temp[i] = annotations[i];
996 temp[i] = annotations[i - 1];
1005 * returns all annotation on the alignment
1007 public AlignmentAnnotation[] getAlignmentAnnotation()
1013 public boolean isNucleotide()
1019 public boolean hasRNAStructure()
1021 // TODO can it happen that structure is removed from alignment?
1022 return hasRNAStructure;
1026 public void setDataset(AlignmentI data)
1028 if (dataset == null && data == null)
1030 createDatasetAlignment();
1032 else if (dataset == null && data != null)
1036 throw new IllegalArgumentException("Circular dataset reference");
1038 if (!(data instanceof Alignment))
1041 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1043 dataset = (Alignment) data;
1044 for (int i = 0; i < getHeight(); i++)
1046 SequenceI currentSeq = getSequenceAt(i);
1047 SequenceI dsq = currentSeq.getDatasetSequence();
1050 dsq = currentSeq.createDatasetSequence();
1051 dataset.addSequence(dsq);
1055 while (dsq.getDatasetSequence() != null)
1057 dsq = dsq.getDatasetSequence();
1059 if (dataset.findIndex(dsq) == -1)
1061 dataset.addSequence(dsq);
1066 dataset.addAlignmentRef();
1070 * add dataset sequences to seq for currentSeq and any sequences it references
1072 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1073 Set<SequenceI> seqs, boolean createDatasetSequence)
1075 SequenceI alignedSeq = currentSeq;
1076 if (currentSeq.getDatasetSequence() != null)
1078 currentSeq = currentSeq.getDatasetSequence();
1082 if (createDatasetSequence)
1084 currentSeq = currentSeq.createDatasetSequence();
1088 List<SequenceI> toProcess = new ArrayList<>();
1089 toProcess.add(currentSeq);
1090 while (toProcess.size() > 0)
1093 SequenceI curDs = toProcess.remove(0);
1095 if (!seqs.add(curDs))
1099 // iterate over database references, making sure we add forward referenced
1101 if (curDs.getDBRefs() != null)
1103 for (DBRefEntry dbr : curDs.getDBRefs())
1105 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1107 if (dbr.getMap().getTo() == alignedSeq)
1110 * update mapping to be to the newly created dataset sequence
1112 dbr.getMap().setTo(currentSeq);
1114 if (dbr.getMap().getTo().getDatasetSequence() != null)
1116 throw new Error("Implementation error: Map.getTo() for dbref "
1117 + dbr + " from " + curDs.getName()
1118 + " is not a dataset sequence.");
1120 // we recurse to add all forward references to dataset sequences via
1122 toProcess.add(dbr.getMap().getTo());
1130 * Creates a new dataset for this alignment. Can only be done once - if
1131 * dataset is not null this will not be performed.
1133 public void createDatasetAlignment()
1135 if (dataset != null)
1139 // try to avoid using SequenceI.equals at this stage, it will be expensive
1140 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1142 for (int i = 0; i < getHeight(); i++)
1144 SequenceI currentSeq = getSequenceAt(i);
1145 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1148 // verify all mappings are in dataset
1149 for (AlignedCodonFrame cf : codonFrameList)
1151 for (SequenceToSequenceMapping ssm : cf.getMappings())
1153 if (!seqs.contains(ssm.getFromSeq()))
1155 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1157 if (!seqs.contains(ssm.getMapping().getTo()))
1159 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1163 // finally construct dataset
1164 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1165 // move mappings to the dataset alignment
1166 dataset.codonFrameList = this.codonFrameList;
1167 this.codonFrameList = null;
1171 * reference count for number of alignments referencing this one.
1173 int alignmentRefs = 0;
1176 * increase reference count to this alignment.
1178 private void addAlignmentRef()
1184 public Alignment getDataset()
1190 public boolean padGaps()
1192 boolean modified = false;
1194 // Remove excess gaps from the end of alignment
1198 int nseq = sequences.size();
1199 for (int i = 0; i < nseq; i++)
1201 current = getSequenceAt(i);
1202 for (int j = current.getLength(); j > maxLength; j--)
1205 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1216 for (int i = 0; i < nseq; i++)
1218 current = getSequenceAt(i);
1219 cLength = current.getLength();
1221 if (cLength < maxLength)
1223 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1226 else if (current.getLength() > maxLength)
1228 current.deleteChars(maxLength, current.getLength());
1235 * Justify the sequences to the left or right by deleting and inserting gaps
1236 * before the initial residue or after the terminal residue
1239 * true if alignment padded to right, false to justify to left
1240 * @return true if alignment was changed
1243 public boolean justify(boolean right)
1245 boolean modified = false;
1247 // Remove excess gaps from the end of alignment
1249 int ends[] = new int[sequences.size() * 2];
1251 for (int i = 0; i < sequences.size(); i++)
1253 current = getSequenceAt(i);
1254 // This should really be a sequence method
1255 ends[i * 2] = current.findIndex(current.getStart());
1256 ends[i * 2 + 1] = current
1257 .findIndex(current.getStart() + current.getLength());
1258 boolean hitres = false;
1259 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1261 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1270 ends[i * 2 + 1] = j;
1271 if (j - ends[i * 2] > maxLength)
1273 maxLength = j - ends[i * 2];
1281 // now edit the flanking gaps to justify to either left or right
1282 int cLength, extent, diff;
1283 for (int i = 0; i < sequences.size(); i++)
1285 current = getSequenceAt(i);
1287 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1288 diff = maxLength - cLength; // number of gaps to indent
1289 extent = current.getLength();
1293 if (extent > ends[i * 2 + 1])
1295 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1298 if (ends[i * 2] > diff)
1300 current.deleteChars(0, ends[i * 2] - diff);
1305 if (ends[i * 2] < diff)
1307 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1315 if (ends[i * 2] > 0)
1317 current.deleteChars(0, ends[i * 2]);
1319 ends[i * 2 + 1] -= ends[i * 2];
1320 extent -= ends[i * 2];
1322 if (extent > maxLength)
1324 current.deleteChars(maxLength + 1, extent);
1329 if (extent < maxLength)
1331 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1341 public HiddenSequences getHiddenSequences()
1343 return hiddenSequences;
1347 public HiddenColumns getHiddenColumns()
1353 public CigarArray getCompactAlignment()
1355 synchronized (sequences)
1357 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1359 for (SequenceI seq : sequences)
1361 alseqs[i++] = new SeqCigar(seq);
1363 CigarArray cal = new CigarArray(alseqs);
1364 cal.addOperation(CigarArray.M, getWidth());
1370 public void setProperty(Object key, Object value)
1372 if (alignmentProperties == null)
1374 alignmentProperties = new Hashtable();
1377 alignmentProperties.put(key, value);
1381 public Object getProperty(Object key)
1383 if (alignmentProperties != null)
1385 return alignmentProperties.get(key);
1394 public Hashtable getProperties()
1396 return alignmentProperties;
1400 * Adds the given mapping to the stored set. Note this may be held on the
1401 * dataset alignment.
1404 public void addCodonFrame(AlignedCodonFrame codons)
1406 List<AlignedCodonFrame> acfs = getCodonFrames();
1407 if (codons != null && acfs != null && !acfs.contains(codons))
1417 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1420 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1426 List<AlignedCodonFrame> cframes = new ArrayList<>();
1427 for (AlignedCodonFrame acf : getCodonFrames())
1429 if (acf.involvesSequence(seq))
1438 * Sets the codon frame mappings (replacing any existing mappings). Note the
1439 * mappings are set on the dataset alignment instead if there is one.
1441 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1444 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1446 if (dataset != null)
1448 dataset.setCodonFrames(acfs);
1452 this.codonFrameList = acfs;
1457 * Returns the set of codon frame mappings. Any changes to the returned set
1458 * will affect the alignment. The mappings are held on (and read from) the
1459 * dataset alignment if there is one.
1461 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1464 public List<AlignedCodonFrame> getCodonFrames()
1466 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1467 // this behaviour is currently incorrect. method should return codon frames
1468 // for just the alignment,
1469 // selected from dataset
1470 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1474 * Removes the given mapping from the stored set. Note that the mappings are
1475 * held on the dataset alignment if there is one.
1478 public boolean removeCodonFrame(AlignedCodonFrame codons)
1480 List<AlignedCodonFrame> acfs = getCodonFrames();
1481 if (codons == null || acfs == null)
1485 return acfs.remove(codons);
1489 public void append(AlignmentI toappend)
1491 // TODO JAL-1270 needs test coverage
1492 // currently tested for use in jalview.gui.SequenceFetcher
1493 char oldc = toappend.getGapCharacter();
1494 boolean samegap = oldc == getGapCharacter();
1495 boolean hashidden = toappend.getHiddenSequences() != null
1496 && toappend.getHiddenSequences().hiddenSequences != null;
1497 // get all sequences including any hidden ones
1498 List<SequenceI> sqs = (hashidden)
1499 ? toappend.getHiddenSequences().getFullAlignment()
1501 : toappend.getSequences();
1504 // avoid self append deadlock by
1505 List<SequenceI> toappendsq = new ArrayList<>();
1508 for (SequenceI addedsq : sqs)
1512 addedsq.replace(oldc, gapCharacter);
1514 toappendsq.add(addedsq);
1517 for (SequenceI addedsq : toappendsq)
1519 addSequence(addedsq);
1522 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1523 for (int a = 0; alan != null && a < alan.length; a++)
1525 addAnnotation(alan[a]);
1529 getCodonFrames().addAll(toappend.getCodonFrames());
1531 List<SequenceGroup> sg = toappend.getGroups();
1534 for (SequenceGroup _sg : sg)
1539 if (toappend.getHiddenSequences() != null)
1541 HiddenSequences hs = toappend.getHiddenSequences();
1542 if (hiddenSequences == null)
1544 hiddenSequences = new HiddenSequences(this);
1546 if (hs.hiddenSequences != null)
1548 for (int s = 0; s < hs.hiddenSequences.length; s++)
1550 // hide the newly appended sequence in the alignment
1551 if (hs.hiddenSequences[s] != null)
1553 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1558 if (toappend.getProperties() != null)
1560 // we really can't do very much here - just try to concatenate strings
1561 // where property collisions occur.
1562 Enumeration key = toappend.getProperties().keys();
1563 while (key.hasMoreElements())
1565 Object k = key.nextElement();
1566 Object ourval = this.getProperty(k);
1567 Object toapprop = toappend.getProperty(k);
1570 if (ourval.getClass().equals(toapprop.getClass())
1571 && !ourval.equals(toapprop))
1573 if (ourval instanceof String)
1577 ((String) ourval) + "; " + ((String) toapprop));
1581 if (ourval instanceof Vector)
1584 Enumeration theirv = ((Vector) toapprop).elements();
1585 while (theirv.hasMoreElements())
1587 ((Vector) ourval).addElement(theirv);
1595 // just add new property directly
1596 setProperty(k, toapprop);
1604 public AlignmentAnnotation findOrCreateAnnotation(String name,
1605 String calcId, boolean autoCalc, SequenceI seqRef,
1606 SequenceGroup groupRef)
1608 if (annotations != null)
1610 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1612 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1613 && (calcId == null || annot.getCalcId().equals(calcId))
1614 && annot.sequenceRef == seqRef
1615 && annot.groupRef == groupRef)
1621 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1622 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1623 annot.hasText = false;
1626 annot.setCalcId(new String(calcId));
1628 annot.autoCalculated = autoCalc;
1631 annot.setSequenceRef(seqRef);
1633 annot.groupRef = groupRef;
1634 addAnnotation(annot);
1640 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1642 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1643 if (alignmentAnnotation != null)
1645 return AlignmentAnnotation.findAnnotation(
1646 Arrays.asList(getAlignmentAnnotation()), calcId);
1648 return Arrays.asList(new AlignmentAnnotation[] {});
1652 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1653 String calcId, String label)
1655 return AlignmentAnnotation.findAnnotations(
1656 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1660 public void moveSelectedSequencesByOne(SequenceGroup sg,
1661 Map<SequenceI, SequenceCollectionI> map, boolean up)
1663 synchronized (sequences)
1668 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1670 SequenceI seq = sequences.get(i);
1671 if (!sg.getSequences(map).contains(seq))
1676 SequenceI temp = sequences.get(i - 1);
1677 if (sg.getSequences(null).contains(temp))
1682 sequences.set(i, temp);
1683 sequences.set(i - 1, seq);
1688 for (int i = sequences.size() - 2; i > -1; i--)
1690 SequenceI seq = sequences.get(i);
1691 if (!sg.getSequences(map).contains(seq))
1696 SequenceI temp = sequences.get(i + 1);
1697 if (sg.getSequences(map).contains(temp))
1702 sequences.set(i, temp);
1703 sequences.set(i + 1, seq);
1711 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1713 alignmentAnnotation.validateRangeAndDisplay();
1714 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1716 hasRNAStructure = true;
1720 private SequenceI seqrep = null;
1724 * @return the representative sequence for this group
1727 public SequenceI getSeqrep()
1733 * set the representative sequence for this group. Note - this affects the
1734 * interpretation of the Hidereps attribute.
1737 * the seqrep to set (null means no sequence representative)
1740 public void setSeqrep(SequenceI seqrep)
1742 this.seqrep = seqrep;
1747 * @return true if group has a sequence representative
1750 public boolean hasSeqrep()
1752 return seqrep != null;
1756 public int getEndRes()
1758 return getWidth() - 1;
1762 public int getStartRes()
1768 * In the case of AlignmentI - returns the dataset for the alignment, if set
1771 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1774 public AnnotatedCollectionI getContext()
1780 * Align this alignment like the given (mapped) one.
1783 public int alignAs(AlignmentI al)
1786 * Currently retains unmapped gaps (in introns), regaps mapped regions
1789 return alignAs(al, false, true);
1793 * Align this alignment 'the same as' the given one. Mapped sequences only are
1794 * realigned. If both of the same type (nucleotide/protein) then align both
1795 * identically. If this is nucleotide and the other is protein, make 3 gaps
1796 * for each gap in the protein sequences. If this is protein and the other is
1797 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1798 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1799 * protein to match the relative ordering of codons in the nucleotide.
1801 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1802 * regions are preserved. Gaps that connect introns to exons are treated
1803 * conservatively, i.e. only preserved if both intron and exon gaps are
1804 * preserved. TODO: check caveats below where the implementation fails
1807 * - must have same dataset, and sequences in al must have equivalent
1808 * dataset sequence and start/end bounds under given mapping
1809 * @param preserveMappedGaps
1810 * if true, gaps within and between mapped codons are preserved
1811 * @param preserveUnmappedGaps
1812 * if true, gaps within and between unmapped codons are preserved
1815 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1816 boolean preserveUnmappedGaps)
1818 // TODO should this method signature be the one in the interface?
1819 // JBPComment - yes - neither flag is used, so should be deleted.
1820 boolean thisIsNucleotide = this.isNucleotide();
1821 boolean thatIsProtein = !al.isNucleotide();
1822 if (!thatIsProtein && !thisIsNucleotide)
1824 return AlignmentUtils.alignProteinAsDna(this, al);
1826 else if (thatIsProtein && thisIsNucleotide)
1828 return AlignmentUtils.alignCdsAsProtein(this, al);
1830 return AlignmentUtils.alignAs(this, al);
1834 * Returns the alignment in Fasta format. Behaviour of this method is not
1835 * guaranteed between versions.
1838 public String toString()
1840 return new FastaFile().print(getSequencesArray(), true);
1844 * Returns the set of distinct sequence names. No ordering is guaranteed.
1847 public Set<String> getSequenceNames()
1849 Set<String> names = new HashSet<>();
1850 for (SequenceI seq : getSequences())
1852 names.add(seq.getName());
1858 public boolean hasValidSequence()
1860 boolean hasValidSeq = false;
1861 for (SequenceI seq : getSequences())
1863 if ((seq.getEnd() - seq.getStart()) > 0)
1873 * Update any mappings to 'virtual' sequences to compatible real ones, if
1874 * present in the added sequences. Returns a count of mappings updated.
1880 public int realiseMappings(List<SequenceI> seqs)
1883 for (SequenceI seq : seqs)
1885 for (AlignedCodonFrame mapping : getCodonFrames())
1887 count += mapping.realiseWith(seq);
1894 * Returns the first AlignedCodonFrame that has a mapping between the given
1902 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1904 for (AlignedCodonFrame acf : getCodonFrames())
1906 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1915 public boolean setHiddenColumns(HiddenColumns cols)
1917 boolean changed = cols == null ? hiddenCols != null
1918 : !cols.equals(hiddenCols);
1924 public void setupJPredAlignment()
1926 SequenceI repseq = getSequenceAt(0);
1928 HiddenColumns cs = new HiddenColumns();
1929 cs.hideList(repseq.getInsertions());
1930 setHiddenColumns(cs);
1934 public HiddenColumns propagateInsertions(SequenceI profileseq,
1935 AlignmentView input)
1939 char gc = getGapCharacter();
1940 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1941 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1942 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1943 return propagateInsertions(profileseq, origseq, nview);
1949 * sequence in al which corresponds to origseq
1951 * alignment which is to have gaps inserted into it
1953 * sequence corresponding to profileseq which defines gap map for
1956 private HiddenColumns propagateInsertions(SequenceI profileseq,
1957 SequenceI origseq, HiddenColumns hc)
1959 // take the set of hidden columns, and the set of gaps in origseq,
1960 // and remove all the hidden gaps from hiddenColumns
1962 // first get the gaps as a Bitset
1963 // then calculate hidden ^ not(gap)
1964 BitSet gaps = origseq.gapBitset();
1967 // for each sequence in the alignment, except the profile sequence,
1968 // insert gaps corresponding to each hidden region but where each hidden
1969 // column region is shifted backwards by the number of preceding visible
1970 // gaps update hidden columns at the same time
1971 HiddenColumns newhidden = new HiddenColumns();
1973 int numGapsBefore = 0;
1974 int gapPosition = 0;
1975 Iterator<int[]> it = hc.iterator();
1976 while (it.hasNext())
1978 int[] region = it.next();
1980 // get region coordinates accounting for gaps
1981 // we can rely on gaps not being *in* hidden regions because we already
1983 while (gapPosition < region[0])
1986 if (gaps.get(gapPosition))
1992 int left = region[0] - numGapsBefore;
1993 int right = region[1] - numGapsBefore;
1995 newhidden.hideColumns(left, right);
1996 padGaps(left, right, profileseq);
2002 * Pad gaps in all sequences in alignment except profileseq
2005 * position of first gap to insert
2007 * position of last gap to insert
2009 * sequence not to pad
2011 private void padGaps(int left, int right, SequenceI profileseq)
2013 char gc = getGapCharacter();
2015 // make a string with number of gaps = length of hidden region
2016 StringBuilder sb = new StringBuilder();
2017 for (int g = 0; g < right - left + 1; g++)
2022 // loop over the sequences and pad with gaps where required
2023 for (int s = 0, ns = getHeight(); s < ns; s++)
2025 SequenceI sqobj = getSequenceAt(s);
2026 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2028 String sq = sqobj.getSequenceAsString();
2030 sq.substring(0, left) + sb.toString() + sq.substring(left));