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
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()
306 public void finalize() throws Throwable
308 if (getDataset() != null)
310 getDataset().removeAlignmentRef();
318 * Defensively nulls out references in case this object is not garbage
321 void nullReferences()
327 hiddenSequences = null;
331 * decrement the alignmentRefs counter by one and null references if it goes
336 private void removeAlignmentRef() throws Throwable
338 if (--alignmentRefs == 0)
345 public void deleteSequence(SequenceI s)
347 synchronized (sequences)
349 deleteSequence(findIndex(s));
354 public void deleteSequence(int i)
356 synchronized (sequences)
358 if (i > -1 && i < getHeight())
361 hiddenSequences.adjustHeightSequenceDeleted(i);
367 public void deleteHiddenSequence(int i)
369 synchronized (sequences)
371 if (i > -1 && i < getHeight())
381 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
384 public SequenceGroup findGroup(SequenceI seq, int position)
386 synchronized (groups)
388 for (SequenceGroup sg : groups)
390 if (sg.getSequences(null).contains(seq))
392 if (position >= sg.getStartRes() && position <= sg.getEndRes())
406 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
409 public SequenceGroup[] findAllGroups(SequenceI s)
411 ArrayList<SequenceGroup> temp = new ArrayList<>();
413 synchronized (groups)
415 int gSize = groups.size();
416 for (int i = 0; i < gSize; i++)
418 SequenceGroup sg = groups.get(i);
419 if (sg == null || sg.getSequences() == null)
421 this.deleteGroup(sg);
426 if (sg.getSequences().contains(s))
432 SequenceGroup[] ret = new SequenceGroup[temp.size()];
433 return temp.toArray(ret);
438 public void addGroup(SequenceGroup sg)
440 synchronized (groups)
442 if (!groups.contains(sg))
444 if (hiddenSequences.getSize() > 0)
446 int i, iSize = sg.getSize();
447 for (i = 0; i < iSize; i++)
449 if (!sequences.contains(sg.getSequenceAt(i)))
451 sg.deleteSequence(sg.getSequenceAt(i), false);
457 if (sg.getSize() < 1)
462 sg.setContext(this, true);
469 * remove any annotation that references gp
472 * (if null, removes all group associated annotation)
474 private void removeAnnotationForGroup(SequenceGroup gp)
476 if (annotations == null || annotations.length == 0)
480 // remove annotation very quickly
481 AlignmentAnnotation[] t,
482 todelete = new AlignmentAnnotation[annotations.length],
483 tokeep = new AlignmentAnnotation[annotations.length];
487 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
489 if (annotations[i].groupRef != null)
491 todelete[p++] = annotations[i];
495 tokeep[k++] = annotations[i];
501 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
503 if (annotations[i].groupRef == gp)
505 todelete[p++] = annotations[i];
509 tokeep[k++] = annotations[i];
515 // clear out the group associated annotation.
516 for (i = 0; i < p; i++)
518 unhookAnnotation(todelete[i]);
521 t = new AlignmentAnnotation[k];
522 for (i = 0; i < k; i++)
531 public void deleteAllGroups()
533 synchronized (groups)
535 if (annotations != null)
537 removeAnnotationForGroup(null);
539 for (SequenceGroup sg : groups)
541 sg.setContext(null, false);
549 public void deleteGroup(SequenceGroup g)
551 synchronized (groups)
553 if (groups.contains(g))
555 removeAnnotationForGroup(g);
557 g.setContext(null, false);
564 public SequenceI findName(String name)
566 return findName(name, false);
572 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
575 public SequenceI findName(String token, boolean b)
577 return findName(null, token, b);
583 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
587 public SequenceI findName(SequenceI startAfter, String token, boolean b)
592 String sqname = null;
593 int nseq = sequences.size();
594 if (startAfter != null)
596 // try to find the sequence in the alignment
597 boolean matched = false;
600 if (getSequenceAt(i++) == startAfter)
613 sq = getSequenceAt(i);
614 sqname = sq.getName();
615 if (sqname.equals(token) // exact match
616 || (b && // allow imperfect matches - case varies
617 (sqname.equalsIgnoreCase(token))))
619 return getSequenceAt(i);
629 public SequenceI[] findSequenceMatch(String name)
631 Vector matches = new Vector();
634 while (i < sequences.size())
636 if (getSequenceAt(i).getName().equals(name))
638 matches.addElement(getSequenceAt(i));
643 SequenceI[] result = new SequenceI[matches.size()];
644 for (i = 0; i < result.length; i++)
646 result[i] = (SequenceI) matches.elementAt(i);
656 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
659 public int findIndex(SequenceI s)
663 while (i < sequences.size())
665 if (s == getSequenceAt(i))
680 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
683 public int findIndex(SearchResultsI results)
687 while (i < sequences.size())
689 if (results.involvesSequence(getSequenceAt(i)))
699 public int getHeight()
701 return sequences.size();
705 public int getAbsoluteHeight()
707 return sequences.size() + getHiddenSequences().getSize();
711 public int getWidth()
715 for (int i = 0; i < sequences.size(); i++)
717 maxLength = Math.max(maxLength, getSequenceAt(i).getLength());
723 public int getVisibleWidth()
726 if (hiddenCols != null)
728 w -= hiddenCols.getSize();
740 public void setGapCharacter(char gc)
743 synchronized (sequences)
745 for (SequenceI seq : sequences)
747 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
748 .replace('-', gc).replace(' ', gc));
756 * @return DOCUMENT ME!
759 public char getGapCharacter()
767 * @see jalview.datamodel.AlignmentI#isAligned()
770 public boolean isAligned()
772 return isAligned(false);
778 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
781 public boolean isAligned(boolean includeHidden)
783 int width = getWidth();
784 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
786 includeHidden = true; // no hidden sequences to check against.
788 for (int i = 0; i < sequences.size(); i++)
790 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
792 if (getSequenceAt(i).getLength() != width)
803 public boolean isHidden(int alignmentIndex)
805 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
809 * Delete all annotations, including auto-calculated if the flag is set true.
810 * Returns true if at least one annotation was deleted, else false.
812 * @param includingAutoCalculated
816 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
818 boolean result = false;
819 for (AlignmentAnnotation alan : getAlignmentAnnotation())
821 if (!alan.autoCalculated || includingAutoCalculated)
823 deleteAnnotation(alan);
833 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
834 * AlignmentAnnotation)
837 public boolean deleteAnnotation(AlignmentAnnotation aa)
839 return deleteAnnotation(aa, true);
843 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
847 if (annotations != null)
849 aSize = annotations.length;
857 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
859 boolean swap = false;
862 for (int i = 0; i < aSize; i++)
864 if (annotations[i] == aa)
869 if (tIndex < temp.length)
871 temp[tIndex++] = annotations[i];
880 unhookAnnotation(aa);
887 * remove any object references associated with this annotation
891 private void unhookAnnotation(AlignmentAnnotation aa)
893 if (aa.sequenceRef != null)
895 aa.sequenceRef.removeAlignmentAnnotation(aa);
897 if (aa.groupRef != null)
899 // probably need to do more here in the future (post 2.5.0)
907 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
908 * AlignmentAnnotation)
911 public void addAnnotation(AlignmentAnnotation aa)
913 addAnnotation(aa, -1);
919 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
920 * AlignmentAnnotation, int)
923 public void addAnnotation(AlignmentAnnotation aa, int pos)
925 if (aa.getRNAStruc() != null)
927 hasRNAStructure = true;
931 if (annotations != null)
933 aSize = annotations.length + 1;
936 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
938 if (pos == -1 || pos >= aSize)
940 temp[aSize - 1] = aa;
949 for (i = 0; i < (aSize - 1); i++, p++)
957 temp[p] = annotations[i];
966 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
968 if (aa == null || annotations == null || annotations.length - 1 < index)
973 int aSize = annotations.length;
974 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
978 for (int i = 0; i < aSize; i++)
987 temp[i] = annotations[i];
991 temp[i] = annotations[i - 1];
1000 * returns all annotation on the alignment
1002 public AlignmentAnnotation[] getAlignmentAnnotation()
1008 public boolean isNucleotide()
1014 public boolean hasRNAStructure()
1016 // TODO can it happen that structure is removed from alignment?
1017 return hasRNAStructure;
1021 public void setDataset(AlignmentI data)
1023 if (dataset == null && data == null)
1025 createDatasetAlignment();
1027 else if (dataset == null && data != null)
1031 throw new IllegalArgumentException("Circular dataset reference");
1033 if (!(data instanceof Alignment))
1036 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1038 dataset = (Alignment) data;
1039 for (int i = 0; i < getHeight(); i++)
1041 SequenceI currentSeq = getSequenceAt(i);
1042 SequenceI dsq = currentSeq.getDatasetSequence();
1045 dsq = currentSeq.createDatasetSequence();
1046 dataset.addSequence(dsq);
1050 while (dsq.getDatasetSequence() != null)
1052 dsq = dsq.getDatasetSequence();
1054 if (dataset.findIndex(dsq) == -1)
1056 dataset.addSequence(dsq);
1061 dataset.addAlignmentRef();
1065 * add dataset sequences to seq for currentSeq and any sequences it references
1067 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1068 Set<SequenceI> seqs, boolean createDatasetSequence)
1070 SequenceI alignedSeq = currentSeq;
1071 if (currentSeq.getDatasetSequence() != null)
1073 currentSeq = currentSeq.getDatasetSequence();
1077 if (createDatasetSequence)
1079 currentSeq = currentSeq.createDatasetSequence();
1083 List<SequenceI> toProcess = new ArrayList<>();
1084 toProcess.add(currentSeq);
1085 while (toProcess.size() > 0)
1088 SequenceI curDs = toProcess.remove(0);
1090 if (!seqs.add(curDs))
1094 // iterate over database references, making sure we add forward referenced
1096 if (curDs.getDBRefs() != null)
1098 for (DBRefEntry dbr : curDs.getDBRefs())
1100 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1102 if (dbr.getMap().getTo() == alignedSeq)
1105 * update mapping to be to the newly created dataset sequence
1107 dbr.getMap().setTo(currentSeq);
1109 if (dbr.getMap().getTo().getDatasetSequence() != null)
1111 throw new Error("Implementation error: Map.getTo() for dbref "
1112 + dbr + " from " + curDs.getName()
1113 + " is not a dataset sequence.");
1115 // we recurse to add all forward references to dataset sequences via
1117 toProcess.add(dbr.getMap().getTo());
1125 * Creates a new dataset for this alignment. Can only be done once - if
1126 * dataset is not null this will not be performed.
1128 public void createDatasetAlignment()
1130 if (dataset != null)
1134 // try to avoid using SequenceI.equals at this stage, it will be expensive
1135 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1137 for (int i = 0; i < getHeight(); i++)
1139 SequenceI currentSeq = getSequenceAt(i);
1140 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1143 // verify all mappings are in dataset
1144 for (AlignedCodonFrame cf : codonFrameList)
1146 for (SequenceToSequenceMapping ssm : cf.getMappings())
1148 if (!seqs.contains(ssm.getFromSeq()))
1150 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1152 if (!seqs.contains(ssm.getMapping().getTo()))
1154 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1158 // finally construct dataset
1159 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1160 // move mappings to the dataset alignment
1161 dataset.codonFrameList = this.codonFrameList;
1162 this.codonFrameList = null;
1166 * reference count for number of alignments referencing this one.
1168 int alignmentRefs = 0;
1171 * increase reference count to this alignment.
1173 private void addAlignmentRef()
1179 public Alignment getDataset()
1185 public boolean padGaps()
1187 boolean modified = false;
1189 // Remove excess gaps from the end of alignment
1193 for (int i = 0; i < sequences.size(); i++)
1195 current = getSequenceAt(i);
1196 for (int j = current.getLength(); j > maxLength; j--)
1199 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1210 for (int i = 0; i < sequences.size(); i++)
1212 current = getSequenceAt(i);
1213 cLength = current.getLength();
1215 if (cLength < maxLength)
1217 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1220 else if (current.getLength() > maxLength)
1222 current.deleteChars(maxLength, current.getLength());
1229 * Justify the sequences to the left or right by deleting and inserting gaps
1230 * before the initial residue or after the terminal residue
1233 * true if alignment padded to right, false to justify to left
1234 * @return true if alignment was changed
1237 public boolean justify(boolean right)
1239 boolean modified = false;
1241 // Remove excess gaps from the end of alignment
1243 int ends[] = new int[sequences.size() * 2];
1245 for (int i = 0; i < sequences.size(); i++)
1247 current = getSequenceAt(i);
1248 // This should really be a sequence method
1249 ends[i * 2] = current.findIndex(current.getStart());
1250 ends[i * 2 + 1] = current
1251 .findIndex(current.getStart() + current.getLength());
1252 boolean hitres = false;
1253 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1255 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1264 ends[i * 2 + 1] = j;
1265 if (j - ends[i * 2] > maxLength)
1267 maxLength = j - ends[i * 2];
1275 // now edit the flanking gaps to justify to either left or right
1276 int cLength, extent, diff;
1277 for (int i = 0; i < sequences.size(); i++)
1279 current = getSequenceAt(i);
1281 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1282 diff = maxLength - cLength; // number of gaps to indent
1283 extent = current.getLength();
1287 if (extent > ends[i * 2 + 1])
1289 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1292 if (ends[i * 2] > diff)
1294 current.deleteChars(0, ends[i * 2] - diff);
1299 if (ends[i * 2] < diff)
1301 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1309 if (ends[i * 2] > 0)
1311 current.deleteChars(0, ends[i * 2]);
1313 ends[i * 2 + 1] -= ends[i * 2];
1314 extent -= ends[i * 2];
1316 if (extent > maxLength)
1318 current.deleteChars(maxLength + 1, extent);
1323 if (extent < maxLength)
1325 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1335 public HiddenSequences getHiddenSequences()
1337 return hiddenSequences;
1341 public HiddenColumns getHiddenColumns()
1347 public CigarArray getCompactAlignment()
1349 synchronized (sequences)
1351 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1353 for (SequenceI seq : sequences)
1355 alseqs[i++] = new SeqCigar(seq);
1357 CigarArray cal = new CigarArray(alseqs);
1358 cal.addOperation(CigarArray.M, getWidth());
1364 public void setProperty(Object key, Object value)
1366 if (alignmentProperties == null)
1368 alignmentProperties = new Hashtable();
1371 alignmentProperties.put(key, value);
1375 public Object getProperty(Object key)
1377 if (alignmentProperties != null)
1379 return alignmentProperties.get(key);
1388 public Hashtable getProperties()
1390 return alignmentProperties;
1394 * Adds the given mapping to the stored set. Note this may be held on the
1395 * dataset alignment.
1398 public void addCodonFrame(AlignedCodonFrame codons)
1400 List<AlignedCodonFrame> acfs = getCodonFrames();
1401 if (codons != null && acfs != null && !acfs.contains(codons))
1411 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1414 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1420 List<AlignedCodonFrame> cframes = new ArrayList<>();
1421 for (AlignedCodonFrame acf : getCodonFrames())
1423 if (acf.involvesSequence(seq))
1432 * Sets the codon frame mappings (replacing any existing mappings). Note the
1433 * mappings are set on the dataset alignment instead if there is one.
1435 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1438 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1440 if (dataset != null)
1442 dataset.setCodonFrames(acfs);
1446 this.codonFrameList = acfs;
1451 * Returns the set of codon frame mappings. Any changes to the returned set
1452 * will affect the alignment. The mappings are held on (and read from) the
1453 * dataset alignment if there is one.
1455 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1458 public List<AlignedCodonFrame> getCodonFrames()
1460 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1461 // this behaviour is currently incorrect. method should return codon frames
1462 // for just the alignment,
1463 // selected from dataset
1464 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1468 * Removes the given mapping from the stored set. Note that the mappings are
1469 * held on the dataset alignment if there is one.
1472 public boolean removeCodonFrame(AlignedCodonFrame codons)
1474 List<AlignedCodonFrame> acfs = getCodonFrames();
1475 if (codons == null || acfs == null)
1479 return acfs.remove(codons);
1483 public void append(AlignmentI toappend)
1485 // TODO JAL-1270 needs test coverage
1486 // currently tested for use in jalview.gui.SequenceFetcher
1487 char oldc = toappend.getGapCharacter();
1488 boolean samegap = oldc == getGapCharacter();
1489 boolean hashidden = toappend.getHiddenSequences() != null
1490 && toappend.getHiddenSequences().hiddenSequences != null;
1491 // get all sequences including any hidden ones
1492 List<SequenceI> sqs = (hashidden)
1493 ? toappend.getHiddenSequences().getFullAlignment()
1495 : toappend.getSequences();
1498 // avoid self append deadlock by
1499 List<SequenceI> toappendsq = new ArrayList<>();
1502 for (SequenceI addedsq : sqs)
1506 addedsq.replace(oldc, gapCharacter);
1508 toappendsq.add(addedsq);
1511 for (SequenceI addedsq : toappendsq)
1513 addSequence(addedsq);
1516 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1517 for (int a = 0; alan != null && a < alan.length; a++)
1519 addAnnotation(alan[a]);
1523 getCodonFrames().addAll(toappend.getCodonFrames());
1525 List<SequenceGroup> sg = toappend.getGroups();
1528 for (SequenceGroup _sg : sg)
1533 if (toappend.getHiddenSequences() != null)
1535 HiddenSequences hs = toappend.getHiddenSequences();
1536 if (hiddenSequences == null)
1538 hiddenSequences = new HiddenSequences(this);
1540 if (hs.hiddenSequences != null)
1542 for (int s = 0; s < hs.hiddenSequences.length; s++)
1544 // hide the newly appended sequence in the alignment
1545 if (hs.hiddenSequences[s] != null)
1547 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1552 if (toappend.getProperties() != null)
1554 // we really can't do very much here - just try to concatenate strings
1555 // where property collisions occur.
1556 Enumeration key = toappend.getProperties().keys();
1557 while (key.hasMoreElements())
1559 Object k = key.nextElement();
1560 Object ourval = this.getProperty(k);
1561 Object toapprop = toappend.getProperty(k);
1564 if (ourval.getClass().equals(toapprop.getClass())
1565 && !ourval.equals(toapprop))
1567 if (ourval instanceof String)
1571 ((String) ourval) + "; " + ((String) toapprop));
1575 if (ourval instanceof Vector)
1578 Enumeration theirv = ((Vector) toapprop).elements();
1579 while (theirv.hasMoreElements())
1581 ((Vector) ourval).addElement(theirv);
1589 // just add new property directly
1590 setProperty(k, toapprop);
1598 public AlignmentAnnotation findOrCreateAnnotation(String name,
1599 String calcId, boolean autoCalc, SequenceI seqRef,
1600 SequenceGroup groupRef)
1602 if (annotations != null)
1604 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1606 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1607 && (calcId == null || annot.getCalcId().equals(calcId))
1608 && annot.sequenceRef == seqRef
1609 && annot.groupRef == groupRef)
1615 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1616 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1617 annot.hasText = false;
1620 annot.setCalcId(new String(calcId));
1622 annot.autoCalculated = autoCalc;
1625 annot.setSequenceRef(seqRef);
1627 annot.groupRef = groupRef;
1628 addAnnotation(annot);
1634 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1636 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1637 if (alignmentAnnotation != null)
1639 return AlignmentAnnotation.findAnnotation(
1640 Arrays.asList(getAlignmentAnnotation()), calcId);
1642 return Arrays.asList(new AlignmentAnnotation[] {});
1646 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1647 String calcId, String label)
1649 return AlignmentAnnotation.findAnnotations(
1650 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1654 public void moveSelectedSequencesByOne(SequenceGroup sg,
1655 Map<SequenceI, SequenceCollectionI> map, boolean up)
1657 synchronized (sequences)
1662 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1664 SequenceI seq = sequences.get(i);
1665 if (!sg.getSequences(map).contains(seq))
1670 SequenceI temp = sequences.get(i - 1);
1671 if (sg.getSequences(null).contains(temp))
1676 sequences.set(i, temp);
1677 sequences.set(i - 1, seq);
1682 for (int i = sequences.size() - 2; i > -1; i--)
1684 SequenceI seq = sequences.get(i);
1685 if (!sg.getSequences(map).contains(seq))
1690 SequenceI temp = sequences.get(i + 1);
1691 if (sg.getSequences(map).contains(temp))
1696 sequences.set(i, temp);
1697 sequences.set(i + 1, seq);
1705 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1707 alignmentAnnotation.validateRangeAndDisplay();
1708 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1710 hasRNAStructure = true;
1714 private SequenceI seqrep = null;
1718 * @return the representative sequence for this group
1721 public SequenceI getSeqrep()
1727 * set the representative sequence for this group. Note - this affects the
1728 * interpretation of the Hidereps attribute.
1731 * the seqrep to set (null means no sequence representative)
1734 public void setSeqrep(SequenceI seqrep)
1736 this.seqrep = seqrep;
1741 * @return true if group has a sequence representative
1744 public boolean hasSeqrep()
1746 return seqrep != null;
1750 public int getEndRes()
1752 return getWidth() - 1;
1756 public int getStartRes()
1762 * In the case of AlignmentI - returns the dataset for the alignment, if set
1765 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1768 public AnnotatedCollectionI getContext()
1774 * Align this alignment like the given (mapped) one.
1777 public int alignAs(AlignmentI al)
1780 * Currently retains unmapped gaps (in introns), regaps mapped regions
1783 return alignAs(al, false, true);
1787 * Align this alignment 'the same as' the given one. Mapped sequences only are
1788 * realigned. If both of the same type (nucleotide/protein) then align both
1789 * identically. If this is nucleotide and the other is protein, make 3 gaps
1790 * for each gap in the protein sequences. If this is protein and the other is
1791 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1792 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1793 * protein to match the relative ordering of codons in the nucleotide.
1795 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1796 * regions are preserved. Gaps that connect introns to exons are treated
1797 * conservatively, i.e. only preserved if both intron and exon gaps are
1798 * preserved. TODO: check caveats below where the implementation fails
1801 * - must have same dataset, and sequences in al must have equivalent
1802 * dataset sequence and start/end bounds under given mapping
1803 * @param preserveMappedGaps
1804 * if true, gaps within and between mapped codons are preserved
1805 * @param preserveUnmappedGaps
1806 * if true, gaps within and between unmapped codons are preserved
1809 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1810 boolean preserveUnmappedGaps)
1812 // TODO should this method signature be the one in the interface?
1813 // JBPComment - yes - neither flag is used, so should be deleted.
1814 boolean thisIsNucleotide = this.isNucleotide();
1815 boolean thatIsProtein = !al.isNucleotide();
1816 if (!thatIsProtein && !thisIsNucleotide)
1818 return AlignmentUtils.alignProteinAsDna(this, al);
1820 else if (thatIsProtein && thisIsNucleotide)
1822 return AlignmentUtils.alignCdsAsProtein(this, al);
1824 return AlignmentUtils.alignAs(this, al);
1828 * Returns the alignment in Fasta format. Behaviour of this method is not
1829 * guaranteed between versions.
1832 public String toString()
1834 return new FastaFile().print(getSequencesArray(), true);
1838 * Returns the set of distinct sequence names. No ordering is guaranteed.
1841 public Set<String> getSequenceNames()
1843 Set<String> names = new HashSet<>();
1844 for (SequenceI seq : getSequences())
1846 names.add(seq.getName());
1852 public boolean hasValidSequence()
1854 boolean hasValidSeq = false;
1855 for (SequenceI seq : getSequences())
1857 if ((seq.getEnd() - seq.getStart()) > 0)
1867 * Update any mappings to 'virtual' sequences to compatible real ones, if
1868 * present in the added sequences. Returns a count of mappings updated.
1874 public int realiseMappings(List<SequenceI> seqs)
1877 for (SequenceI seq : seqs)
1879 for (AlignedCodonFrame mapping : getCodonFrames())
1881 count += mapping.realiseWith(seq);
1888 * Returns the first AlignedCodonFrame that has a mapping between the given
1896 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1898 for (AlignedCodonFrame acf : getCodonFrames())
1900 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1909 public boolean setHiddenColumns(HiddenColumns cols)
1911 boolean changed = cols == null ? hiddenCols != null
1912 : !cols.equals(hiddenCols);
1918 public void setupJPredAlignment()
1920 SequenceI repseq = getSequenceAt(0);
1922 HiddenColumns cs = new HiddenColumns();
1923 cs.hideList(repseq.getInsertions());
1924 setHiddenColumns(cs);
1928 public HiddenColumns propagateInsertions(SequenceI profileseq,
1929 AlignmentView input)
1933 char gc = getGapCharacter();
1934 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1935 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1936 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1937 return propagateInsertions(profileseq, origseq, nview);
1943 * sequence in al which corresponds to origseq
1945 * alignment which is to have gaps inserted into it
1947 * sequence corresponding to profileseq which defines gap map for
1950 private HiddenColumns propagateInsertions(SequenceI profileseq,
1951 SequenceI origseq, HiddenColumns hc)
1953 // take the set of hidden columns, and the set of gaps in origseq,
1954 // and remove all the hidden gaps from hiddenColumns
1956 // first get the gaps as a Bitset
1957 // then calculate hidden ^ not(gap)
1958 BitSet gaps = origseq.gapBitset();
1961 // for each sequence in the alignment, except the profile sequence,
1962 // insert gaps corresponding to each hidden region but where each hidden
1963 // column region is shifted backwards by the number of preceding visible
1964 // gaps update hidden columns at the same time
1965 HiddenColumns newhidden = new HiddenColumns();
1967 int numGapsBefore = 0;
1968 int gapPosition = 0;
1969 Iterator<int[]> it = hc.iterator();
1970 while (it.hasNext())
1972 int[] region = it.next();
1974 // get region coordinates accounting for gaps
1975 // we can rely on gaps not being *in* hidden regions because we already
1977 while (gapPosition < region[0])
1980 if (gaps.get(gapPosition))
1986 int left = region[0] - numGapsBefore;
1987 int right = region[1] - numGapsBefore;
1989 newhidden.hideColumns(left, right);
1990 padGaps(left, right, profileseq);
1996 * Pad gaps in all sequences in alignment except profileseq
1999 * position of first gap to insert
2001 * position of last gap to insert
2003 * sequence not to pad
2005 private void padGaps(int left, int right, SequenceI profileseq)
2007 char gc = getGapCharacter();
2009 // make a string with number of gaps = length of hidden region
2010 StringBuilder sb = new StringBuilder();
2011 for (int g = 0; g < right - left + 1; g++)
2016 // loop over the sequences and pad with gaps where required
2017 for (int s = 0, ns = getHeight(); s < ns; s++)
2019 SequenceI sqobj = getSequenceAt(s);
2020 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2022 String sq = sqobj.getSequenceAsString();
2024 sq.substring(0, left) + sb.toString() + sq.substring(left));