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)
198 if (i > -1 && i < sequences.size())
200 return sequences.get(i);
208 public SequenceI getSequenceAtAbsoluteIndex(int i)
210 SequenceI seq = null;
211 if (getHiddenSequences().getSize() > 0)
213 seq = getHiddenSequences().getHiddenSequence(i);
216 // didn't find the sequence in the hidden sequences, get it from the
218 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
219 seq = getSequenceAt(index);
224 seq = getSequenceAt(i);
230 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
231 * this currently does not recalculate whether or not the alignment is
232 * nucleotide, so mixed alignments may have undefined behaviour.
237 public void addSequence(SequenceI snew)
242 // maintain dataset integrity
243 SequenceI dsseq = snew.getDatasetSequence();
246 // derive new sequence
247 SequenceI adding = snew.deriveSequence();
249 dsseq = snew.getDatasetSequence();
251 if (getDataset().findIndex(dsseq) == -1)
253 getDataset().addSequence(dsseq);
257 if (sequences == null)
259 initAlignment(new SequenceI[] { snew });
263 synchronized (sequences)
268 if (hiddenSequences != null)
270 hiddenSequences.adjustHeightSequenceAdded();
275 public SequenceI replaceSequenceAt(int i, SequenceI snew)
277 synchronized (sequences)
279 if (sequences.size() > i)
281 return sequences.set(i, snew);
287 hiddenSequences.adjustHeightSequenceAdded();
296 * @return DOCUMENT ME!
299 public List<SequenceGroup> getGroups()
307 if (getDataset() != null)
311 getDataset().removeAlignmentRef();
312 } catch (Throwable e)
322 * Defensively nulls out references in case this object is not garbage
325 void nullReferences()
331 hiddenSequences = null;
335 * decrement the alignmentRefs counter by one and null references if it goes
340 private void removeAlignmentRef() throws Throwable
342 if (--alignmentRefs == 0)
349 public void deleteSequence(SequenceI s)
351 synchronized (sequences)
353 deleteSequence(findIndex(s));
358 public void deleteSequence(int i)
360 synchronized (sequences)
362 if (i > -1 && i < getHeight())
365 hiddenSequences.adjustHeightSequenceDeleted(i);
371 public void deleteHiddenSequence(int i)
373 synchronized (sequences)
375 if (i > -1 && i < getHeight())
385 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
388 public SequenceGroup findGroup(SequenceI seq, int position)
390 synchronized (groups)
392 for (SequenceGroup sg : groups)
394 if (sg.getSequences(null).contains(seq))
396 if (position >= sg.getStartRes() && position <= sg.getEndRes())
410 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
413 public SequenceGroup[] findAllGroups(SequenceI s)
415 ArrayList<SequenceGroup> temp = new ArrayList<>();
417 synchronized (groups)
419 int gSize = groups.size();
420 for (int i = 0; i < gSize; i++)
422 SequenceGroup sg = groups.get(i);
423 if (sg == null || sg.getSequences() == null)
425 this.deleteGroup(sg);
430 if (sg.getSequences().contains(s))
436 SequenceGroup[] ret = new SequenceGroup[temp.size()];
437 return temp.toArray(ret);
442 public void addGroup(SequenceGroup sg)
444 synchronized (groups)
446 if (!groups.contains(sg))
448 if (hiddenSequences.getSize() > 0)
450 int i, iSize = sg.getSize();
451 for (i = 0; i < iSize; i++)
453 if (!sequences.contains(sg.getSequenceAt(i)))
455 sg.deleteSequence(sg.getSequenceAt(i), false);
461 if (sg.getSize() < 1)
466 sg.setContext(this, true);
473 * remove any annotation that references gp
476 * (if null, removes all group associated annotation)
478 private void removeAnnotationForGroup(SequenceGroup gp)
480 if (annotations == null || annotations.length == 0)
484 // remove annotation very quickly
485 AlignmentAnnotation[] t,
486 todelete = new AlignmentAnnotation[annotations.length],
487 tokeep = new AlignmentAnnotation[annotations.length];
491 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
493 if (annotations[i].groupRef != null)
495 todelete[p++] = annotations[i];
499 tokeep[k++] = annotations[i];
505 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
507 if (annotations[i].groupRef == gp)
509 todelete[p++] = annotations[i];
513 tokeep[k++] = annotations[i];
519 // clear out the group associated annotation.
520 for (i = 0; i < p; i++)
522 unhookAnnotation(todelete[i]);
525 t = new AlignmentAnnotation[k];
526 for (i = 0; i < k; i++)
535 public void deleteAllGroups()
537 synchronized (groups)
539 if (annotations != null)
541 removeAnnotationForGroup(null);
543 for (SequenceGroup sg : groups)
545 sg.setContext(null, false);
553 public void deleteGroup(SequenceGroup g)
555 synchronized (groups)
557 if (groups.contains(g))
559 removeAnnotationForGroup(g);
561 g.setContext(null, false);
568 public SequenceI findName(String name)
570 return findName(name, false);
576 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
579 public SequenceI findName(String token, boolean b)
581 return findName(null, token, b);
587 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
591 public SequenceI findName(SequenceI startAfter, String token, boolean b)
596 String sqname = null;
597 if (startAfter != null)
599 // try to find the sequence in the alignment
600 boolean matched = false;
601 while (i < sequences.size())
603 if (getSequenceAt(i++) == startAfter)
614 while (i < sequences.size())
616 sq = getSequenceAt(i);
617 sqname = sq.getName();
618 if (sqname.equals(token) // exact match
619 || (b && // allow imperfect matches - case varies
620 (sqname.equalsIgnoreCase(token))))
622 return getSequenceAt(i);
632 public SequenceI[] findSequenceMatch(String name)
634 Vector matches = new Vector();
637 while (i < sequences.size())
639 if (getSequenceAt(i).getName().equals(name))
641 matches.addElement(getSequenceAt(i));
646 SequenceI[] result = new SequenceI[matches.size()];
647 for (i = 0; i < result.length; i++)
649 result[i] = (SequenceI) matches.elementAt(i);
659 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
662 public int findIndex(SequenceI s)
666 while (i < sequences.size())
668 if (s == getSequenceAt(i))
683 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
686 public int findIndex(SearchResultsI results)
690 while (i < sequences.size())
692 if (results.involvesSequence(getSequenceAt(i)))
702 public int getHeight()
704 return sequences.size();
708 public int getAbsoluteHeight()
710 return sequences.size() + getHiddenSequences().getSize();
714 public int getWidth()
718 for (int i = 0; i < sequences.size(); i++)
720 maxLength = Math.max(maxLength, getSequenceAt(i).getLength());
726 public int getVisibleWidth()
729 if (hiddenCols != null)
731 w -= hiddenCols.getSize();
743 public void setGapCharacter(char gc)
746 synchronized (sequences)
748 for (SequenceI seq : sequences)
750 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
751 .replace('-', gc).replace(' ', gc));
759 * @return DOCUMENT ME!
762 public char getGapCharacter()
770 * @see jalview.datamodel.AlignmentI#isAligned()
773 public boolean isAligned()
775 return isAligned(false);
781 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
784 public boolean isAligned(boolean includeHidden)
786 int width = getWidth();
787 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
789 includeHidden = true; // no hidden sequences to check against.
791 for (int i = 0; i < sequences.size(); i++)
793 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
795 if (getSequenceAt(i).getLength() != width)
806 public boolean isHidden(int alignmentIndex)
808 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
812 * Delete all annotations, including auto-calculated if the flag is set true.
813 * Returns true if at least one annotation was deleted, else false.
815 * @param includingAutoCalculated
819 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
821 boolean result = false;
822 for (AlignmentAnnotation alan : getAlignmentAnnotation())
824 if (!alan.autoCalculated || includingAutoCalculated)
826 deleteAnnotation(alan);
836 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
837 * AlignmentAnnotation)
840 public boolean deleteAnnotation(AlignmentAnnotation aa)
842 return deleteAnnotation(aa, true);
846 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
850 if (annotations != null)
852 aSize = annotations.length;
860 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
862 boolean swap = false;
865 for (int i = 0; i < aSize; i++)
867 if (annotations[i] == aa)
872 if (tIndex < temp.length)
874 temp[tIndex++] = annotations[i];
883 unhookAnnotation(aa);
890 * remove any object references associated with this annotation
894 private void unhookAnnotation(AlignmentAnnotation aa)
896 if (aa.sequenceRef != null)
898 aa.sequenceRef.removeAlignmentAnnotation(aa);
900 if (aa.groupRef != null)
902 // probably need to do more here in the future (post 2.5.0)
910 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
911 * AlignmentAnnotation)
914 public void addAnnotation(AlignmentAnnotation aa)
916 addAnnotation(aa, -1);
922 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
923 * AlignmentAnnotation, int)
926 public void addAnnotation(AlignmentAnnotation aa, int pos)
928 if (aa.getRNAStruc() != null)
930 hasRNAStructure = true;
934 if (annotations != null)
936 aSize = annotations.length + 1;
939 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
941 if (pos == -1 || pos >= aSize)
943 temp[aSize - 1] = aa;
952 for (i = 0; i < (aSize - 1); i++, p++)
960 temp[p] = annotations[i];
969 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
971 if (aa == null || annotations == null || annotations.length - 1 < index)
976 int aSize = annotations.length;
977 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
981 for (int i = 0; i < aSize; i++)
990 temp[i] = annotations[i];
994 temp[i] = annotations[i - 1];
1003 * returns all annotation on the alignment
1005 public AlignmentAnnotation[] getAlignmentAnnotation()
1011 public boolean isNucleotide()
1017 public boolean hasRNAStructure()
1019 // TODO can it happen that structure is removed from alignment?
1020 return hasRNAStructure;
1024 public void setDataset(AlignmentI data)
1026 if (dataset == null && data == null)
1028 createDatasetAlignment();
1030 else if (dataset == null && data != null)
1034 throw new IllegalArgumentException("Circular dataset reference");
1036 if (!(data instanceof Alignment))
1039 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1041 dataset = (Alignment) data;
1042 for (int i = 0; i < getHeight(); i++)
1044 SequenceI currentSeq = getSequenceAt(i);
1045 SequenceI dsq = currentSeq.getDatasetSequence();
1048 dsq = currentSeq.createDatasetSequence();
1049 dataset.addSequence(dsq);
1053 while (dsq.getDatasetSequence() != null)
1055 dsq = dsq.getDatasetSequence();
1057 if (dataset.findIndex(dsq) == -1)
1059 dataset.addSequence(dsq);
1064 dataset.addAlignmentRef();
1068 * add dataset sequences to seq for currentSeq and any sequences it references
1070 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1071 Set<SequenceI> seqs, boolean createDatasetSequence)
1073 SequenceI alignedSeq = currentSeq;
1074 if (currentSeq.getDatasetSequence() != null)
1076 currentSeq = currentSeq.getDatasetSequence();
1080 if (createDatasetSequence)
1082 currentSeq = currentSeq.createDatasetSequence();
1086 List<SequenceI> toProcess = new ArrayList<>();
1087 toProcess.add(currentSeq);
1088 while (toProcess.size() > 0)
1091 SequenceI curDs = toProcess.remove(0);
1093 if (!seqs.add(curDs))
1097 // iterate over database references, making sure we add forward referenced
1099 if (curDs.getDBRefs() != null)
1101 for (DBRefEntry dbr : curDs.getDBRefs())
1103 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1105 if (dbr.getMap().getTo() == alignedSeq)
1108 * update mapping to be to the newly created dataset sequence
1110 dbr.getMap().setTo(currentSeq);
1112 if (dbr.getMap().getTo().getDatasetSequence() != null)
1114 throw new Error("Implementation error: Map.getTo() for dbref "
1115 + dbr + " from " + curDs.getName()
1116 + " is not a dataset sequence.");
1118 // we recurse to add all forward references to dataset sequences via
1120 toProcess.add(dbr.getMap().getTo());
1128 * Creates a new dataset for this alignment. Can only be done once - if
1129 * dataset is not null this will not be performed.
1131 public void createDatasetAlignment()
1133 if (dataset != null)
1137 // try to avoid using SequenceI.equals at this stage, it will be expensive
1138 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1140 for (int i = 0; i < getHeight(); i++)
1142 SequenceI currentSeq = getSequenceAt(i);
1143 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1146 // verify all mappings are in dataset
1147 for (AlignedCodonFrame cf : codonFrameList)
1149 for (SequenceToSequenceMapping ssm : cf.getMappings())
1151 if (!seqs.contains(ssm.getFromSeq()))
1153 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1155 if (!seqs.contains(ssm.getMapping().getTo()))
1157 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1161 // finally construct dataset
1162 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1163 // move mappings to the dataset alignment
1164 dataset.codonFrameList = this.codonFrameList;
1165 this.codonFrameList = null;
1169 * reference count for number of alignments referencing this one.
1171 int alignmentRefs = 0;
1174 * increase reference count to this alignment.
1176 private void addAlignmentRef()
1182 public Alignment getDataset()
1188 public boolean padGaps()
1190 boolean modified = false;
1192 // Remove excess gaps from the end of alignment
1196 for (int i = 0; i < sequences.size(); i++)
1198 current = getSequenceAt(i);
1199 for (int j = current.getLength(); j > maxLength; j--)
1202 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1213 for (int i = 0; i < sequences.size(); i++)
1215 current = getSequenceAt(i);
1216 cLength = current.getLength();
1218 if (cLength < maxLength)
1220 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1223 else if (current.getLength() > maxLength)
1225 current.deleteChars(maxLength, current.getLength());
1232 * Justify the sequences to the left or right by deleting and inserting gaps
1233 * before the initial residue or after the terminal residue
1236 * true if alignment padded to right, false to justify to left
1237 * @return true if alignment was changed
1240 public boolean justify(boolean right)
1242 boolean modified = false;
1244 // Remove excess gaps from the end of alignment
1246 int ends[] = new int[sequences.size() * 2];
1248 for (int i = 0; i < sequences.size(); i++)
1250 current = getSequenceAt(i);
1251 // This should really be a sequence method
1252 ends[i * 2] = current.findIndex(current.getStart());
1253 ends[i * 2 + 1] = current
1254 .findIndex(current.getStart() + current.getLength());
1255 boolean hitres = false;
1256 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1258 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1267 ends[i * 2 + 1] = j;
1268 if (j - ends[i * 2] > maxLength)
1270 maxLength = j - ends[i * 2];
1278 // now edit the flanking gaps to justify to either left or right
1279 int cLength, extent, diff;
1280 for (int i = 0; i < sequences.size(); i++)
1282 current = getSequenceAt(i);
1284 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1285 diff = maxLength - cLength; // number of gaps to indent
1286 extent = current.getLength();
1290 if (extent > ends[i * 2 + 1])
1292 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1295 if (ends[i * 2] > diff)
1297 current.deleteChars(0, ends[i * 2] - diff);
1302 if (ends[i * 2] < diff)
1304 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1312 if (ends[i * 2] > 0)
1314 current.deleteChars(0, ends[i * 2]);
1316 ends[i * 2 + 1] -= ends[i * 2];
1317 extent -= ends[i * 2];
1319 if (extent > maxLength)
1321 current.deleteChars(maxLength + 1, extent);
1326 if (extent < maxLength)
1328 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1338 public HiddenSequences getHiddenSequences()
1340 return hiddenSequences;
1344 public HiddenColumns getHiddenColumns()
1350 public CigarArray getCompactAlignment()
1352 synchronized (sequences)
1354 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1356 for (SequenceI seq : sequences)
1358 alseqs[i++] = new SeqCigar(seq);
1360 CigarArray cal = new CigarArray(alseqs);
1361 cal.addOperation(CigarArray.M, getWidth());
1367 public void setProperty(Object key, Object value)
1369 if (alignmentProperties == null)
1371 alignmentProperties = new Hashtable();
1374 alignmentProperties.put(key, value);
1378 public Object getProperty(Object key)
1380 if (alignmentProperties != null)
1382 return alignmentProperties.get(key);
1391 public Hashtable getProperties()
1393 return alignmentProperties;
1397 * Adds the given mapping to the stored set. Note this may be held on the
1398 * dataset alignment.
1401 public void addCodonFrame(AlignedCodonFrame codons)
1403 List<AlignedCodonFrame> acfs = getCodonFrames();
1404 if (codons != null && acfs != null && !acfs.contains(codons))
1414 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1417 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1423 List<AlignedCodonFrame> cframes = new ArrayList<>();
1424 for (AlignedCodonFrame acf : getCodonFrames())
1426 if (acf.involvesSequence(seq))
1435 * Sets the codon frame mappings (replacing any existing mappings). Note the
1436 * mappings are set on the dataset alignment instead if there is one.
1438 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1441 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1443 if (dataset != null)
1445 dataset.setCodonFrames(acfs);
1449 this.codonFrameList = acfs;
1454 * Returns the set of codon frame mappings. Any changes to the returned set
1455 * will affect the alignment. The mappings are held on (and read from) the
1456 * dataset alignment if there is one.
1458 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1461 public List<AlignedCodonFrame> getCodonFrames()
1463 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1464 // this behaviour is currently incorrect. method should return codon frames
1465 // for just the alignment,
1466 // selected from dataset
1467 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1471 * Removes the given mapping from the stored set. Note that the mappings are
1472 * held on the dataset alignment if there is one.
1475 public boolean removeCodonFrame(AlignedCodonFrame codons)
1477 List<AlignedCodonFrame> acfs = getCodonFrames();
1478 if (codons == null || acfs == null)
1482 return acfs.remove(codons);
1486 public void append(AlignmentI toappend)
1488 // TODO JAL-1270 needs test coverage
1489 // currently tested for use in jalview.gui.SequenceFetcher
1490 char oldc = toappend.getGapCharacter();
1491 boolean samegap = oldc == getGapCharacter();
1492 boolean hashidden = toappend.getHiddenSequences() != null
1493 && toappend.getHiddenSequences().hiddenSequences != null;
1494 // get all sequences including any hidden ones
1495 List<SequenceI> sqs = (hashidden)
1496 ? toappend.getHiddenSequences().getFullAlignment()
1498 : toappend.getSequences();
1501 // avoid self append deadlock by
1502 List<SequenceI> toappendsq = new ArrayList<>();
1505 for (SequenceI addedsq : sqs)
1509 addedsq.replace(oldc, gapCharacter);
1511 toappendsq.add(addedsq);
1514 for (SequenceI addedsq : toappendsq)
1516 addSequence(addedsq);
1519 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1520 for (int a = 0; alan != null && a < alan.length; a++)
1522 addAnnotation(alan[a]);
1526 getCodonFrames().addAll(toappend.getCodonFrames());
1528 List<SequenceGroup> sg = toappend.getGroups();
1531 for (SequenceGroup _sg : sg)
1536 if (toappend.getHiddenSequences() != null)
1538 HiddenSequences hs = toappend.getHiddenSequences();
1539 if (hiddenSequences == null)
1541 hiddenSequences = new HiddenSequences(this);
1543 if (hs.hiddenSequences != null)
1545 for (int s = 0; s < hs.hiddenSequences.length; s++)
1547 // hide the newly appended sequence in the alignment
1548 if (hs.hiddenSequences[s] != null)
1550 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1555 if (toappend.getProperties() != null)
1557 // we really can't do very much here - just try to concatenate strings
1558 // where property collisions occur.
1559 Enumeration key = toappend.getProperties().keys();
1560 while (key.hasMoreElements())
1562 Object k = key.nextElement();
1563 Object ourval = this.getProperty(k);
1564 Object toapprop = toappend.getProperty(k);
1567 if (ourval.getClass().equals(toapprop.getClass())
1568 && !ourval.equals(toapprop))
1570 if (ourval instanceof String)
1574 ((String) ourval) + "; " + ((String) toapprop));
1578 if (ourval instanceof Vector)
1581 Enumeration theirv = ((Vector) toapprop).elements();
1582 while (theirv.hasMoreElements())
1584 ((Vector) ourval).addElement(theirv);
1592 // just add new property directly
1593 setProperty(k, toapprop);
1601 public AlignmentAnnotation findOrCreateAnnotation(String name,
1602 String calcId, boolean autoCalc, SequenceI seqRef,
1603 SequenceGroup groupRef)
1605 if (annotations != null)
1607 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1609 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1610 && (calcId == null || annot.getCalcId().equals(calcId))
1611 && annot.sequenceRef == seqRef
1612 && annot.groupRef == groupRef)
1618 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1619 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1620 annot.hasText = false;
1623 annot.setCalcId(new String(calcId));
1625 annot.autoCalculated = autoCalc;
1628 annot.setSequenceRef(seqRef);
1630 annot.groupRef = groupRef;
1631 addAnnotation(annot);
1637 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1639 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1640 if (alignmentAnnotation != null)
1642 return AlignmentAnnotation.findAnnotation(
1643 Arrays.asList(getAlignmentAnnotation()), calcId);
1645 return Arrays.asList(new AlignmentAnnotation[] {});
1649 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1650 String calcId, String label)
1652 return AlignmentAnnotation.findAnnotations(
1653 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1657 public void moveSelectedSequencesByOne(SequenceGroup sg,
1658 Map<SequenceI, SequenceCollectionI> map, boolean up)
1660 synchronized (sequences)
1665 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1667 SequenceI seq = sequences.get(i);
1668 if (!sg.getSequences(map).contains(seq))
1673 SequenceI temp = sequences.get(i - 1);
1674 if (sg.getSequences(null).contains(temp))
1679 sequences.set(i, temp);
1680 sequences.set(i - 1, seq);
1685 for (int i = sequences.size() - 2; i > -1; i--)
1687 SequenceI seq = sequences.get(i);
1688 if (!sg.getSequences(map).contains(seq))
1693 SequenceI temp = sequences.get(i + 1);
1694 if (sg.getSequences(map).contains(temp))
1699 sequences.set(i, temp);
1700 sequences.set(i + 1, seq);
1708 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1710 alignmentAnnotation.validateRangeAndDisplay();
1711 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1713 hasRNAStructure = true;
1717 private SequenceI seqrep = null;
1721 * @return the representative sequence for this group
1724 public SequenceI getSeqrep()
1730 * set the representative sequence for this group. Note - this affects the
1731 * interpretation of the Hidereps attribute.
1734 * the seqrep to set (null means no sequence representative)
1737 public void setSeqrep(SequenceI seqrep)
1739 this.seqrep = seqrep;
1744 * @return true if group has a sequence representative
1747 public boolean hasSeqrep()
1749 return seqrep != null;
1753 public int getEndRes()
1755 return getWidth() - 1;
1759 public int getStartRes()
1765 * In the case of AlignmentI - returns the dataset for the alignment, if set
1768 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1771 public AnnotatedCollectionI getContext()
1777 * Align this alignment like the given (mapped) one.
1780 public int alignAs(AlignmentI al)
1783 * Currently retains unmapped gaps (in introns), regaps mapped regions
1786 return alignAs(al, false, true);
1790 * Align this alignment 'the same as' the given one. Mapped sequences only are
1791 * realigned. If both of the same type (nucleotide/protein) then align both
1792 * identically. If this is nucleotide and the other is protein, make 3 gaps
1793 * for each gap in the protein sequences. If this is protein and the other is
1794 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1795 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1796 * protein to match the relative ordering of codons in the nucleotide.
1798 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1799 * regions are preserved. Gaps that connect introns to exons are treated
1800 * conservatively, i.e. only preserved if both intron and exon gaps are
1801 * preserved. TODO: check caveats below where the implementation fails
1804 * - must have same dataset, and sequences in al must have equivalent
1805 * dataset sequence and start/end bounds under given mapping
1806 * @param preserveMappedGaps
1807 * if true, gaps within and between mapped codons are preserved
1808 * @param preserveUnmappedGaps
1809 * if true, gaps within and between unmapped codons are preserved
1812 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1813 boolean preserveUnmappedGaps)
1815 // TODO should this method signature be the one in the interface?
1816 // JBPComment - yes - neither flag is used, so should be deleted.
1817 boolean thisIsNucleotide = this.isNucleotide();
1818 boolean thatIsProtein = !al.isNucleotide();
1819 if (!thatIsProtein && !thisIsNucleotide)
1821 return AlignmentUtils.alignProteinAsDna(this, al);
1823 else if (thatIsProtein && thisIsNucleotide)
1825 return AlignmentUtils.alignCdsAsProtein(this, al);
1827 return AlignmentUtils.alignAs(this, al);
1831 * Returns the alignment in Fasta format. Behaviour of this method is not
1832 * guaranteed between versions.
1835 public String toString()
1837 return new FastaFile().print(getSequencesArray(), true);
1841 * Returns the set of distinct sequence names. No ordering is guaranteed.
1844 public Set<String> getSequenceNames()
1846 Set<String> names = new HashSet<>();
1847 for (SequenceI seq : getSequences())
1849 names.add(seq.getName());
1855 public boolean hasValidSequence()
1857 boolean hasValidSeq = false;
1858 for (SequenceI seq : getSequences())
1860 if ((seq.getEnd() - seq.getStart()) > 0)
1870 * Update any mappings to 'virtual' sequences to compatible real ones, if
1871 * present in the added sequences. Returns a count of mappings updated.
1877 public int realiseMappings(List<SequenceI> seqs)
1880 for (SequenceI seq : seqs)
1882 for (AlignedCodonFrame mapping : getCodonFrames())
1884 count += mapping.realiseWith(seq);
1891 * Returns the first AlignedCodonFrame that has a mapping between the given
1899 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1901 for (AlignedCodonFrame acf : getCodonFrames())
1903 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1912 public boolean setHiddenColumns(HiddenColumns cols)
1914 boolean changed = cols == null ? hiddenCols != null
1915 : !cols.equals(hiddenCols);
1921 public void setupJPredAlignment()
1923 SequenceI repseq = getSequenceAt(0);
1925 HiddenColumns cs = new HiddenColumns();
1926 cs.hideList(repseq.getInsertions());
1927 setHiddenColumns(cs);
1931 public HiddenColumns propagateInsertions(SequenceI profileseq,
1932 AlignmentView input)
1936 char gc = getGapCharacter();
1937 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1938 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1939 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1940 return propagateInsertions(profileseq, origseq, nview);
1946 * sequence in al which corresponds to origseq
1948 * alignment which is to have gaps inserted into it
1950 * sequence corresponding to profileseq which defines gap map for
1953 private HiddenColumns propagateInsertions(SequenceI profileseq,
1954 SequenceI origseq, HiddenColumns hc)
1956 // take the set of hidden columns, and the set of gaps in origseq,
1957 // and remove all the hidden gaps from hiddenColumns
1959 // first get the gaps as a Bitset
1960 // then calculate hidden ^ not(gap)
1961 BitSet gaps = origseq.gapBitset();
1964 // for each sequence in the alignment, except the profile sequence,
1965 // insert gaps corresponding to each hidden region but where each hidden
1966 // column region is shifted backwards by the number of preceding visible
1967 // gaps update hidden columns at the same time
1968 HiddenColumns newhidden = new HiddenColumns();
1970 int numGapsBefore = 0;
1971 int gapPosition = 0;
1972 Iterator<int[]> it = hc.iterator();
1973 while (it.hasNext())
1975 int[] region = it.next();
1977 // get region coordinates accounting for gaps
1978 // we can rely on gaps not being *in* hidden regions because we already
1980 while (gapPosition < region[0])
1983 if (gaps.get(gapPosition))
1989 int left = region[0] - numGapsBefore;
1990 int right = region[1] - numGapsBefore;
1992 newhidden.hideColumns(left, right);
1993 padGaps(left, right, profileseq);
1999 * Pad gaps in all sequences in alignment except profileseq
2002 * position of first gap to insert
2004 * position of last gap to insert
2006 * sequence not to pad
2008 private void padGaps(int left, int right, SequenceI profileseq)
2010 char gc = getGapCharacter();
2012 // make a string with number of gaps = length of hidden region
2013 StringBuilder sb = new StringBuilder();
2014 for (int g = 0; g < right - left + 1; g++)
2019 // loop over the sequences and pad with gaps where required
2020 for (int s = 0, ns = getHeight(); s < ns; s++)
2022 SequenceI sqobj = getSequenceAt(s);
2023 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2025 String sq = sqobj.getSequenceAsString();
2027 sq.substring(0, left) + sb.toString() + sq.substring(left));