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.HashMap;
36 import java.util.HashSet;
37 import java.util.Hashtable;
38 import java.util.Iterator;
39 import java.util.List;
42 import java.util.Vector;
45 * Data structure to hold and manipulate a multiple sequence alignment
51 public class Alignment implements AlignmentI
53 private Alignment dataset;
55 private List<SequenceI> sequences;
57 protected List<SequenceGroup> groups;
59 protected char gapCharacter = '-';
61 private boolean nucleotide = true;
63 public boolean hasRNAStructure = false;
65 public AlignmentAnnotation[] annotations;
67 HiddenSequences hiddenSequences;
69 HiddenColumns hiddenCols;
71 public Hashtable alignmentProperties;
73 private List<AlignedCodonFrame> codonFrameList;
75 private void initAlignment(SequenceI[] seqs)
77 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
78 hiddenSequences = new HiddenSequences(this);
79 hiddenCols = new HiddenColumns();
80 codonFrameList = new ArrayList<>();
82 nucleotide = Comparison.isNucleotide(seqs);
84 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
86 for (int i = 0; i < seqs.length; i++)
88 sequences.add(seqs[i]);
94 * Make a 'copy' alignment - sequences have new copies of features and
95 * annotations, but share the original dataset sequences.
97 public Alignment(AlignmentI al)
99 SequenceI[] seqs = al.getSequencesArray();
100 for (int i = 0; i < seqs.length; i++)
102 seqs[i] = new Sequence(seqs[i]);
108 * Share the same dataset sequence mappings (if any).
110 if (dataset == null && al.getDataset() == null)
112 this.setCodonFrames(al.getCodonFrames());
117 * Make an alignment from an array of Sequences.
121 public Alignment(SequenceI[] seqs)
127 * Make a new alignment from an array of SeqCigars
132 public Alignment(SeqCigar[] alseqs)
134 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
135 gapCharacter, new HiddenColumns(), null);
140 * Make a new alignment from an CigarArray JBPNote - can only do this when
141 * compactAlignment does not contain hidden regions. JBPNote - must also check
142 * that compactAlignment resolves to a set of SeqCigars - or construct them
145 * @param compactAlignment
148 public static AlignmentI createAlignment(CigarArray compactAlignment)
150 throw new Error(MessageManager
151 .getString("error.alignment_cigararray_not_implemented"));
152 // this(compactAlignment.refCigars);
156 public List<SequenceI> getSequences()
162 public List<SequenceI> getSequences(
163 Map<SequenceI, SequenceCollectionI> hiddenReps)
165 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
171 public SequenceI[] getSequencesArray()
173 if (sequences == null)
177 synchronized (sequences)
179 return sequences.toArray(new SequenceI[sequences.size()]);
184 * Returns a map of lists of sequences keyed by sequence name.
189 public Map<String, List<SequenceI>> getSequencesByName()
191 return AlignmentUtils.getSequencesByName(this);
195 public SequenceI getSequenceAt(int i)
197 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 if (startAfter != null)
595 // try to find the sequence in the alignment
596 boolean matched = false;
597 while (i < sequences.size())
599 if (getSequenceAt(i++) == startAfter)
610 while (i < sequences.size())
612 sq = getSequenceAt(i);
613 sqname = sq.getName();
614 if (sqname.equals(token) // exact match
615 || (b && // allow imperfect matches - case varies
616 (sqname.equalsIgnoreCase(token))))
618 return getSequenceAt(i);
628 public SequenceI[] findSequenceMatch(String name)
630 Vector matches = new Vector();
633 while (i < sequences.size())
635 if (getSequenceAt(i).getName().equals(name))
637 matches.addElement(getSequenceAt(i));
642 SequenceI[] result = new SequenceI[matches.size()];
643 for (i = 0; i < result.length; i++)
645 result[i] = (SequenceI) matches.elementAt(i);
655 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
658 public int findIndex(SequenceI s)
662 while (i < sequences.size())
664 if (s == getSequenceAt(i))
679 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
682 public int findIndex(SearchResultsI results)
686 while (i < sequences.size())
688 if (results.involvesSequence(getSequenceAt(i)))
698 public int getHeight()
700 return sequences.size();
704 public int getAbsoluteHeight()
706 return sequences.size() + getHiddenSequences().getSize();
710 public int getWidth()
714 for (int i = 0; i < sequences.size(); i++)
716 maxLength = Math.max(maxLength, getSequenceAt(i).getLength());
722 public int getVisibleWidth()
725 if (hiddenCols != null)
727 w -= hiddenCols.getSize();
739 public void setGapCharacter(char gc)
742 synchronized (sequences)
744 for (SequenceI seq : sequences)
746 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
747 .replace('-', gc).replace(' ', gc));
755 * @return DOCUMENT ME!
758 public char getGapCharacter()
766 * @see jalview.datamodel.AlignmentI#isAligned()
769 public boolean isAligned()
771 return isAligned(false);
777 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
780 public boolean isAligned(boolean includeHidden)
782 int width = getWidth();
783 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
785 includeHidden = true; // no hidden sequences to check against.
787 for (int i = 0; i < sequences.size(); i++)
789 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
791 if (getSequenceAt(i).getLength() != width)
802 public boolean isHidden(int alignmentIndex)
804 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
808 * Delete all annotations, including auto-calculated if the flag is set true.
809 * Returns true if at least one annotation was deleted, else false.
811 * @param includingAutoCalculated
815 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
817 boolean result = false;
818 for (AlignmentAnnotation alan : getAlignmentAnnotation())
820 if (!alan.autoCalculated || includingAutoCalculated)
822 deleteAnnotation(alan);
832 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
833 * AlignmentAnnotation)
836 public boolean deleteAnnotation(AlignmentAnnotation aa)
838 return deleteAnnotation(aa, true);
842 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
846 if (annotations != null)
848 aSize = annotations.length;
856 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
858 boolean swap = false;
861 for (int i = 0; i < aSize; i++)
863 if (annotations[i] == aa)
868 if (tIndex < temp.length)
870 temp[tIndex++] = annotations[i];
879 unhookAnnotation(aa);
886 * remove any object references associated with this annotation
890 private void unhookAnnotation(AlignmentAnnotation aa)
892 if (aa.sequenceRef != null)
894 aa.sequenceRef.removeAlignmentAnnotation(aa);
896 if (aa.groupRef != null)
898 // probably need to do more here in the future (post 2.5.0)
906 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
907 * AlignmentAnnotation)
910 public void addAnnotation(AlignmentAnnotation aa)
912 addAnnotation(aa, -1);
918 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
919 * AlignmentAnnotation, int)
922 public void addAnnotation(AlignmentAnnotation aa, int pos)
924 if (aa.getRNAStruc() != null)
926 hasRNAStructure = true;
930 if (annotations != null)
932 aSize = annotations.length + 1;
935 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
937 if (pos == -1 || pos >= aSize)
939 temp[aSize - 1] = aa;
948 for (i = 0; i < (aSize - 1); i++, p++)
956 temp[p] = annotations[i];
965 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
967 if (aa == null || annotations == null || annotations.length - 1 < index)
972 int aSize = annotations.length;
973 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
977 for (int i = 0; i < aSize; i++)
986 temp[i] = annotations[i];
990 temp[i] = annotations[i - 1];
999 * returns all annotation on the alignment
1001 public AlignmentAnnotation[] getAlignmentAnnotation()
1007 public boolean isNucleotide()
1013 public boolean hasRNAStructure()
1015 // TODO can it happen that structure is removed from alignment?
1016 return hasRNAStructure;
1020 public void setDataset(AlignmentI data)
1022 if (dataset == null && data == null)
1024 createDatasetAlignment();
1026 else if (dataset == null && data != null)
1030 throw new IllegalArgumentException("Circular dataset reference");
1032 if (!(data instanceof Alignment))
1035 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1037 dataset = (Alignment) data;
1038 for (int i = 0; i < getHeight(); i++)
1040 SequenceI currentSeq = getSequenceAt(i);
1041 SequenceI dsq = currentSeq.getDatasetSequence();
1044 dsq = currentSeq.createDatasetSequence();
1045 dataset.addSequence(dsq);
1049 while (dsq.getDatasetSequence() != null)
1051 dsq = dsq.getDatasetSequence();
1053 if (dataset.findIndex(dsq) == -1)
1055 dataset.addSequence(dsq);
1060 dataset.addAlignmentRef();
1064 * add dataset sequences to seq for currentSeq and any sequences it references
1066 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1067 Set<SequenceI> seqs, boolean createDatasetSequence)
1069 SequenceI alignedSeq = currentSeq;
1070 if (currentSeq.getDatasetSequence() != null)
1072 currentSeq = currentSeq.getDatasetSequence();
1076 if (createDatasetSequence)
1078 currentSeq = currentSeq.createDatasetSequence();
1082 List<SequenceI> toProcess = new ArrayList<>();
1083 toProcess.add(currentSeq);
1084 while (toProcess.size() > 0)
1087 SequenceI curDs = toProcess.remove(0);
1089 if (!seqs.add(curDs))
1093 // iterate over database references, making sure we add forward referenced
1095 if (curDs.getDBRefs() != null)
1097 for (DBRefEntry dbr : curDs.getDBRefs())
1099 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1101 if (dbr.getMap().getTo() == alignedSeq)
1104 * update mapping to be to the newly created dataset sequence
1106 dbr.getMap().setTo(currentSeq);
1108 if (dbr.getMap().getTo().getDatasetSequence() != null)
1110 throw new Error("Implementation error: Map.getTo() for dbref "
1111 + dbr + " from " + curDs.getName()
1112 + " is not a dataset sequence.");
1114 // we recurse to add all forward references to dataset sequences via
1116 toProcess.add(dbr.getMap().getTo());
1124 * Creates a new dataset for this alignment. Can only be done once - if
1125 * dataset is not null this will not be performed.
1127 public void createDatasetAlignment()
1129 if (dataset != null)
1133 // try to avoid using SequenceI.equals at this stage, it will be expensive
1134 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1136 for (int i = 0; i < getHeight(); i++)
1138 SequenceI currentSeq = getSequenceAt(i);
1139 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1142 // verify all mappings are in dataset
1143 for (AlignedCodonFrame cf : codonFrameList)
1145 for (SequenceToSequenceMapping ssm : cf.getMappings())
1147 if (!seqs.contains(ssm.getFromSeq()))
1149 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1151 if (!seqs.contains(ssm.getMapping().getTo()))
1153 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1157 // finally construct dataset
1158 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1159 // move mappings to the dataset alignment
1160 dataset.codonFrameList = this.codonFrameList;
1161 this.codonFrameList = null;
1165 * reference count for number of alignments referencing this one.
1167 int alignmentRefs = 0;
1170 * increase reference count to this alignment.
1172 private void addAlignmentRef()
1178 public Alignment getDataset()
1184 public boolean padGaps()
1186 boolean modified = false;
1188 // Remove excess gaps from the end of alignment
1192 for (int i = 0; i < sequences.size(); i++)
1194 current = getSequenceAt(i);
1195 for (int j = current.getLength(); j > maxLength; j--)
1198 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1209 for (int i = 0; i < sequences.size(); i++)
1211 current = getSequenceAt(i);
1212 cLength = current.getLength();
1214 if (cLength < maxLength)
1216 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1219 else if (current.getLength() > maxLength)
1221 current.deleteChars(maxLength, current.getLength());
1228 * Justify the sequences to the left or right by deleting and inserting gaps
1229 * before the initial residue or after the terminal residue
1232 * true if alignment padded to right, false to justify to left
1233 * @return true if alignment was changed
1236 public boolean justify(boolean right)
1238 boolean modified = false;
1240 // Remove excess gaps from the end of alignment
1242 int ends[] = new int[sequences.size() * 2];
1244 for (int i = 0; i < sequences.size(); i++)
1246 current = getSequenceAt(i);
1247 // This should really be a sequence method
1248 ends[i * 2] = current.findIndex(current.getStart());
1249 ends[i * 2 + 1] = current
1250 .findIndex(current.getStart() + current.getLength());
1251 boolean hitres = false;
1252 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1254 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1263 ends[i * 2 + 1] = j;
1264 if (j - ends[i * 2] > maxLength)
1266 maxLength = j - ends[i * 2];
1274 // now edit the flanking gaps to justify to either left or right
1275 int cLength, extent, diff;
1276 for (int i = 0; i < sequences.size(); i++)
1278 current = getSequenceAt(i);
1280 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1281 diff = maxLength - cLength; // number of gaps to indent
1282 extent = current.getLength();
1286 if (extent > ends[i * 2 + 1])
1288 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1291 if (ends[i * 2] > diff)
1293 current.deleteChars(0, ends[i * 2] - diff);
1298 if (ends[i * 2] < diff)
1300 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1308 if (ends[i * 2] > 0)
1310 current.deleteChars(0, ends[i * 2]);
1312 ends[i * 2 + 1] -= ends[i * 2];
1313 extent -= ends[i * 2];
1315 if (extent > maxLength)
1317 current.deleteChars(maxLength + 1, extent);
1322 if (extent < maxLength)
1324 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1334 public HiddenSequences getHiddenSequences()
1336 return hiddenSequences;
1340 public HiddenColumns getHiddenColumns()
1346 public CigarArray getCompactAlignment()
1348 synchronized (sequences)
1350 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1352 for (SequenceI seq : sequences)
1354 alseqs[i++] = new SeqCigar(seq);
1356 CigarArray cal = new CigarArray(alseqs);
1357 cal.addOperation(CigarArray.M, getWidth());
1363 public void setProperty(Object key, Object value)
1365 if (alignmentProperties == null)
1367 alignmentProperties = new Hashtable();
1370 alignmentProperties.put(key, value);
1374 public Object getProperty(Object key)
1376 if (alignmentProperties != null)
1378 return alignmentProperties.get(key);
1387 public Hashtable getProperties()
1389 return alignmentProperties;
1393 * Adds the given mapping to the stored set. Note this may be held on the
1394 * dataset alignment.
1397 public void addCodonFrame(AlignedCodonFrame codons)
1399 List<AlignedCodonFrame> acfs = getCodonFrames();
1400 if (codons != null && acfs != null && !acfs.contains(codons))
1410 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1413 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1419 List<AlignedCodonFrame> cframes = new ArrayList<>();
1420 for (AlignedCodonFrame acf : getCodonFrames())
1422 if (acf.involvesSequence(seq))
1431 * Sets the codon frame mappings (replacing any existing mappings). Note the
1432 * mappings are set on the dataset alignment instead if there is one.
1434 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1437 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1439 if (dataset != null)
1441 dataset.setCodonFrames(acfs);
1445 this.codonFrameList = acfs;
1450 * Returns the set of codon frame mappings. Any changes to the returned set
1451 * will affect the alignment. The mappings are held on (and read from) the
1452 * dataset alignment if there is one.
1454 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1457 public List<AlignedCodonFrame> getCodonFrames()
1459 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1460 // this behaviour is currently incorrect. method should return codon frames
1461 // for just the alignment,
1462 // selected from dataset
1463 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1467 * Removes the given mapping from the stored set. Note that the mappings are
1468 * held on the dataset alignment if there is one.
1471 public boolean removeCodonFrame(AlignedCodonFrame codons)
1473 List<AlignedCodonFrame> acfs = getCodonFrames();
1474 if (codons == null || acfs == null)
1478 return acfs.remove(codons);
1482 public void append(AlignmentI toappend)
1484 // TODO JAL-1270 needs test coverage
1485 // currently tested for use in jalview.gui.SequenceFetcher
1486 char oldc = toappend.getGapCharacter();
1487 boolean samegap = oldc == getGapCharacter();
1488 boolean hashidden = toappend.getHiddenSequences() != null
1489 && toappend.getHiddenSequences().hiddenSequences != null;
1490 // get all sequences including any hidden ones
1491 List<SequenceI> sqs = (hashidden)
1492 ? toappend.getHiddenSequences().getFullAlignment()
1494 : toappend.getSequences();
1497 // avoid self append deadlock by
1498 List<SequenceI> toappendsq = new ArrayList<>();
1501 for (SequenceI addedsq : sqs)
1505 addedsq.replace(oldc, gapCharacter);
1507 toappendsq.add(addedsq);
1510 for (SequenceI addedsq : toappendsq)
1512 addSequence(addedsq);
1515 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1516 for (int a = 0; alan != null && a < alan.length; a++)
1518 addAnnotation(alan[a]);
1522 getCodonFrames().addAll(toappend.getCodonFrames());
1524 List<SequenceGroup> sg = toappend.getGroups();
1527 for (SequenceGroup _sg : sg)
1532 if (toappend.getHiddenSequences() != null)
1534 HiddenSequences hs = toappend.getHiddenSequences();
1535 if (hiddenSequences == null)
1537 hiddenSequences = new HiddenSequences(this);
1539 if (hs.hiddenSequences != null)
1541 for (int s = 0; s < hs.hiddenSequences.length; s++)
1543 // hide the newly appended sequence in the alignment
1544 if (hs.hiddenSequences[s] != null)
1546 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1551 if (toappend.getProperties() != null)
1553 // we really can't do very much here - just try to concatenate strings
1554 // where property collisions occur.
1555 Enumeration key = toappend.getProperties().keys();
1556 while (key.hasMoreElements())
1558 Object k = key.nextElement();
1559 Object ourval = this.getProperty(k);
1560 Object toapprop = toappend.getProperty(k);
1563 if (ourval.getClass().equals(toapprop.getClass())
1564 && !ourval.equals(toapprop))
1566 if (ourval instanceof String)
1570 ((String) ourval) + "; " + ((String) toapprop));
1574 if (ourval instanceof Vector)
1577 Enumeration theirv = ((Vector) toapprop).elements();
1578 while (theirv.hasMoreElements())
1580 ((Vector) ourval).addElement(theirv);
1588 // just add new property directly
1589 setProperty(k, toapprop);
1597 public AlignmentAnnotation findOrCreateAnnotation(String name,
1598 String calcId, boolean autoCalc, SequenceI seqRef,
1599 SequenceGroup groupRef)
1601 if (annotations != null)
1603 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1605 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1606 && (calcId == null || annot.getCalcId().equals(calcId))
1607 && annot.sequenceRef == seqRef
1608 && annot.groupRef == groupRef)
1614 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1615 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1616 annot.hasText = false;
1619 annot.setCalcId(new String(calcId));
1621 annot.autoCalculated = autoCalc;
1624 annot.setSequenceRef(seqRef);
1626 annot.groupRef = groupRef;
1627 addAnnotation(annot);
1633 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1635 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1636 if (alignmentAnnotation != null)
1638 return AlignmentAnnotation.findAnnotation(
1639 Arrays.asList(getAlignmentAnnotation()), calcId);
1641 return Arrays.asList(new AlignmentAnnotation[] {});
1645 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1646 String calcId, String label)
1648 return AlignmentAnnotation.findAnnotations(
1649 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1653 public void moveSelectedSequencesByOne(SequenceGroup sg,
1654 Map<SequenceI, SequenceCollectionI> map, boolean up)
1656 synchronized (sequences)
1661 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1663 SequenceI seq = sequences.get(i);
1664 if (!sg.getSequences(map).contains(seq))
1669 SequenceI temp = sequences.get(i - 1);
1670 if (sg.getSequences(null).contains(temp))
1675 sequences.set(i, temp);
1676 sequences.set(i - 1, seq);
1681 for (int i = sequences.size() - 2; i > -1; i--)
1683 SequenceI seq = sequences.get(i);
1684 if (!sg.getSequences(map).contains(seq))
1689 SequenceI temp = sequences.get(i + 1);
1690 if (sg.getSequences(map).contains(temp))
1695 sequences.set(i, temp);
1696 sequences.set(i + 1, seq);
1704 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1706 alignmentAnnotation.validateRangeAndDisplay();
1707 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1709 hasRNAStructure = true;
1713 private SequenceI seqrep = null;
1717 * @return the representative sequence for this group
1720 public SequenceI getSeqrep()
1726 * set the representative sequence for this group. Note - this affects the
1727 * interpretation of the Hidereps attribute.
1730 * the seqrep to set (null means no sequence representative)
1733 public void setSeqrep(SequenceI seqrep)
1735 this.seqrep = seqrep;
1740 * @return true if group has a sequence representative
1743 public boolean hasSeqrep()
1745 return seqrep != null;
1749 public int getEndRes()
1751 return getWidth() - 1;
1755 public int getStartRes()
1761 * In the case of AlignmentI - returns the dataset for the alignment, if set
1764 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1767 public AnnotatedCollectionI getContext()
1773 * Align this alignment like the given (mapped) one.
1776 public int alignAs(AlignmentI al)
1779 * Currently retains unmapped gaps (in introns), regaps mapped regions
1782 return alignAs(al, false, true);
1786 * Align this alignment 'the same as' the given one. Mapped sequences only are
1787 * realigned. If both of the same type (nucleotide/protein) then align both
1788 * identically. If this is nucleotide and the other is protein, make 3 gaps
1789 * for each gap in the protein sequences. If this is protein and the other is
1790 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1791 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1792 * protein to match the relative ordering of codons in the nucleotide.
1794 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1795 * regions are preserved. Gaps that connect introns to exons are treated
1796 * conservatively, i.e. only preserved if both intron and exon gaps are
1797 * preserved. TODO: check caveats below where the implementation fails
1800 * - must have same dataset, and sequences in al must have equivalent
1801 * dataset sequence and start/end bounds under given mapping
1802 * @param preserveMappedGaps
1803 * if true, gaps within and between mapped codons are preserved
1804 * @param preserveUnmappedGaps
1805 * if true, gaps within and between unmapped codons are preserved
1808 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1809 boolean preserveUnmappedGaps)
1811 // TODO should this method signature be the one in the interface?
1812 // JBPComment - yes - neither flag is used, so should be deleted.
1813 boolean thisIsNucleotide = this.isNucleotide();
1814 boolean thatIsProtein = !al.isNucleotide();
1815 if (!thatIsProtein && !thisIsNucleotide)
1817 return AlignmentUtils.alignProteinAsDna(this, al);
1819 else if (thatIsProtein && thisIsNucleotide)
1821 return AlignmentUtils.alignCdsAsProtein(this, al);
1823 return AlignmentUtils.alignAs(this, al);
1827 * Returns the alignment in Fasta format. Behaviour of this method is not
1828 * guaranteed between versions.
1831 public String toString()
1833 return new FastaFile().print(getSequencesArray(), true);
1837 * Returns the set of distinct sequence names. No ordering is guaranteed.
1840 public Set<String> getSequenceNames()
1842 Set<String> names = new HashSet<>();
1843 for (SequenceI seq : getSequences())
1845 names.add(seq.getName());
1851 public boolean hasValidSequence()
1853 boolean hasValidSeq = false;
1854 for (SequenceI seq : getSequences())
1856 if ((seq.getEnd() - seq.getStart()) > 0)
1866 * Update any mappings to 'virtual' sequences to compatible real ones, if
1867 * present in the added sequences. Returns a count of mappings updated.
1873 public int realiseMappings(List<SequenceI> seqs)
1876 for (SequenceI seq : seqs)
1878 for (AlignedCodonFrame mapping : getCodonFrames())
1880 count += mapping.realiseWith(seq);
1887 * Returns the first AlignedCodonFrame that has a mapping between the given
1895 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1897 for (AlignedCodonFrame acf : getCodonFrames())
1899 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1908 public boolean setHiddenColumns(HiddenColumns cols)
1910 boolean changed = cols == null ? hiddenCols != null
1911 : !cols.equals(hiddenCols);
1917 public void setupJPredAlignment()
1919 SequenceI repseq = getSequenceAt(0);
1921 HiddenColumns cs = new HiddenColumns();
1922 cs.hideList(repseq.getInsertions());
1923 setHiddenColumns(cs);
1927 public HiddenColumns propagateInsertions(SequenceI profileseq,
1928 AlignmentView input)
1932 char gc = getGapCharacter();
1933 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1934 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1935 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1936 return propagateInsertions(profileseq, origseq, nview);
1942 * sequence in al which corresponds to origseq
1944 * alignment which is to have gaps inserted into it
1946 * sequence corresponding to profileseq which defines gap map for
1949 private HiddenColumns propagateInsertions(SequenceI profileseq,
1950 SequenceI origseq, HiddenColumns hc)
1952 // take the set of hidden columns, and the set of gaps in origseq,
1953 // and remove all the hidden gaps from hiddenColumns
1955 // first get the gaps as a Bitset
1956 // then calculate hidden ^ not(gap)
1957 BitSet gaps = origseq.gapBitset();
1960 // for each sequence in the alignment, except the profile sequence,
1961 // insert gaps corresponding to each hidden region but where each hidden
1962 // column region is shifted backwards by the number of preceding visible
1963 // gaps update hidden columns at the same time
1964 HiddenColumns newhidden = new HiddenColumns();
1966 int numGapsBefore = 0;
1967 int gapPosition = 0;
1968 Iterator<int[]> it = hc.iterator();
1969 while (it.hasNext())
1971 int[] region = it.next();
1973 // get region coordinates accounting for gaps
1974 // we can rely on gaps not being *in* hidden regions because we already
1976 while (gapPosition < region[0])
1979 if (gaps.get(gapPosition))
1985 int left = region[0] - numGapsBefore;
1986 int right = region[1] - numGapsBefore;
1988 newhidden.hideColumns(left, right);
1989 padGaps(left, right, profileseq);
1995 * Pad gaps in all sequences in alignment except profileseq
1998 * position of first gap to insert
2000 * position of last gap to insert
2002 * sequence not to pad
2004 private void padGaps(int left, int right, SequenceI profileseq)
2006 char gc = getGapCharacter();
2008 // make a string with number of gaps = length of hidden region
2009 StringBuilder sb = new StringBuilder();
2010 for (int g = 0; g < right - left + 1; g++)
2015 // loop over the sequences and pad with gaps where required
2016 for (int s = 0, ns = getHeight(); s < ns; s++)
2018 SequenceI sqobj = getSequenceAt(s);
2019 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2021 String sq = sqobj.getSequenceAsString();
2023 sq.substring(0, left) + sb.toString() + sq.substring(left));
2029 * Returns a map from sequence to position (0, 1,...) in the alignment
2032 public Map<SequenceI, Integer> getSequencePositions()
2034 Map<SequenceI, Integer> map = new HashMap<>();
2036 synchronized (sequences)
2038 int i = sequences.size();
2039 for (int j = 0; j < i; j++)
2041 map.put(sequences.get(j), Integer.valueOf(j));