2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.datamodel;
23 import jalview.analysis.AlignmentUtils;
24 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
25 import jalview.io.FastaFile;
26 import jalview.util.Comparison;
27 import jalview.util.LinkedIdentityHashSet;
28 import jalview.util.MessageManager;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.BitSet;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.HashSet;
36 import java.util.Hashtable;
37 import java.util.Iterator;
38 import java.util.List;
41 import java.util.Vector;
44 * Data structure to hold and manipulate a multiple sequence alignment
50 public class Alignment implements AlignmentI
52 private Alignment dataset;
54 private List<SequenceI> sequences;
56 protected List<SequenceGroup> groups;
58 protected char gapCharacter = '-';
60 private boolean nucleotide = true;
62 public boolean hasRNAStructure = false;
64 public AlignmentAnnotation[] annotations;
66 HiddenSequences hiddenSequences;
68 HiddenColumns hiddenCols;
70 public Hashtable alignmentProperties;
72 private List<AlignedCodonFrame> codonFrameList;
74 private void initAlignment(SequenceI[] seqs)
76 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
77 hiddenSequences = new HiddenSequences(this);
78 hiddenCols = new HiddenColumns();
79 codonFrameList = new ArrayList<>();
81 nucleotide = Comparison.isNucleotide(seqs);
83 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
85 for (int i = 0; i < seqs.length; i++)
87 sequences.add(seqs[i]);
93 * Make a 'copy' alignment - sequences have new copies of features and
94 * annotations, but share the original dataset sequences.
96 public Alignment(AlignmentI al)
98 SequenceI[] seqs = al.getSequencesArray();
99 for (int i = 0; i < seqs.length; i++)
101 seqs[i] = new Sequence(seqs[i]);
107 * Share the same dataset sequence mappings (if any).
109 if (dataset == null && al.getDataset() == null)
111 this.setCodonFrames(al.getCodonFrames());
116 * Make an alignment from an array of Sequences.
120 public Alignment(SequenceI[] seqs)
126 * Make a new alignment from an array of SeqCigars
131 public Alignment(SeqCigar[] alseqs)
133 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
134 gapCharacter, new HiddenColumns(), null);
139 * Make a new alignment from an CigarArray JBPNote - can only do this when
140 * compactAlignment does not contain hidden regions. JBPNote - must also check
141 * that compactAlignment resolves to a set of SeqCigars - or construct them
144 * @param compactAlignment
147 public static AlignmentI createAlignment(CigarArray compactAlignment)
149 throw new Error(MessageManager
150 .getString("error.alignment_cigararray_not_implemented"));
151 // this(compactAlignment.refCigars);
155 public List<SequenceI> getSequences()
161 public List<SequenceI> getSequences(
162 Map<SequenceI, SequenceCollectionI> hiddenReps)
164 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
170 public SequenceI[] getSequencesArray()
172 if (sequences == null)
176 synchronized (sequences)
178 return sequences.toArray(new SequenceI[sequences.size()]);
183 * Returns a map of lists of sequences keyed by sequence name.
188 public Map<String, List<SequenceI>> getSequencesByName()
190 return AlignmentUtils.getSequencesByName(this);
194 public SequenceI getSequenceAt(int i)
196 synchronized (sequences)
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();
294 * Inserts a sequence at a point in the alignment.
297 * the index of the position the sequence is to be inserted in.
300 public void insertSequenceAt(int i, SequenceI snew)
302 synchronized (sequences)
304 if (sequences.size() > i)
306 sequences.add(i, snew);
313 hiddenSequences.adjustHeightSequenceAdded();
322 * @return DOCUMENT ME!
325 public List<SequenceGroup> getGroups()
331 public void finalize() throws Throwable
333 if (getDataset() != null)
335 getDataset().removeAlignmentRef();
343 * Defensively nulls out references in case this object is not garbage
346 void nullReferences()
352 hiddenSequences = null;
356 * decrement the alignmentRefs counter by one and null references if it goes
361 private void removeAlignmentRef() throws Throwable
363 if (--alignmentRefs == 0)
370 public void deleteSequence(SequenceI s)
372 synchronized (sequences)
374 deleteSequence(findIndex(s));
379 public void deleteSequence(int i)
381 synchronized (sequences)
383 if (i > -1 && i < getHeight())
386 hiddenSequences.adjustHeightSequenceDeleted(i);
392 public void deleteHiddenSequence(int i)
394 synchronized (sequences)
396 if (i > -1 && i < getHeight())
406 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
409 public SequenceGroup findGroup(SequenceI seq, int position)
411 synchronized (groups)
413 for (SequenceGroup sg : groups)
415 if (sg.getSequences(null).contains(seq))
417 if (position >= sg.getStartRes() && position <= sg.getEndRes())
431 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
434 public SequenceGroup[] findAllGroups(SequenceI s)
436 ArrayList<SequenceGroup> temp = new ArrayList<>();
438 synchronized (groups)
440 int gSize = groups.size();
441 for (int i = 0; i < gSize; i++)
443 SequenceGroup sg = groups.get(i);
444 if (sg == null || sg.getSequences() == null)
446 this.deleteGroup(sg);
451 if (sg.getSequences().contains(s))
457 SequenceGroup[] ret = new SequenceGroup[temp.size()];
458 return temp.toArray(ret);
463 public void addGroup(SequenceGroup sg)
465 synchronized (groups)
467 if (!groups.contains(sg))
469 if (hiddenSequences.getSize() > 0)
471 int i, iSize = sg.getSize();
472 for (i = 0; i < iSize; i++)
474 if (!sequences.contains(sg.getSequenceAt(i)))
476 sg.deleteSequence(sg.getSequenceAt(i), false);
482 if (sg.getSize() < 1)
487 sg.setContext(this, true);
494 * remove any annotation that references gp
497 * (if null, removes all group associated annotation)
499 private void removeAnnotationForGroup(SequenceGroup gp)
501 if (annotations == null || annotations.length == 0)
505 // remove annotation very quickly
506 AlignmentAnnotation[] t,
507 todelete = new AlignmentAnnotation[annotations.length],
508 tokeep = new AlignmentAnnotation[annotations.length];
512 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
514 if (annotations[i].groupRef != null)
516 todelete[p++] = annotations[i];
520 tokeep[k++] = annotations[i];
526 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
528 if (annotations[i].groupRef == gp)
530 todelete[p++] = annotations[i];
534 tokeep[k++] = annotations[i];
540 // clear out the group associated annotation.
541 for (i = 0; i < p; i++)
543 unhookAnnotation(todelete[i]);
546 t = new AlignmentAnnotation[k];
547 for (i = 0; i < k; i++)
556 public void deleteAllGroups()
558 synchronized (groups)
560 if (annotations != null)
562 removeAnnotationForGroup(null);
564 for (SequenceGroup sg : groups)
566 sg.setContext(null, false);
574 public void deleteGroup(SequenceGroup g)
576 synchronized (groups)
578 if (groups.contains(g))
580 removeAnnotationForGroup(g);
582 g.setContext(null, false);
589 public SequenceI findName(String name)
591 return findName(name, false);
597 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
600 public SequenceI findName(String token, boolean b)
602 return findName(null, token, b);
608 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
612 public SequenceI findName(SequenceI startAfter, String token, boolean b)
617 String sqname = null;
618 if (startAfter != null)
620 // try to find the sequence in the alignment
621 boolean matched = false;
622 while (i < sequences.size())
624 if (getSequenceAt(i++) == startAfter)
635 while (i < sequences.size())
637 sq = getSequenceAt(i);
638 sqname = sq.getName();
639 if (sqname.equals(token) // exact match
640 || (b && // allow imperfect matches - case varies
641 (sqname.equalsIgnoreCase(token))))
643 return getSequenceAt(i);
653 public SequenceI[] findSequenceMatch(String name)
655 Vector matches = new Vector();
658 while (i < sequences.size())
660 if (getSequenceAt(i).getName().equals(name))
662 matches.addElement(getSequenceAt(i));
667 SequenceI[] result = new SequenceI[matches.size()];
668 for (i = 0; i < result.length; i++)
670 result[i] = (SequenceI) matches.elementAt(i);
680 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
683 public int findIndex(SequenceI s)
687 while (i < sequences.size())
689 if (s == getSequenceAt(i))
704 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
707 public int findIndex(SearchResultsI results)
711 while (i < sequences.size())
713 if (results.involvesSequence(getSequenceAt(i)))
723 public int getHeight()
725 return sequences.size();
729 public int getAbsoluteHeight()
731 return sequences.size() + getHiddenSequences().getSize();
735 public int getWidth()
739 for (int i = 0; i < sequences.size(); i++)
741 if (getSequenceAt(i).getLength() > maxLength)
743 maxLength = getSequenceAt(i).getLength();
751 public int getWidth()
753 final Wrapper temp = new Wrapper();
755 forEachSequence(new Consumer<SequenceI>()
758 public void accept(SequenceI s)
760 if (s.getLength() > temp.inner)
762 temp.inner = s.getLength();
765 }, 0, sequences.size() - 1);
770 public static class Wrapper
782 public void setGapCharacter(char gc)
785 synchronized (sequences)
787 for (SequenceI seq : sequences)
789 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
790 .replace('-', gc).replace(' ', gc));
798 * @return DOCUMENT ME!
801 public char getGapCharacter()
809 * @see jalview.datamodel.AlignmentI#isAligned()
812 public boolean isAligned()
814 return isAligned(false);
820 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
823 public boolean isAligned(boolean includeHidden)
825 int width = getWidth();
826 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
828 includeHidden = true; // no hidden sequences to check against.
830 for (int i = 0; i < sequences.size(); i++)
832 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
834 if (getSequenceAt(i).getLength() != width)
845 public boolean isHidden(int alignmentIndex)
847 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
851 * Delete all annotations, including auto-calculated if the flag is set true.
852 * Returns true if at least one annotation was deleted, else false.
854 * @param includingAutoCalculated
858 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
860 boolean result = false;
861 for (AlignmentAnnotation alan : getAlignmentAnnotation())
863 if (!alan.autoCalculated || includingAutoCalculated)
865 deleteAnnotation(alan);
875 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
876 * AlignmentAnnotation)
879 public boolean deleteAnnotation(AlignmentAnnotation aa)
881 return deleteAnnotation(aa, true);
885 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
889 if (annotations != null)
891 aSize = annotations.length;
899 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
901 boolean swap = false;
904 for (int i = 0; i < aSize; i++)
906 if (annotations[i] == aa)
911 if (tIndex < temp.length)
913 temp[tIndex++] = annotations[i];
922 unhookAnnotation(aa);
929 * remove any object references associated with this annotation
933 private void unhookAnnotation(AlignmentAnnotation aa)
935 if (aa.sequenceRef != null)
937 aa.sequenceRef.removeAlignmentAnnotation(aa);
939 if (aa.groupRef != null)
941 // probably need to do more here in the future (post 2.5.0)
949 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
950 * AlignmentAnnotation)
953 public void addAnnotation(AlignmentAnnotation aa)
955 addAnnotation(aa, -1);
961 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
962 * AlignmentAnnotation, int)
965 public void addAnnotation(AlignmentAnnotation aa, int pos)
967 if (aa.getRNAStruc() != null)
969 hasRNAStructure = true;
973 if (annotations != null)
975 aSize = annotations.length + 1;
978 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
980 if (pos == -1 || pos >= aSize)
982 temp[aSize - 1] = aa;
991 for (i = 0; i < (aSize - 1); i++, p++)
999 temp[p] = annotations[i];
1008 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
1010 if (aa == null || annotations == null || annotations.length - 1 < index)
1015 int aSize = annotations.length;
1016 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
1020 for (int i = 0; i < aSize; i++)
1029 temp[i] = annotations[i];
1033 temp[i] = annotations[i - 1];
1042 * returns all annotation on the alignment
1044 public AlignmentAnnotation[] getAlignmentAnnotation()
1050 public boolean isNucleotide()
1056 public boolean hasRNAStructure()
1058 // TODO can it happen that structure is removed from alignment?
1059 return hasRNAStructure;
1063 public void setDataset(AlignmentI data)
1065 if (dataset == null && data == null)
1067 createDatasetAlignment();
1069 else if (dataset == null && data != null)
1073 throw new IllegalArgumentException("Circular dataset reference");
1075 if (!(data instanceof Alignment))
1078 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1080 dataset = (Alignment) data;
1081 for (int i = 0; i < getHeight(); i++)
1083 SequenceI currentSeq = getSequenceAt(i);
1084 SequenceI dsq = currentSeq.getDatasetSequence();
1087 dsq = currentSeq.createDatasetSequence();
1088 dataset.addSequence(dsq);
1092 while (dsq.getDatasetSequence() != null)
1094 dsq = dsq.getDatasetSequence();
1096 if (dataset.findIndex(dsq) == -1)
1098 dataset.addSequence(dsq);
1103 dataset.addAlignmentRef();
1107 * add dataset sequences to seq for currentSeq and any sequences it references
1109 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1110 Set<SequenceI> seqs, boolean createDatasetSequence)
1112 SequenceI alignedSeq = currentSeq;
1113 if (currentSeq.getDatasetSequence() != null)
1115 currentSeq = currentSeq.getDatasetSequence();
1119 if (createDatasetSequence)
1121 currentSeq = currentSeq.createDatasetSequence();
1125 List<SequenceI> toProcess = new ArrayList<>();
1126 toProcess.add(currentSeq);
1127 while (toProcess.size() > 0)
1130 SequenceI curDs = toProcess.remove(0);
1132 if (!seqs.add(curDs))
1136 // iterate over database references, making sure we add forward referenced
1138 if (curDs.getDBRefs() != null)
1140 for (DBRefEntry dbr : curDs.getDBRefs())
1142 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1144 if (dbr.getMap().getTo() == alignedSeq)
1147 * update mapping to be to the newly created dataset sequence
1149 dbr.getMap().setTo(currentSeq);
1151 if (dbr.getMap().getTo().getDatasetSequence() != null)
1153 throw new Error("Implementation error: Map.getTo() for dbref "
1154 + dbr + " from " + curDs.getName()
1155 + " is not a dataset sequence.");
1157 // we recurse to add all forward references to dataset sequences via
1159 toProcess.add(dbr.getMap().getTo());
1167 * Creates a new dataset for this alignment. Can only be done once - if
1168 * dataset is not null this will not be performed.
1170 public void createDatasetAlignment()
1172 if (dataset != null)
1176 // try to avoid using SequenceI.equals at this stage, it will be expensive
1177 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1179 for (int i = 0; i < getHeight(); i++)
1181 SequenceI currentSeq = getSequenceAt(i);
1182 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1185 // verify all mappings are in dataset
1186 for (AlignedCodonFrame cf : codonFrameList)
1188 for (SequenceToSequenceMapping ssm : cf.getMappings())
1190 if (!seqs.contains(ssm.getFromSeq()))
1192 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1194 if (!seqs.contains(ssm.getMapping().getTo()))
1196 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1200 // finally construct dataset
1201 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1202 // move mappings to the dataset alignment
1203 dataset.codonFrameList = this.codonFrameList;
1204 this.codonFrameList = null;
1208 * reference count for number of alignments referencing this one.
1210 int alignmentRefs = 0;
1213 * increase reference count to this alignment.
1215 private void addAlignmentRef()
1221 public Alignment getDataset()
1227 public boolean padGaps()
1229 boolean modified = false;
1231 // Remove excess gaps from the end of alignment
1235 for (int i = 0; i < sequences.size(); i++)
1237 current = getSequenceAt(i);
1238 for (int j = current.getLength(); j > maxLength; j--)
1241 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1252 for (int i = 0; i < sequences.size(); i++)
1254 current = getSequenceAt(i);
1255 cLength = current.getLength();
1257 if (cLength < maxLength)
1259 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1262 else if (current.getLength() > maxLength)
1264 current.deleteChars(maxLength, current.getLength());
1271 * Justify the sequences to the left or right by deleting and inserting gaps
1272 * before the initial residue or after the terminal residue
1275 * true if alignment padded to right, false to justify to left
1276 * @return true if alignment was changed
1279 public boolean justify(boolean right)
1281 boolean modified = false;
1283 // Remove excess gaps from the end of alignment
1285 int ends[] = new int[sequences.size() * 2];
1287 for (int i = 0; i < sequences.size(); i++)
1289 current = getSequenceAt(i);
1290 // This should really be a sequence method
1291 ends[i * 2] = current.findIndex(current.getStart());
1292 ends[i * 2 + 1] = current
1293 .findIndex(current.getStart() + current.getLength());
1294 boolean hitres = false;
1295 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1297 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1306 ends[i * 2 + 1] = j;
1307 if (j - ends[i * 2] > maxLength)
1309 maxLength = j - ends[i * 2];
1317 // now edit the flanking gaps to justify to either left or right
1318 int cLength, extent, diff;
1319 for (int i = 0; i < sequences.size(); i++)
1321 current = getSequenceAt(i);
1323 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1324 diff = maxLength - cLength; // number of gaps to indent
1325 extent = current.getLength();
1329 if (extent > ends[i * 2 + 1])
1331 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1334 if (ends[i * 2] > diff)
1336 current.deleteChars(0, ends[i * 2] - diff);
1341 if (ends[i * 2] < diff)
1343 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1351 if (ends[i * 2] > 0)
1353 current.deleteChars(0, ends[i * 2]);
1355 ends[i * 2 + 1] -= ends[i * 2];
1356 extent -= ends[i * 2];
1358 if (extent > maxLength)
1360 current.deleteChars(maxLength + 1, extent);
1365 if (extent < maxLength)
1367 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1377 public HiddenSequences getHiddenSequences()
1379 return hiddenSequences;
1383 public HiddenColumns getHiddenColumns()
1389 public CigarArray getCompactAlignment()
1391 synchronized (sequences)
1393 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1395 for (SequenceI seq : sequences)
1397 alseqs[i++] = new SeqCigar(seq);
1399 CigarArray cal = new CigarArray(alseqs);
1400 cal.addOperation(CigarArray.M, getWidth());
1406 public void setProperty(Object key, Object value)
1408 if (alignmentProperties == null)
1410 alignmentProperties = new Hashtable();
1413 alignmentProperties.put(key, value);
1417 public Object getProperty(Object key)
1419 if (alignmentProperties != null)
1421 return alignmentProperties.get(key);
1430 public Hashtable getProperties()
1432 return alignmentProperties;
1436 * Adds the given mapping to the stored set. Note this may be held on the
1437 * dataset alignment.
1440 public void addCodonFrame(AlignedCodonFrame codons)
1442 List<AlignedCodonFrame> acfs = getCodonFrames();
1443 if (codons != null && acfs != null && !acfs.contains(codons))
1453 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1456 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1462 List<AlignedCodonFrame> cframes = new ArrayList<>();
1463 for (AlignedCodonFrame acf : getCodonFrames())
1465 if (acf.involvesSequence(seq))
1474 * Sets the codon frame mappings (replacing any existing mappings). Note the
1475 * mappings are set on the dataset alignment instead if there is one.
1477 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1480 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1482 if (dataset != null)
1484 dataset.setCodonFrames(acfs);
1488 this.codonFrameList = acfs;
1493 * Returns the set of codon frame mappings. Any changes to the returned set
1494 * will affect the alignment. The mappings are held on (and read from) the
1495 * dataset alignment if there is one.
1497 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1500 public List<AlignedCodonFrame> getCodonFrames()
1502 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1503 // this behaviour is currently incorrect. method should return codon frames
1504 // for just the alignment,
1505 // selected from dataset
1506 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1510 * Removes the given mapping from the stored set. Note that the mappings are
1511 * held on the dataset alignment if there is one.
1514 public boolean removeCodonFrame(AlignedCodonFrame codons)
1516 List<AlignedCodonFrame> acfs = getCodonFrames();
1517 if (codons == null || acfs == null)
1521 return acfs.remove(codons);
1525 public void append(AlignmentI toappend)
1527 // TODO JAL-1270 needs test coverage
1528 // currently tested for use in jalview.gui.SequenceFetcher
1529 char oldc = toappend.getGapCharacter();
1530 boolean samegap = oldc == getGapCharacter();
1531 boolean hashidden = toappend.getHiddenSequences() != null
1532 && toappend.getHiddenSequences().hiddenSequences != null;
1533 // get all sequences including any hidden ones
1534 List<SequenceI> sqs = (hashidden)
1535 ? toappend.getHiddenSequences().getFullAlignment()
1537 : toappend.getSequences();
1540 // avoid self append deadlock by
1541 List<SequenceI> toappendsq = new ArrayList<>();
1544 for (SequenceI addedsq : sqs)
1548 addedsq.replace(oldc, gapCharacter);
1550 toappendsq.add(addedsq);
1553 for (SequenceI addedsq : toappendsq)
1555 addSequence(addedsq);
1558 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1559 for (int a = 0; alan != null && a < alan.length; a++)
1561 addAnnotation(alan[a]);
1565 getCodonFrames().addAll(toappend.getCodonFrames());
1567 List<SequenceGroup> sg = toappend.getGroups();
1570 for (SequenceGroup _sg : sg)
1575 if (toappend.getHiddenSequences() != null)
1577 HiddenSequences hs = toappend.getHiddenSequences();
1578 if (hiddenSequences == null)
1580 hiddenSequences = new HiddenSequences(this);
1582 if (hs.hiddenSequences != null)
1584 for (int s = 0; s < hs.hiddenSequences.length; s++)
1586 // hide the newly appended sequence in the alignment
1587 if (hs.hiddenSequences[s] != null)
1589 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1594 if (toappend.getProperties() != null)
1596 // we really can't do very much here - just try to concatenate strings
1597 // where property collisions occur.
1598 Enumeration key = toappend.getProperties().keys();
1599 while (key.hasMoreElements())
1601 Object k = key.nextElement();
1602 Object ourval = this.getProperty(k);
1603 Object toapprop = toappend.getProperty(k);
1606 if (ourval.getClass().equals(toapprop.getClass())
1607 && !ourval.equals(toapprop))
1609 if (ourval instanceof String)
1613 ((String) ourval) + "; " + ((String) toapprop));
1617 if (ourval instanceof Vector)
1620 Enumeration theirv = ((Vector) toapprop).elements();
1621 while (theirv.hasMoreElements())
1623 ((Vector) ourval).addElement(theirv);
1631 // just add new property directly
1632 setProperty(k, toapprop);
1640 public AlignmentAnnotation findOrCreateAnnotation(String name,
1641 String calcId, boolean autoCalc, SequenceI seqRef,
1642 SequenceGroup groupRef)
1644 if (annotations != null)
1646 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1648 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1649 && (calcId == null || annot.getCalcId().equals(calcId))
1650 && annot.sequenceRef == seqRef
1651 && annot.groupRef == groupRef)
1657 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1658 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1659 annot.hasText = false;
1662 annot.setCalcId(calcId);
1664 annot.autoCalculated = autoCalc;
1667 annot.setSequenceRef(seqRef);
1669 annot.groupRef = groupRef;
1670 addAnnotation(annot);
1676 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1678 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1679 if (alignmentAnnotation != null)
1681 return AlignmentAnnotation.findAnnotation(
1682 Arrays.asList(getAlignmentAnnotation()), calcId);
1684 return Arrays.asList(new AlignmentAnnotation[] {});
1688 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1689 String calcId, String label)
1691 return AlignmentAnnotation.findAnnotations(
1692 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1696 public void moveSelectedSequencesByOne(SequenceGroup sg,
1697 Map<SequenceI, SequenceCollectionI> map, boolean up)
1699 synchronized (sequences)
1704 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1706 SequenceI seq = sequences.get(i);
1707 if (!sg.getSequences(map).contains(seq))
1712 SequenceI temp = sequences.get(i - 1);
1713 if (sg.getSequences(null).contains(temp))
1718 sequences.set(i, temp);
1719 sequences.set(i - 1, seq);
1724 for (int i = sequences.size() - 2; i > -1; i--)
1726 SequenceI seq = sequences.get(i);
1727 if (!sg.getSequences(map).contains(seq))
1732 SequenceI temp = sequences.get(i + 1);
1733 if (sg.getSequences(map).contains(temp))
1738 sequences.set(i, temp);
1739 sequences.set(i + 1, seq);
1747 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1749 alignmentAnnotation.validateRangeAndDisplay();
1750 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1752 hasRNAStructure = true;
1756 private SequenceI seqrep = null;
1760 * @return the representative sequence for this group
1763 public SequenceI getSeqrep()
1769 * set the representative sequence for this group. Note - this affects the
1770 * interpretation of the Hidereps attribute.
1773 * the seqrep to set (null means no sequence representative)
1776 public void setSeqrep(SequenceI seqrep)
1778 this.seqrep = seqrep;
1783 * @return true if group has a sequence representative
1786 public boolean hasSeqrep()
1788 return seqrep != null;
1792 public int getEndRes()
1794 return getWidth() - 1;
1798 public int getStartRes()
1804 * In the case of AlignmentI - returns the dataset for the alignment, if set
1807 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1810 public AnnotatedCollectionI getContext()
1816 * Align this alignment like the given (mapped) one.
1819 public int alignAs(AlignmentI al)
1822 * Currently retains unmapped gaps (in introns), regaps mapped regions
1825 return alignAs(al, false, true);
1829 * Align this alignment 'the same as' the given one. Mapped sequences only are
1830 * realigned. If both of the same type (nucleotide/protein) then align both
1831 * identically. If this is nucleotide and the other is protein, make 3 gaps
1832 * for each gap in the protein sequences. If this is protein and the other is
1833 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1834 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1835 * protein to match the relative ordering of codons in the nucleotide.
1837 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1838 * regions are preserved. Gaps that connect introns to exons are treated
1839 * conservatively, i.e. only preserved if both intron and exon gaps are
1840 * preserved. TODO: check caveats below where the implementation fails
1843 * - must have same dataset, and sequences in al must have equivalent
1844 * dataset sequence and start/end bounds under given mapping
1845 * @param preserveMappedGaps
1846 * if true, gaps within and between mapped codons are preserved
1847 * @param preserveUnmappedGaps
1848 * if true, gaps within and between unmapped codons are preserved
1851 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1852 boolean preserveUnmappedGaps)
1854 // TODO should this method signature be the one in the interface?
1855 // JBPComment - yes - neither flag is used, so should be deleted.
1856 boolean thisIsNucleotide = this.isNucleotide();
1857 boolean thatIsProtein = !al.isNucleotide();
1858 if (!thatIsProtein && !thisIsNucleotide)
1860 return AlignmentUtils.alignProteinAsDna(this, al);
1862 else if (thatIsProtein && thisIsNucleotide)
1864 return AlignmentUtils.alignCdsAsProtein(this, al);
1866 return AlignmentUtils.alignAs(this, al);
1870 * Returns the alignment in Fasta format. Behaviour of this method is not
1871 * guaranteed between versions.
1874 public String toString()
1876 return new FastaFile().print(getSequencesArray(), true);
1880 * Returns the set of distinct sequence names. No ordering is guaranteed.
1883 public Set<String> getSequenceNames()
1885 Set<String> names = new HashSet<>();
1886 for (SequenceI seq : getSequences())
1888 names.add(seq.getName());
1894 public boolean hasValidSequence()
1896 boolean hasValidSeq = false;
1897 for (SequenceI seq : getSequences())
1899 if ((seq.getEnd() - seq.getStart()) > 0)
1909 * Update any mappings to 'virtual' sequences to compatible real ones, if
1910 * present in the added sequences. Returns a count of mappings updated.
1916 public int realiseMappings(List<SequenceI> seqs)
1919 for (SequenceI seq : seqs)
1921 for (AlignedCodonFrame mapping : getCodonFrames())
1923 count += mapping.realiseWith(seq);
1930 * Returns the first AlignedCodonFrame that has a mapping between the given
1938 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1940 for (AlignedCodonFrame acf : getCodonFrames())
1942 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1951 public void setHiddenColumns(HiddenColumns cols)
1957 public void setupJPredAlignment()
1959 SequenceI repseq = getSequenceAt(0);
1961 HiddenColumns cs = new HiddenColumns();
1962 cs.hideList(repseq.getInsertions());
1963 setHiddenColumns(cs);
1967 public HiddenColumns propagateInsertions(SequenceI profileseq,
1968 AlignmentView input)
1972 char gc = getGapCharacter();
1973 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1974 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1975 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1976 return propagateInsertions(profileseq, origseq, nview);
1982 * sequence in al which corresponds to origseq
1984 * alignment which is to have gaps inserted into it
1986 * sequence corresponding to profileseq which defines gap map for
1989 private HiddenColumns propagateInsertions(SequenceI profileseq,
1990 SequenceI origseq, HiddenColumns hc)
1992 // take the set of hidden columns, and the set of gaps in origseq,
1993 // and remove all the hidden gaps from hiddenColumns
1995 // first get the gaps as a Bitset
1996 // then calculate hidden ^ not(gap)
1997 BitSet gaps = origseq.gapBitset();
2000 // for each sequence in the alignment, except the profile sequence,
2001 // insert gaps corresponding to each hidden region but where each hidden
2002 // column region is shifted backwards by the number of preceding visible
2003 // gaps update hidden columns at the same time
2004 HiddenColumns newhidden = new HiddenColumns();
2006 int numGapsBefore = 0;
2007 int gapPosition = 0;
2008 Iterator<int[]> it = hc.iterator();
2009 while (it.hasNext())
2011 int[] region = it.next();
2013 // get region coordinates accounting for gaps
2014 // we can rely on gaps not being *in* hidden regions because we already
2016 while (gapPosition < region[0])
2019 if (gaps.get(gapPosition))
2025 int left = region[0] - numGapsBefore;
2026 int right = region[1] - numGapsBefore;
2028 newhidden.hideColumns(left, right);
2029 padGaps(left, right, profileseq);
2035 * Pad gaps in all sequences in alignment except profileseq
2038 * position of first gap to insert
2040 * position of last gap to insert
2042 * sequence not to pad
2044 private void padGaps(int left, int right, SequenceI profileseq)
2046 char gc = getGapCharacter();
2048 // make a string with number of gaps = length of hidden region
2049 StringBuilder sb = new StringBuilder();
2050 for (int g = 0; g < right - left + 1; g++)
2055 // loop over the sequences and pad with gaps where required
2056 for (int s = 0, ns = getHeight(); s < ns; s++)
2058 SequenceI sqobj = getSequenceAt(s);
2059 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2061 String sq = sqobj.getSequenceAsString();
2063 sq.substring(0, left) + sb.toString() + sq.substring(left));
2069 public List<SequenceI> getHmmSequences()
2071 List<SequenceI> result = new ArrayList<>();
2072 for (int i = 0; i < sequences.size(); i++)
2074 SequenceI seq = sequences.get(i);
2075 if (seq.hasHMMProfile())