2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.datamodel;
23 import jalview.analysis.AlignmentUtils;
24 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
25 import jalview.io.FastaFile;
26 import jalview.util.Comparison;
27 import jalview.util.LinkedIdentityHashSet;
28 import jalview.util.MessageManager;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.BitSet;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.HashSet;
36 import java.util.Hashtable;
37 import java.util.Iterator;
38 import java.util.List;
41 import java.util.Vector;
44 * Data structure to hold and manipulate a multiple sequence alignment
50 public class Alignment implements AlignmentI, AutoCloseable
52 private Alignment dataset;
54 private List<SequenceI> sequences;
56 protected List<SequenceGroup> groups;
58 protected char gapCharacter = '-';
60 private boolean nucleotide = true;
62 public boolean hasRNAStructure = false;
64 public AlignmentAnnotation[] annotations;
66 HiddenSequences hiddenSequences;
68 HiddenColumns hiddenCols;
70 public Hashtable alignmentProperties;
72 private List<AlignedCodonFrame> codonFrameList;
74 private void initAlignment(SequenceI[] seqs)
76 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
77 hiddenSequences = new HiddenSequences(this);
78 hiddenCols = new HiddenColumns();
79 codonFrameList = new ArrayList<>();
81 nucleotide = Comparison.isNucleotide(seqs);
83 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
85 for (int i = 0; i < seqs.length; i++)
87 sequences.add(seqs[i]);
93 * Make a 'copy' alignment - sequences have new copies of features and
94 * annotations, but share the original dataset sequences.
96 public Alignment(AlignmentI al)
98 SequenceI[] seqs = al.getSequencesArray();
99 for (int i = 0; i < seqs.length; i++)
101 seqs[i] = new Sequence(seqs[i]);
107 * Share the same dataset sequence mappings (if any).
109 if (dataset == null && al.getDataset() == null)
111 this.setCodonFrames(al.getCodonFrames());
116 * Make an alignment from an array of Sequences.
120 public Alignment(SequenceI[] seqs)
126 * Make a new alignment from an array of SeqCigars
131 public Alignment(SeqCigar[] alseqs)
133 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
134 gapCharacter, new HiddenColumns(), null);
139 * Make a new alignment from an CigarArray JBPNote - can only do this when
140 * compactAlignment does not contain hidden regions. JBPNote - must also check
141 * that compactAlignment resolves to a set of SeqCigars - or construct them
144 * @param compactAlignment
147 public static AlignmentI createAlignment(CigarArray compactAlignment)
149 throw new Error(MessageManager
150 .getString("error.alignment_cigararray_not_implemented"));
151 // this(compactAlignment.refCigars);
155 public List<SequenceI> getSequences()
161 public List<SequenceI> getSequences(
162 Map<SequenceI, SequenceCollectionI> hiddenReps)
164 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
170 public SequenceI[] getSequencesArray()
172 if (sequences == null)
176 synchronized (sequences)
178 return sequences.toArray(new SequenceI[sequences.size()]);
183 * Returns a map of lists of sequences keyed by sequence name.
188 public Map<String, List<SequenceI>> getSequencesByName()
190 return AlignmentUtils.getSequencesByName(this);
194 public SequenceI getSequenceAt(int i)
196 synchronized (sequences)
199 if (i > -1 && i < sequences.size())
201 return sequences.get(i);
209 public SequenceI getSequenceAtAbsoluteIndex(int i)
211 SequenceI seq = null;
212 if (getHiddenSequences().getSize() > 0)
214 seq = getHiddenSequences().getHiddenSequence(i);
217 // didn't find the sequence in the hidden sequences, get it from the
219 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
220 seq = getSequenceAt(index);
225 seq = getSequenceAt(i);
231 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
232 * this currently does not recalculate whether or not the alignment is
233 * nucleotide, so mixed alignments may have undefined behaviour.
238 public void addSequence(SequenceI snew)
243 // maintain dataset integrity
244 SequenceI dsseq = snew.getDatasetSequence();
247 // derive new sequence
248 SequenceI adding = snew.deriveSequence();
250 dsseq = snew.getDatasetSequence();
252 if (getDataset().findIndex(dsseq) == -1)
254 getDataset().addSequence(dsseq);
258 if (sequences == null)
260 initAlignment(new SequenceI[] { snew });
264 synchronized (sequences)
269 if (hiddenSequences != null)
271 hiddenSequences.adjustHeightSequenceAdded();
276 public SequenceI replaceSequenceAt(int i, SequenceI snew)
278 synchronized (sequences)
280 if (sequences.size() > i)
282 return sequences.set(i, snew);
288 hiddenSequences.adjustHeightSequenceAdded();
295 * Inserts a sequence at a point in the alignment.
298 * the index of the position the sequence is to be inserted in.
301 public void insertSequenceAt(int i, SequenceI snew)
303 synchronized (sequences)
305 if (sequences.size() > i)
307 sequences.add(i, snew);
314 hiddenSequences.adjustHeightSequenceAdded();
323 * @return DOCUMENT ME!
326 public List<SequenceGroup> getGroups()
334 if (getDataset() != null)
338 getDataset().removeAlignmentRef();
339 } catch (Throwable e)
349 * Defensively nulls out references in case this object is not garbage
352 void nullReferences()
358 hiddenSequences = null;
362 * decrement the alignmentRefs counter by one and null references if it goes
367 private void removeAlignmentRef() throws Throwable
369 if (--alignmentRefs == 0)
376 public void deleteSequence(SequenceI s)
378 synchronized (sequences)
380 deleteSequence(findIndex(s));
385 public void deleteSequence(int i)
387 synchronized (sequences)
389 if (i > -1 && i < getHeight())
392 hiddenSequences.adjustHeightSequenceDeleted(i);
398 public void deleteHiddenSequence(int i)
400 synchronized (sequences)
402 if (i > -1 && i < getHeight())
412 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
415 public SequenceGroup findGroup(SequenceI seq, int position)
417 synchronized (groups)
419 for (SequenceGroup sg : groups)
421 if (sg.getSequences(null).contains(seq))
423 if (position >= sg.getStartRes() && position <= sg.getEndRes())
437 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
440 public SequenceGroup[] findAllGroups(SequenceI s)
442 ArrayList<SequenceGroup> temp = new ArrayList<>();
444 synchronized (groups)
446 int gSize = groups.size();
447 for (int i = 0; i < gSize; i++)
449 SequenceGroup sg = groups.get(i);
450 if (sg == null || sg.getSequences() == null)
452 this.deleteGroup(sg);
457 if (sg.getSequences().contains(s))
463 SequenceGroup[] ret = new SequenceGroup[temp.size()];
464 return temp.toArray(ret);
469 public void addGroup(SequenceGroup sg)
471 synchronized (groups)
473 if (!groups.contains(sg))
475 if (hiddenSequences.getSize() > 0)
477 int i, iSize = sg.getSize();
478 for (i = 0; i < iSize; i++)
480 if (!sequences.contains(sg.getSequenceAt(i)))
482 sg.deleteSequence(sg.getSequenceAt(i), false);
488 if (sg.getSize() < 1)
493 sg.setContext(this, true);
500 * remove any annotation that references gp
503 * (if null, removes all group associated annotation)
505 private void removeAnnotationForGroup(SequenceGroup gp)
507 if (annotations == null || annotations.length == 0)
511 // remove annotation very quickly
512 AlignmentAnnotation[] t,
513 todelete = new AlignmentAnnotation[annotations.length],
514 tokeep = new AlignmentAnnotation[annotations.length];
518 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
520 if (annotations[i].groupRef != null)
522 todelete[p++] = annotations[i];
526 tokeep[k++] = annotations[i];
532 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
534 if (annotations[i].groupRef == gp)
536 todelete[p++] = annotations[i];
540 tokeep[k++] = annotations[i];
546 // clear out the group associated annotation.
547 for (i = 0; i < p; i++)
549 unhookAnnotation(todelete[i]);
552 t = new AlignmentAnnotation[k];
553 for (i = 0; i < k; i++)
562 public void deleteAllGroups()
564 synchronized (groups)
566 if (annotations != null)
568 removeAnnotationForGroup(null);
570 for (SequenceGroup sg : groups)
572 sg.setContext(null, false);
580 public void deleteGroup(SequenceGroup g)
582 synchronized (groups)
584 if (groups.contains(g))
586 removeAnnotationForGroup(g);
588 g.setContext(null, false);
595 public SequenceI findName(String name)
597 return findName(name, false);
603 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
606 public SequenceI findName(String token, boolean b)
608 return findName(null, token, b);
614 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
618 public SequenceI findName(SequenceI startAfter, String token, boolean b)
624 String sqname = null;
625 int nseq = sequences.size();
626 if (startAfter != null)
628 // try to find the sequence in the alignment
629 boolean matched = false;
632 if (getSequenceAt(i++) == startAfter)
645 sq = getSequenceAt(i);
646 sqname = sq.getName();
647 if (sqname.equals(token) // exact match
648 || (b && // allow imperfect matches - case varies
649 (sqname.equalsIgnoreCase(token))))
651 return getSequenceAt(i);
661 public SequenceI[] findSequenceMatch(String name)
663 Vector matches = new Vector();
666 while (i < sequences.size())
668 if (getSequenceAt(i).getName().equals(name))
670 matches.addElement(getSequenceAt(i));
675 SequenceI[] result = new SequenceI[matches.size()];
676 for (i = 0; i < result.length; i++)
678 result[i] = (SequenceI) matches.elementAt(i);
688 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
691 public int findIndex(SequenceI s)
695 while (i < sequences.size())
697 if (s == getSequenceAt(i))
712 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
715 public int findIndex(SearchResultsI results)
719 while (i < sequences.size())
721 if (results.involvesSequence(getSequenceAt(i)))
731 public int getHeight()
733 return sequences.size();
737 public int getAbsoluteHeight()
739 return sequences.size() + getHiddenSequences().getSize();
743 public int getWidth()
747 for (int i = 0; i < sequences.size(); i++)
749 maxLength = Math.max(maxLength, getSequenceAt(i).getLength());
755 public int getVisibleWidth()
758 if (hiddenCols != null)
760 w -= hiddenCols.getSize();
772 public void setGapCharacter(char gc)
775 synchronized (sequences)
777 for (SequenceI seq : sequences)
779 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
780 .replace('-', gc).replace(' ', gc));
788 * @return DOCUMENT ME!
791 public char getGapCharacter()
799 * @see jalview.datamodel.AlignmentI#isAligned()
802 public boolean isAligned()
804 return isAligned(false);
810 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
813 public boolean isAligned(boolean includeHidden)
815 int width = getWidth();
816 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
818 includeHidden = true; // no hidden sequences to check against.
820 for (int i = 0; i < sequences.size(); i++)
822 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
824 if (getSequenceAt(i).getLength() != width)
835 public boolean isHidden(int alignmentIndex)
837 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
841 * Delete all annotations, including auto-calculated if the flag is set true.
842 * Returns true if at least one annotation was deleted, else false.
844 * @param includingAutoCalculated
848 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
850 boolean result = false;
851 for (AlignmentAnnotation alan : getAlignmentAnnotation())
853 if (!alan.autoCalculated || includingAutoCalculated)
855 deleteAnnotation(alan);
865 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
866 * AlignmentAnnotation)
869 public boolean deleteAnnotation(AlignmentAnnotation aa)
871 return deleteAnnotation(aa, true);
875 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
879 if (annotations != null)
881 aSize = annotations.length;
889 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
891 boolean swap = false;
894 for (int i = 0; i < aSize; i++)
896 if (annotations[i] == aa)
901 if (tIndex < temp.length)
903 temp[tIndex++] = annotations[i];
912 unhookAnnotation(aa);
919 * remove any object references associated with this annotation
923 private void unhookAnnotation(AlignmentAnnotation aa)
925 if (aa.sequenceRef != null)
927 aa.sequenceRef.removeAlignmentAnnotation(aa);
929 if (aa.groupRef != null)
931 // probably need to do more here in the future (post 2.5.0)
939 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
940 * AlignmentAnnotation)
943 public void addAnnotation(AlignmentAnnotation aa)
945 addAnnotation(aa, -1);
951 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
952 * AlignmentAnnotation, int)
955 public void addAnnotation(AlignmentAnnotation aa, int pos)
957 if (aa.getRNAStruc() != null)
959 hasRNAStructure = true;
963 if (annotations != null)
965 aSize = annotations.length + 1;
968 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
970 if (pos == -1 || pos >= aSize)
972 temp[aSize - 1] = aa;
981 for (i = 0; i < (aSize - 1); i++, p++)
989 temp[p] = annotations[i];
998 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
1000 if (aa == null || annotations == null || annotations.length - 1 < index)
1005 int aSize = annotations.length;
1006 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
1010 for (int i = 0; i < aSize; i++)
1019 temp[i] = annotations[i];
1023 temp[i] = annotations[i - 1];
1032 * returns all annotation on the alignment
1034 public AlignmentAnnotation[] getAlignmentAnnotation()
1040 public boolean isNucleotide()
1046 public boolean hasRNAStructure()
1048 // TODO can it happen that structure is removed from alignment?
1049 return hasRNAStructure;
1053 public void setDataset(AlignmentI data)
1055 if (dataset == null && data == null)
1057 createDatasetAlignment();
1059 else if (dataset == null && data != null)
1063 throw new IllegalArgumentException("Circular dataset reference");
1065 if (!(data instanceof Alignment))
1068 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1070 dataset = (Alignment) data;
1071 for (int i = 0; i < getHeight(); i++)
1073 SequenceI currentSeq = getSequenceAt(i);
1074 SequenceI dsq = currentSeq.getDatasetSequence();
1077 dsq = currentSeq.createDatasetSequence();
1078 dataset.addSequence(dsq);
1082 while (dsq.getDatasetSequence() != null)
1084 dsq = dsq.getDatasetSequence();
1086 if (dataset.findIndex(dsq) == -1)
1088 dataset.addSequence(dsq);
1093 dataset.addAlignmentRef();
1097 * add dataset sequences to seq for currentSeq and any sequences it references
1099 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1100 Set<SequenceI> seqs, boolean createDatasetSequence)
1102 SequenceI alignedSeq = currentSeq;
1103 if (currentSeq.getDatasetSequence() != null)
1105 currentSeq = currentSeq.getDatasetSequence();
1109 if (createDatasetSequence)
1111 currentSeq = currentSeq.createDatasetSequence();
1115 List<SequenceI> toProcess = new ArrayList<>();
1116 toProcess.add(currentSeq);
1117 while (toProcess.size() > 0)
1120 SequenceI curDs = toProcess.remove(0);
1122 if (!seqs.add(curDs))
1126 // iterate over database references, making sure we add forward referenced
1128 if (curDs.getDBRefs() != null)
1130 for (DBRefEntry dbr : curDs.getDBRefs())
1132 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1134 if (dbr.getMap().getTo() == alignedSeq)
1137 * update mapping to be to the newly created dataset sequence
1139 dbr.getMap().setTo(currentSeq);
1141 if (dbr.getMap().getTo().getDatasetSequence() != null)
1143 throw new Error("Implementation error: Map.getTo() for dbref "
1144 + dbr + " from " + curDs.getName()
1145 + " is not a dataset sequence.");
1147 // we recurse to add all forward references to dataset sequences via
1149 toProcess.add(dbr.getMap().getTo());
1157 * Creates a new dataset for this alignment. Can only be done once - if
1158 * dataset is not null this will not be performed.
1160 public void createDatasetAlignment()
1162 if (dataset != null)
1166 // try to avoid using SequenceI.equals at this stage, it will be expensive
1167 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1169 for (int i = 0; i < getHeight(); i++)
1171 SequenceI currentSeq = getSequenceAt(i);
1172 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1175 // verify all mappings are in dataset
1176 for (AlignedCodonFrame cf : codonFrameList)
1178 for (SequenceToSequenceMapping ssm : cf.getMappings())
1180 if (!seqs.contains(ssm.getFromSeq()))
1182 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1184 if (!seqs.contains(ssm.getMapping().getTo()))
1186 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1190 // finally construct dataset
1191 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1192 // move mappings to the dataset alignment
1193 dataset.codonFrameList = this.codonFrameList;
1194 this.codonFrameList = null;
1198 * reference count for number of alignments referencing this one.
1200 int alignmentRefs = 0;
1203 * increase reference count to this alignment.
1205 private void addAlignmentRef()
1211 public Alignment getDataset()
1217 public boolean padGaps()
1219 boolean modified = false;
1221 // Remove excess gaps from the end of alignment
1225 int nseq = sequences.size();
1226 for (int i = 0; i < nseq; i++)
1228 current = getSequenceAt(i);
1229 for (int j = current.getLength(); j > maxLength; j--)
1232 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1243 for (int i = 0; i < nseq; i++)
1245 current = getSequenceAt(i);
1246 cLength = current.getLength();
1248 if (cLength < maxLength)
1250 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1253 else if (current.getLength() > maxLength)
1255 current.deleteChars(maxLength, current.getLength());
1262 * Justify the sequences to the left or right by deleting and inserting gaps
1263 * before the initial residue or after the terminal residue
1266 * true if alignment padded to right, false to justify to left
1267 * @return true if alignment was changed
1270 public boolean justify(boolean right)
1272 boolean modified = false;
1274 // Remove excess gaps from the end of alignment
1276 int ends[] = new int[sequences.size() * 2];
1278 for (int i = 0; i < sequences.size(); i++)
1280 current = getSequenceAt(i);
1281 // This should really be a sequence method
1282 ends[i * 2] = current.findIndex(current.getStart());
1283 ends[i * 2 + 1] = current
1284 .findIndex(current.getStart() + current.getLength());
1285 boolean hitres = false;
1286 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1288 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1297 ends[i * 2 + 1] = j;
1298 if (j - ends[i * 2] > maxLength)
1300 maxLength = j - ends[i * 2];
1308 // now edit the flanking gaps to justify to either left or right
1309 int cLength, extent, diff;
1310 for (int i = 0; i < sequences.size(); i++)
1312 current = getSequenceAt(i);
1314 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1315 diff = maxLength - cLength; // number of gaps to indent
1316 extent = current.getLength();
1320 if (extent > ends[i * 2 + 1])
1322 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1325 if (ends[i * 2] > diff)
1327 current.deleteChars(0, ends[i * 2] - diff);
1332 if (ends[i * 2] < diff)
1334 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1342 if (ends[i * 2] > 0)
1344 current.deleteChars(0, ends[i * 2]);
1346 ends[i * 2 + 1] -= ends[i * 2];
1347 extent -= ends[i * 2];
1349 if (extent > maxLength)
1351 current.deleteChars(maxLength + 1, extent);
1356 if (extent < maxLength)
1358 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1368 public HiddenSequences getHiddenSequences()
1370 return hiddenSequences;
1374 public HiddenColumns getHiddenColumns()
1380 public CigarArray getCompactAlignment()
1382 synchronized (sequences)
1384 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1386 for (SequenceI seq : sequences)
1388 alseqs[i++] = new SeqCigar(seq);
1390 CigarArray cal = new CigarArray(alseqs);
1391 cal.addOperation(CigarArray.M, getWidth());
1397 public void setProperty(Object key, Object value)
1399 if (alignmentProperties == null)
1401 alignmentProperties = new Hashtable();
1404 alignmentProperties.put(key, value);
1408 public Object getProperty(Object key)
1410 if (alignmentProperties != null)
1412 return alignmentProperties.get(key);
1421 public Hashtable getProperties()
1423 return alignmentProperties;
1427 * Adds the given mapping to the stored set. Note this may be held on the
1428 * dataset alignment.
1431 public void addCodonFrame(AlignedCodonFrame codons)
1433 List<AlignedCodonFrame> acfs = getCodonFrames();
1434 if (codons != null && acfs != null && !acfs.contains(codons))
1444 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1447 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1453 List<AlignedCodonFrame> cframes = new ArrayList<>();
1454 for (AlignedCodonFrame acf : getCodonFrames())
1456 if (acf.involvesSequence(seq))
1465 * Sets the codon frame mappings (replacing any existing mappings). Note the
1466 * mappings are set on the dataset alignment instead if there is one.
1468 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1471 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1473 if (dataset != null)
1475 dataset.setCodonFrames(acfs);
1479 this.codonFrameList = acfs;
1484 * Returns the set of codon frame mappings. Any changes to the returned set
1485 * will affect the alignment. The mappings are held on (and read from) the
1486 * dataset alignment if there is one.
1488 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1491 public List<AlignedCodonFrame> getCodonFrames()
1493 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1494 // this behaviour is currently incorrect. method should return codon frames
1495 // for just the alignment,
1496 // selected from dataset
1497 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1501 * Removes the given mapping from the stored set. Note that the mappings are
1502 * held on the dataset alignment if there is one.
1505 public boolean removeCodonFrame(AlignedCodonFrame codons)
1507 List<AlignedCodonFrame> acfs = getCodonFrames();
1508 if (codons == null || acfs == null)
1512 return acfs.remove(codons);
1516 public void append(AlignmentI toappend)
1518 // TODO JAL-1270 needs test coverage
1519 // currently tested for use in jalview.gui.SequenceFetcher
1520 char oldc = toappend.getGapCharacter();
1521 boolean samegap = oldc == getGapCharacter();
1522 boolean hashidden = toappend.getHiddenSequences() != null
1523 && toappend.getHiddenSequences().hiddenSequences != null;
1524 // get all sequences including any hidden ones
1525 List<SequenceI> sqs = (hashidden)
1526 ? toappend.getHiddenSequences().getFullAlignment()
1528 : toappend.getSequences();
1531 // avoid self append deadlock by
1532 List<SequenceI> toappendsq = new ArrayList<>();
1535 for (SequenceI addedsq : sqs)
1539 addedsq.replace(oldc, gapCharacter);
1541 toappendsq.add(addedsq);
1544 for (SequenceI addedsq : toappendsq)
1546 addSequence(addedsq);
1549 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1550 for (int a = 0; alan != null && a < alan.length; a++)
1552 addAnnotation(alan[a]);
1556 getCodonFrames().addAll(toappend.getCodonFrames());
1558 List<SequenceGroup> sg = toappend.getGroups();
1561 for (SequenceGroup _sg : sg)
1566 if (toappend.getHiddenSequences() != null)
1568 HiddenSequences hs = toappend.getHiddenSequences();
1569 if (hiddenSequences == null)
1571 hiddenSequences = new HiddenSequences(this);
1573 if (hs.hiddenSequences != null)
1575 for (int s = 0; s < hs.hiddenSequences.length; s++)
1577 // hide the newly appended sequence in the alignment
1578 if (hs.hiddenSequences[s] != null)
1580 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1585 if (toappend.getProperties() != null)
1587 // we really can't do very much here - just try to concatenate strings
1588 // where property collisions occur.
1589 Enumeration key = toappend.getProperties().keys();
1590 while (key.hasMoreElements())
1592 Object k = key.nextElement();
1593 Object ourval = this.getProperty(k);
1594 Object toapprop = toappend.getProperty(k);
1597 if (ourval.getClass().equals(toapprop.getClass())
1598 && !ourval.equals(toapprop))
1600 if (ourval instanceof String)
1604 ((String) ourval) + "; " + ((String) toapprop));
1608 if (ourval instanceof Vector)
1611 Enumeration theirv = ((Vector) toapprop).elements();
1612 while (theirv.hasMoreElements())
1614 ((Vector) ourval).addElement(theirv);
1622 // just add new property directly
1623 setProperty(k, toapprop);
1631 public AlignmentAnnotation findOrCreateAnnotation(String name,
1632 String calcId, boolean autoCalc, SequenceI seqRef,
1633 SequenceGroup groupRef)
1635 AlignmentAnnotation annot = annotations == null ? null
1636 : AlignmentAnnotation.findFirstAnnotation(
1637 Arrays.asList(getAlignmentAnnotation()), name, calcId,
1638 autoCalc, seqRef, groupRef);
1643 annot = new AlignmentAnnotation(name, name, new Annotation[1], 0f, 0f,
1644 AlignmentAnnotation.BAR_GRAPH);
1645 annot.hasText = false;
1648 annot.setCalcId(calcId);
1650 annot.autoCalculated = autoCalc;
1653 annot.setSequenceRef(seqRef);
1655 annot.groupRef = groupRef;
1656 addAnnotation(annot);
1663 public AlignmentAnnotation updateFromOrCopyAnnotation(
1664 AlignmentAnnotation ala)
1666 AlignmentAnnotation annot = AlignmentAnnotation.findFirstAnnotation(
1667 Arrays.asList(getAlignmentAnnotation()), ala.label, ala.calcId,
1668 ala.autoCalculated, ala.sequenceRef, ala.groupRef);
1671 annot = new AlignmentAnnotation(ala);
1672 addAnnotation(annot);
1676 annot.updateAlignmentAnnotationFrom(ala);
1678 validateAnnotation(annot);
1683 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1685 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1686 if (alignmentAnnotation != null)
1688 return AlignmentAnnotation.findAnnotation(
1689 Arrays.asList(getAlignmentAnnotation()), calcId);
1691 return Arrays.asList(new AlignmentAnnotation[] {});
1695 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1696 String calcId, String label)
1698 return AlignmentAnnotation.findAnnotations(
1699 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1703 public void moveSelectedSequencesByOne(SequenceGroup sg,
1704 Map<SequenceI, SequenceCollectionI> map, boolean up)
1706 synchronized (sequences)
1711 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1713 SequenceI seq = sequences.get(i);
1714 if (!sg.getSequences(map).contains(seq))
1719 SequenceI temp = sequences.get(i - 1);
1720 if (sg.getSequences(null).contains(temp))
1725 sequences.set(i, temp);
1726 sequences.set(i - 1, seq);
1731 for (int i = sequences.size() - 2; i > -1; i--)
1733 SequenceI seq = sequences.get(i);
1734 if (!sg.getSequences(map).contains(seq))
1739 SequenceI temp = sequences.get(i + 1);
1740 if (sg.getSequences(map).contains(temp))
1745 sequences.set(i, temp);
1746 sequences.set(i + 1, seq);
1754 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1756 alignmentAnnotation.validateRangeAndDisplay();
1757 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1759 hasRNAStructure = true;
1763 private SequenceI seqrep = null;
1767 * @return the representative sequence for this group
1770 public SequenceI getSeqrep()
1776 * set the representative sequence for this group. Note - this affects the
1777 * interpretation of the Hidereps attribute.
1780 * the seqrep to set (null means no sequence representative)
1783 public void setSeqrep(SequenceI seqrep)
1785 this.seqrep = seqrep;
1790 * @return true if group has a sequence representative
1793 public boolean hasSeqrep()
1795 return seqrep != null;
1799 public int getEndRes()
1801 return getWidth() - 1;
1805 public int getStartRes()
1811 * In the case of AlignmentI - returns the dataset for the alignment, if set
1814 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1817 public AnnotatedCollectionI getContext()
1823 * Align this alignment like the given (mapped) one.
1826 public int alignAs(AlignmentI al)
1829 * Currently retains unmapped gaps (in introns), regaps mapped regions
1832 return alignAs(al, false, true);
1836 * Align this alignment 'the same as' the given one. Mapped sequences only are
1837 * realigned. If both of the same type (nucleotide/protein) then align both
1838 * identically. If this is nucleotide and the other is protein, make 3 gaps
1839 * for each gap in the protein sequences. If this is protein and the other is
1840 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1841 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1842 * protein to match the relative ordering of codons in the nucleotide.
1844 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1845 * regions are preserved. Gaps that connect introns to exons are treated
1846 * conservatively, i.e. only preserved if both intron and exon gaps are
1847 * preserved. TODO: check caveats below where the implementation fails
1850 * - must have same dataset, and sequences in al must have equivalent
1851 * dataset sequence and start/end bounds under given mapping
1852 * @param preserveMappedGaps
1853 * if true, gaps within and between mapped codons are preserved
1854 * @param preserveUnmappedGaps
1855 * if true, gaps within and between unmapped codons are preserved
1858 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1859 boolean preserveUnmappedGaps)
1861 // TODO should this method signature be the one in the interface?
1862 // JBPComment - yes - neither flag is used, so should be deleted.
1863 boolean thisIsNucleotide = this.isNucleotide();
1864 boolean thatIsProtein = !al.isNucleotide();
1865 if (!thatIsProtein && !thisIsNucleotide)
1867 return AlignmentUtils.alignProteinAsDna(this, al);
1869 else if (thatIsProtein && thisIsNucleotide)
1871 return AlignmentUtils.alignCdsAsProtein(this, al);
1873 return AlignmentUtils.alignAs(this, al);
1877 * Returns the alignment in Fasta format. Behaviour of this method is not
1878 * guaranteed between versions.
1881 public String toString()
1883 return new FastaFile().print(getSequencesArray(), true);
1887 * Returns the set of distinct sequence names. No ordering is guaranteed.
1890 public Set<String> getSequenceNames()
1892 Set<String> names = new HashSet<>();
1893 for (SequenceI seq : getSequences())
1895 names.add(seq.getName());
1901 public boolean hasValidSequence()
1903 boolean hasValidSeq = false;
1904 for (SequenceI seq : getSequences())
1906 if ((seq.getEnd() - seq.getStart()) > 0)
1916 * Update any mappings to 'virtual' sequences to compatible real ones, if
1917 * present in the added sequences. Returns a count of mappings updated.
1923 public int realiseMappings(List<SequenceI> seqs)
1926 for (SequenceI seq : seqs)
1928 for (AlignedCodonFrame mapping : getCodonFrames())
1930 count += mapping.realiseWith(seq);
1937 * Returns the first AlignedCodonFrame that has a mapping between the given
1945 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1947 for (AlignedCodonFrame acf : getCodonFrames())
1949 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1958 public boolean setHiddenColumns(HiddenColumns cols)
1960 boolean changed = cols == null ? hiddenCols != null
1961 : !cols.equals(hiddenCols);
1967 public void setupJPredAlignment()
1969 SequenceI repseq = getSequenceAt(0);
1971 HiddenColumns cs = new HiddenColumns();
1972 cs.hideList(repseq.getInsertions());
1973 setHiddenColumns(cs);
1977 public HiddenColumns propagateInsertions(SequenceI profileseq,
1978 AlignmentView input)
1982 char gc = getGapCharacter();
1983 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1984 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1985 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1986 return propagateInsertions(profileseq, origseq, nview);
1992 * sequence in al which corresponds to origseq
1994 * alignment which is to have gaps inserted into it
1996 * sequence corresponding to profileseq which defines gap map for
1999 private HiddenColumns propagateInsertions(SequenceI profileseq,
2000 SequenceI origseq, HiddenColumns hc)
2002 // take the set of hidden columns, and the set of gaps in origseq,
2003 // and remove all the hidden gaps from hiddenColumns
2005 // first get the gaps as a Bitset
2006 // then calculate hidden ^ not(gap)
2007 BitSet gaps = origseq.gapBitset();
2010 // for each sequence in the alignment, except the profile sequence,
2011 // insert gaps corresponding to each hidden region but where each hidden
2012 // column region is shifted backwards by the number of preceding visible
2013 // gaps update hidden columns at the same time
2014 HiddenColumns newhidden = new HiddenColumns();
2016 int numGapsBefore = 0;
2017 int gapPosition = 0;
2018 Iterator<int[]> it = hc.iterator();
2019 while (it.hasNext())
2021 int[] region = it.next();
2023 // get region coordinates accounting for gaps
2024 // we can rely on gaps not being *in* hidden regions because we already
2026 while (gapPosition < region[0])
2029 if (gaps.get(gapPosition))
2035 int left = region[0] - numGapsBefore;
2036 int right = region[1] - numGapsBefore;
2038 newhidden.hideColumns(left, right);
2039 padGaps(left, right, profileseq);
2045 * Pad gaps in all sequences in alignment except profileseq
2048 * position of first gap to insert
2050 * position of last gap to insert
2052 * sequence not to pad
2054 private void padGaps(int left, int right, SequenceI profileseq)
2056 char gc = getGapCharacter();
2058 // make a string with number of gaps = length of hidden region
2059 StringBuilder sb = new StringBuilder();
2060 for (int g = 0; g < right - left + 1; g++)
2065 // loop over the sequences and pad with gaps where required
2066 for (int s = 0, ns = getHeight(); s < ns; s++)
2068 SequenceI sqobj = getSequenceAt(s);
2069 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2071 String sq = sqobj.getSequenceAsString();
2073 sq.substring(0, left) + sb.toString() + sq.substring(left));
2079 public List<SequenceI> getHmmSequences()
2081 List<SequenceI> result = new ArrayList<>();
2082 for (int i = 0; i < sequences.size(); i++)
2084 SequenceI seq = sequences.get(i);
2085 if (seq.hasHMMProfile())