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();
296 * @return DOCUMENT ME!
299 public List<SequenceGroup> getGroups()
305 public void finalize() throws Throwable
307 if (getDataset() != null)
309 getDataset().removeAlignmentRef();
317 * Defensively nulls out references in case this object is not garbage
320 void nullReferences()
326 hiddenSequences = null;
330 * decrement the alignmentRefs counter by one and null references if it goes
335 private void removeAlignmentRef() throws Throwable
337 if (--alignmentRefs == 0)
344 public void deleteSequence(SequenceI s)
346 synchronized (sequences)
348 deleteSequence(findIndex(s));
353 public void deleteSequence(int i)
355 synchronized (sequences)
357 if (i > -1 && i < getHeight())
360 hiddenSequences.adjustHeightSequenceDeleted(i);
366 public void deleteHiddenSequence(int i)
368 synchronized (sequences)
370 if (i > -1 && i < getHeight())
380 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
383 public SequenceGroup findGroup(SequenceI seq, int position)
385 synchronized (groups)
387 for (SequenceGroup sg : groups)
389 if (sg.getSequences(null).contains(seq))
391 if (position >= sg.getStartRes() && position <= sg.getEndRes())
405 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
408 public SequenceGroup[] findAllGroups(SequenceI s)
410 ArrayList<SequenceGroup> temp = new ArrayList<>();
412 synchronized (groups)
414 int gSize = groups.size();
415 for (int i = 0; i < gSize; i++)
417 SequenceGroup sg = groups.get(i);
418 if (sg == null || sg.getSequences() == null)
420 this.deleteGroup(sg);
425 if (sg.getSequences().contains(s))
431 SequenceGroup[] ret = new SequenceGroup[temp.size()];
432 return temp.toArray(ret);
437 public void addGroup(SequenceGroup sg)
439 synchronized (groups)
441 if (!groups.contains(sg))
443 if (hiddenSequences.getSize() > 0)
445 int i, iSize = sg.getSize();
446 for (i = 0; i < iSize; i++)
448 if (!sequences.contains(sg.getSequenceAt(i)))
450 sg.deleteSequence(sg.getSequenceAt(i), false);
456 if (sg.getSize() < 1)
461 sg.setContext(this, true);
468 * remove any annotation that references gp
471 * (if null, removes all group associated annotation)
473 private void removeAnnotationForGroup(SequenceGroup gp)
475 if (annotations == null || annotations.length == 0)
479 // remove annotation very quickly
480 AlignmentAnnotation[] t,
481 todelete = new AlignmentAnnotation[annotations.length],
482 tokeep = new AlignmentAnnotation[annotations.length];
486 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
488 if (annotations[i].groupRef != null)
490 todelete[p++] = annotations[i];
494 tokeep[k++] = annotations[i];
500 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
502 if (annotations[i].groupRef == gp)
504 todelete[p++] = annotations[i];
508 tokeep[k++] = annotations[i];
514 // clear out the group associated annotation.
515 for (i = 0; i < p; i++)
517 unhookAnnotation(todelete[i]);
520 t = new AlignmentAnnotation[k];
521 for (i = 0; i < k; i++)
530 public void deleteAllGroups()
532 synchronized (groups)
534 if (annotations != null)
536 removeAnnotationForGroup(null);
538 for (SequenceGroup sg : groups)
540 sg.setContext(null, false);
548 public void deleteGroup(SequenceGroup g)
550 synchronized (groups)
552 if (groups.contains(g))
554 removeAnnotationForGroup(g);
556 g.setContext(null, false);
563 public SequenceI findName(String name)
565 return findName(name, false);
571 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
574 public SequenceI findName(String token, boolean b)
576 return findName(null, token, b);
582 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
586 public SequenceI findName(SequenceI startAfter, String token, boolean b)
591 String sqname = null;
592 if (startAfter != null)
594 // try to find the sequence in the alignment
595 boolean matched = false;
596 while (i < sequences.size())
598 if (getSequenceAt(i++) == startAfter)
609 while (i < sequences.size())
611 sq = getSequenceAt(i);
612 sqname = sq.getName();
613 if (sqname.equals(token) // exact match
614 || (b && // allow imperfect matches - case varies
615 (sqname.equalsIgnoreCase(token))))
617 return getSequenceAt(i);
627 public SequenceI[] findSequenceMatch(String name)
629 Vector matches = new Vector();
632 while (i < sequences.size())
634 if (getSequenceAt(i).getName().equals(name))
636 matches.addElement(getSequenceAt(i));
641 SequenceI[] result = new SequenceI[matches.size()];
642 for (i = 0; i < result.length; i++)
644 result[i] = (SequenceI) matches.elementAt(i);
654 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
657 public int findIndex(SequenceI s)
661 while (i < sequences.size())
663 if (s == getSequenceAt(i))
678 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
681 public int findIndex(SearchResultsI results)
685 while (i < sequences.size())
687 if (results.involvesSequence(getSequenceAt(i)))
697 public int getHeight()
699 return sequences.size();
703 public int getAbsoluteHeight()
705 return sequences.size() + getHiddenSequences().getSize();
709 public int getWidth()
713 for (int i = 0; i < sequences.size(); i++)
715 if (getSequenceAt(i).getLength() > maxLength)
717 maxLength = getSequenceAt(i).getLength();
725 public int getWidth()
727 final Wrapper temp = new Wrapper();
729 forEachSequence(new Consumer<SequenceI>()
732 public void accept(SequenceI s)
734 if (s.getLength() > temp.inner)
736 temp.inner = s.getLength();
739 }, 0, sequences.size() - 1);
744 public static class Wrapper
756 public void setGapCharacter(char gc)
759 synchronized (sequences)
761 for (SequenceI seq : sequences)
763 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
764 .replace('-', gc).replace(' ', gc));
772 * @return DOCUMENT ME!
775 public char getGapCharacter()
783 * @see jalview.datamodel.AlignmentI#isAligned()
786 public boolean isAligned()
788 return isAligned(false);
794 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
797 public boolean isAligned(boolean includeHidden)
799 int width = getWidth();
800 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
802 includeHidden = true; // no hidden sequences to check against.
804 for (int i = 0; i < sequences.size(); i++)
806 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
808 if (getSequenceAt(i).getLength() != width)
819 public boolean isHidden(int alignmentIndex)
821 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
825 * Delete all annotations, including auto-calculated if the flag is set true.
826 * Returns true if at least one annotation was deleted, else false.
828 * @param includingAutoCalculated
832 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
834 boolean result = false;
835 for (AlignmentAnnotation alan : getAlignmentAnnotation())
837 if (!alan.autoCalculated || includingAutoCalculated)
839 deleteAnnotation(alan);
849 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
850 * AlignmentAnnotation)
853 public boolean deleteAnnotation(AlignmentAnnotation aa)
855 return deleteAnnotation(aa, true);
859 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
863 if (annotations != null)
865 aSize = annotations.length;
873 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
875 boolean swap = false;
878 for (int i = 0; i < aSize; i++)
880 if (annotations[i] == aa)
885 if (tIndex < temp.length)
887 temp[tIndex++] = annotations[i];
896 unhookAnnotation(aa);
903 * remove any object references associated with this annotation
907 private void unhookAnnotation(AlignmentAnnotation aa)
909 if (aa.sequenceRef != null)
911 aa.sequenceRef.removeAlignmentAnnotation(aa);
913 if (aa.groupRef != null)
915 // probably need to do more here in the future (post 2.5.0)
923 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
924 * AlignmentAnnotation)
927 public void addAnnotation(AlignmentAnnotation aa)
929 addAnnotation(aa, -1);
935 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
936 * AlignmentAnnotation, int)
939 public void addAnnotation(AlignmentAnnotation aa, int pos)
941 if (aa.getRNAStruc() != null)
943 hasRNAStructure = true;
947 if (annotations != null)
949 aSize = annotations.length + 1;
952 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
954 if (pos == -1 || pos >= aSize)
956 temp[aSize - 1] = aa;
965 for (i = 0; i < (aSize - 1); i++, p++)
973 temp[p] = annotations[i];
982 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
984 if (aa == null || annotations == null || annotations.length - 1 < index)
989 int aSize = annotations.length;
990 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
994 for (int i = 0; i < aSize; i++)
1003 temp[i] = annotations[i];
1007 temp[i] = annotations[i - 1];
1016 * returns all annotation on the alignment
1018 public AlignmentAnnotation[] getAlignmentAnnotation()
1024 public boolean isNucleotide()
1030 public boolean hasRNAStructure()
1032 // TODO can it happen that structure is removed from alignment?
1033 return hasRNAStructure;
1037 public void setDataset(AlignmentI data)
1039 if (dataset == null && data == null)
1041 createDatasetAlignment();
1043 else if (dataset == null && data != null)
1047 throw new IllegalArgumentException("Circular dataset reference");
1049 if (!(data instanceof Alignment))
1052 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1054 dataset = (Alignment) data;
1055 for (int i = 0; i < getHeight(); i++)
1057 SequenceI currentSeq = getSequenceAt(i);
1058 SequenceI dsq = currentSeq.getDatasetSequence();
1061 dsq = currentSeq.createDatasetSequence();
1062 dataset.addSequence(dsq);
1066 while (dsq.getDatasetSequence() != null)
1068 dsq = dsq.getDatasetSequence();
1070 if (dataset.findIndex(dsq) == -1)
1072 dataset.addSequence(dsq);
1077 dataset.addAlignmentRef();
1081 * add dataset sequences to seq for currentSeq and any sequences it references
1083 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1084 Set<SequenceI> seqs, boolean createDatasetSequence)
1086 SequenceI alignedSeq = currentSeq;
1087 if (currentSeq.getDatasetSequence() != null)
1089 currentSeq = currentSeq.getDatasetSequence();
1093 if (createDatasetSequence)
1095 currentSeq = currentSeq.createDatasetSequence();
1099 List<SequenceI> toProcess = new ArrayList<>();
1100 toProcess.add(currentSeq);
1101 while (toProcess.size() > 0)
1104 SequenceI curDs = toProcess.remove(0);
1106 if (!seqs.add(curDs))
1110 // iterate over database references, making sure we add forward referenced
1112 if (curDs.getDBRefs() != null)
1114 for (DBRefEntry dbr : curDs.getDBRefs())
1116 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1118 if (dbr.getMap().getTo() == alignedSeq)
1121 * update mapping to be to the newly created dataset sequence
1123 dbr.getMap().setTo(currentSeq);
1125 if (dbr.getMap().getTo().getDatasetSequence() != null)
1127 throw new Error("Implementation error: Map.getTo() for dbref "
1128 + dbr + " from " + curDs.getName()
1129 + " is not a dataset sequence.");
1131 // we recurse to add all forward references to dataset sequences via
1133 toProcess.add(dbr.getMap().getTo());
1141 * Creates a new dataset for this alignment. Can only be done once - if
1142 * dataset is not null this will not be performed.
1144 public void createDatasetAlignment()
1146 if (dataset != null)
1150 // try to avoid using SequenceI.equals at this stage, it will be expensive
1151 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1153 for (int i = 0; i < getHeight(); i++)
1155 SequenceI currentSeq = getSequenceAt(i);
1156 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1159 // verify all mappings are in dataset
1160 for (AlignedCodonFrame cf : codonFrameList)
1162 for (SequenceToSequenceMapping ssm : cf.getMappings())
1164 if (!seqs.contains(ssm.getFromSeq()))
1166 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1168 if (!seqs.contains(ssm.getMapping().getTo()))
1170 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1174 // finally construct dataset
1175 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1176 // move mappings to the dataset alignment
1177 dataset.codonFrameList = this.codonFrameList;
1178 this.codonFrameList = null;
1182 * reference count for number of alignments referencing this one.
1184 int alignmentRefs = 0;
1187 * increase reference count to this alignment.
1189 private void addAlignmentRef()
1195 public Alignment getDataset()
1201 public boolean padGaps()
1203 boolean modified = false;
1205 // Remove excess gaps from the end of alignment
1209 for (int i = 0; i < sequences.size(); i++)
1211 current = getSequenceAt(i);
1212 for (int j = current.getLength(); j > maxLength; j--)
1215 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1226 for (int i = 0; i < sequences.size(); i++)
1228 current = getSequenceAt(i);
1229 cLength = current.getLength();
1231 if (cLength < maxLength)
1233 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1236 else if (current.getLength() > maxLength)
1238 current.deleteChars(maxLength, current.getLength());
1245 * Justify the sequences to the left or right by deleting and inserting gaps
1246 * before the initial residue or after the terminal residue
1249 * true if alignment padded to right, false to justify to left
1250 * @return true if alignment was changed
1253 public boolean justify(boolean right)
1255 boolean modified = false;
1257 // Remove excess gaps from the end of alignment
1259 int ends[] = new int[sequences.size() * 2];
1261 for (int i = 0; i < sequences.size(); i++)
1263 current = getSequenceAt(i);
1264 // This should really be a sequence method
1265 ends[i * 2] = current.findIndex(current.getStart());
1266 ends[i * 2 + 1] = current
1267 .findIndex(current.getStart() + current.getLength());
1268 boolean hitres = false;
1269 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1271 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1280 ends[i * 2 + 1] = j;
1281 if (j - ends[i * 2] > maxLength)
1283 maxLength = j - ends[i * 2];
1291 // now edit the flanking gaps to justify to either left or right
1292 int cLength, extent, diff;
1293 for (int i = 0; i < sequences.size(); i++)
1295 current = getSequenceAt(i);
1297 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1298 diff = maxLength - cLength; // number of gaps to indent
1299 extent = current.getLength();
1303 if (extent > ends[i * 2 + 1])
1305 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1308 if (ends[i * 2] > diff)
1310 current.deleteChars(0, ends[i * 2] - diff);
1315 if (ends[i * 2] < diff)
1317 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1325 if (ends[i * 2] > 0)
1327 current.deleteChars(0, ends[i * 2]);
1329 ends[i * 2 + 1] -= ends[i * 2];
1330 extent -= ends[i * 2];
1332 if (extent > maxLength)
1334 current.deleteChars(maxLength + 1, extent);
1339 if (extent < maxLength)
1341 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1351 public HiddenSequences getHiddenSequences()
1353 return hiddenSequences;
1357 public HiddenColumns getHiddenColumns()
1363 public CigarArray getCompactAlignment()
1365 synchronized (sequences)
1367 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1369 for (SequenceI seq : sequences)
1371 alseqs[i++] = new SeqCigar(seq);
1373 CigarArray cal = new CigarArray(alseqs);
1374 cal.addOperation(CigarArray.M, getWidth());
1380 public void setProperty(Object key, Object value)
1382 if (alignmentProperties == null)
1384 alignmentProperties = new Hashtable();
1387 alignmentProperties.put(key, value);
1391 public Object getProperty(Object key)
1393 if (alignmentProperties != null)
1395 return alignmentProperties.get(key);
1404 public Hashtable getProperties()
1406 return alignmentProperties;
1410 * Adds the given mapping to the stored set. Note this may be held on the
1411 * dataset alignment.
1414 public void addCodonFrame(AlignedCodonFrame codons)
1416 List<AlignedCodonFrame> acfs = getCodonFrames();
1417 if (codons != null && acfs != null && !acfs.contains(codons))
1427 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1430 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1436 List<AlignedCodonFrame> cframes = new ArrayList<>();
1437 for (AlignedCodonFrame acf : getCodonFrames())
1439 if (acf.involvesSequence(seq))
1448 * Sets the codon frame mappings (replacing any existing mappings). Note the
1449 * mappings are set on the dataset alignment instead if there is one.
1451 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1454 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1456 if (dataset != null)
1458 dataset.setCodonFrames(acfs);
1462 this.codonFrameList = acfs;
1467 * Returns the set of codon frame mappings. Any changes to the returned set
1468 * will affect the alignment. The mappings are held on (and read from) the
1469 * dataset alignment if there is one.
1471 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1474 public List<AlignedCodonFrame> getCodonFrames()
1476 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1477 // this behaviour is currently incorrect. method should return codon frames
1478 // for just the alignment,
1479 // selected from dataset
1480 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1484 * Removes the given mapping from the stored set. Note that the mappings are
1485 * held on the dataset alignment if there is one.
1488 public boolean removeCodonFrame(AlignedCodonFrame codons)
1490 List<AlignedCodonFrame> acfs = getCodonFrames();
1491 if (codons == null || acfs == null)
1495 return acfs.remove(codons);
1499 public void append(AlignmentI toappend)
1501 // TODO JAL-1270 needs test coverage
1502 // currently tested for use in jalview.gui.SequenceFetcher
1503 char oldc = toappend.getGapCharacter();
1504 boolean samegap = oldc == getGapCharacter();
1505 boolean hashidden = toappend.getHiddenSequences() != null
1506 && toappend.getHiddenSequences().hiddenSequences != null;
1507 // get all sequences including any hidden ones
1508 List<SequenceI> sqs = (hashidden)
1509 ? toappend.getHiddenSequences().getFullAlignment()
1511 : toappend.getSequences();
1514 // avoid self append deadlock by
1515 List<SequenceI> toappendsq = new ArrayList<>();
1518 for (SequenceI addedsq : sqs)
1522 addedsq.replace(oldc, gapCharacter);
1524 toappendsq.add(addedsq);
1527 for (SequenceI addedsq : toappendsq)
1529 addSequence(addedsq);
1532 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1533 for (int a = 0; alan != null && a < alan.length; a++)
1535 addAnnotation(alan[a]);
1539 getCodonFrames().addAll(toappend.getCodonFrames());
1541 List<SequenceGroup> sg = toappend.getGroups();
1544 for (SequenceGroup _sg : sg)
1549 if (toappend.getHiddenSequences() != null)
1551 HiddenSequences hs = toappend.getHiddenSequences();
1552 if (hiddenSequences == null)
1554 hiddenSequences = new HiddenSequences(this);
1556 if (hs.hiddenSequences != null)
1558 for (int s = 0; s < hs.hiddenSequences.length; s++)
1560 // hide the newly appended sequence in the alignment
1561 if (hs.hiddenSequences[s] != null)
1563 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1568 if (toappend.getProperties() != null)
1570 // we really can't do very much here - just try to concatenate strings
1571 // where property collisions occur.
1572 Enumeration key = toappend.getProperties().keys();
1573 while (key.hasMoreElements())
1575 Object k = key.nextElement();
1576 Object ourval = this.getProperty(k);
1577 Object toapprop = toappend.getProperty(k);
1580 if (ourval.getClass().equals(toapprop.getClass())
1581 && !ourval.equals(toapprop))
1583 if (ourval instanceof String)
1587 ((String) ourval) + "; " + ((String) toapprop));
1591 if (ourval instanceof Vector)
1594 Enumeration theirv = ((Vector) toapprop).elements();
1595 while (theirv.hasMoreElements())
1597 ((Vector) ourval).addElement(theirv);
1605 // just add new property directly
1606 setProperty(k, toapprop);
1614 public AlignmentAnnotation findOrCreateAnnotation(String name,
1615 String calcId, boolean autoCalc, SequenceI seqRef,
1616 SequenceGroup groupRef)
1618 if (annotations != null)
1620 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1622 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1623 && (calcId == null || annot.getCalcId().equals(calcId))
1624 && annot.sequenceRef == seqRef
1625 && annot.groupRef == groupRef)
1631 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1632 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1633 annot.hasText = false;
1636 annot.setCalcId(new String(calcId));
1638 annot.autoCalculated = autoCalc;
1641 annot.setSequenceRef(seqRef);
1643 annot.groupRef = groupRef;
1644 addAnnotation(annot);
1650 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1652 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1653 if (alignmentAnnotation != null)
1655 return AlignmentAnnotation.findAnnotation(
1656 Arrays.asList(getAlignmentAnnotation()), calcId);
1658 return Arrays.asList(new AlignmentAnnotation[] {});
1662 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1663 String calcId, String label)
1665 return AlignmentAnnotation.findAnnotations(
1666 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1670 public void moveSelectedSequencesByOne(SequenceGroup sg,
1671 Map<SequenceI, SequenceCollectionI> map, boolean up)
1673 synchronized (sequences)
1678 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1680 SequenceI seq = sequences.get(i);
1681 if (!sg.getSequences(map).contains(seq))
1686 SequenceI temp = sequences.get(i - 1);
1687 if (sg.getSequences(null).contains(temp))
1692 sequences.set(i, temp);
1693 sequences.set(i - 1, seq);
1698 for (int i = sequences.size() - 2; i > -1; i--)
1700 SequenceI seq = sequences.get(i);
1701 if (!sg.getSequences(map).contains(seq))
1706 SequenceI temp = sequences.get(i + 1);
1707 if (sg.getSequences(map).contains(temp))
1712 sequences.set(i, temp);
1713 sequences.set(i + 1, seq);
1721 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1723 alignmentAnnotation.validateRangeAndDisplay();
1724 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1726 hasRNAStructure = true;
1730 private SequenceI seqrep = null;
1734 * @return the representative sequence for this group
1737 public SequenceI getSeqrep()
1743 * set the representative sequence for this group. Note - this affects the
1744 * interpretation of the Hidereps attribute.
1747 * the seqrep to set (null means no sequence representative)
1750 public void setSeqrep(SequenceI seqrep)
1752 this.seqrep = seqrep;
1757 * @return true if group has a sequence representative
1760 public boolean hasSeqrep()
1762 return seqrep != null;
1766 public int getEndRes()
1768 return getWidth() - 1;
1772 public int getStartRes()
1778 * In the case of AlignmentI - returns the dataset for the alignment, if set
1781 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1784 public AnnotatedCollectionI getContext()
1790 * Align this alignment like the given (mapped) one.
1793 public int alignAs(AlignmentI al)
1796 * Currently retains unmapped gaps (in introns), regaps mapped regions
1799 return alignAs(al, false, true);
1803 * Align this alignment 'the same as' the given one. Mapped sequences only are
1804 * realigned. If both of the same type (nucleotide/protein) then align both
1805 * identically. If this is nucleotide and the other is protein, make 3 gaps
1806 * for each gap in the protein sequences. If this is protein and the other is
1807 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1808 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1809 * protein to match the relative ordering of codons in the nucleotide.
1811 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1812 * regions are preserved. Gaps that connect introns to exons are treated
1813 * conservatively, i.e. only preserved if both intron and exon gaps are
1814 * preserved. TODO: check caveats below where the implementation fails
1817 * - must have same dataset, and sequences in al must have equivalent
1818 * dataset sequence and start/end bounds under given mapping
1819 * @param preserveMappedGaps
1820 * if true, gaps within and between mapped codons are preserved
1821 * @param preserveUnmappedGaps
1822 * if true, gaps within and between unmapped codons are preserved
1825 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1826 boolean preserveUnmappedGaps)
1828 // TODO should this method signature be the one in the interface?
1829 // JBPComment - yes - neither flag is used, so should be deleted.
1830 boolean thisIsNucleotide = this.isNucleotide();
1831 boolean thatIsProtein = !al.isNucleotide();
1832 if (!thatIsProtein && !thisIsNucleotide)
1834 return AlignmentUtils.alignProteinAsDna(this, al);
1836 else if (thatIsProtein && thisIsNucleotide)
1838 return AlignmentUtils.alignCdsAsProtein(this, al);
1840 return AlignmentUtils.alignAs(this, al);
1844 * Returns the alignment in Fasta format. Behaviour of this method is not
1845 * guaranteed between versions.
1848 public String toString()
1850 return new FastaFile().print(getSequencesArray(), true);
1854 * Returns the set of distinct sequence names. No ordering is guaranteed.
1857 public Set<String> getSequenceNames()
1859 Set<String> names = new HashSet<>();
1860 for (SequenceI seq : getSequences())
1862 names.add(seq.getName());
1868 public boolean hasValidSequence()
1870 boolean hasValidSeq = false;
1871 for (SequenceI seq : getSequences())
1873 if ((seq.getEnd() - seq.getStart()) > 0)
1883 * Update any mappings to 'virtual' sequences to compatible real ones, if
1884 * present in the added sequences. Returns a count of mappings updated.
1890 public int realiseMappings(List<SequenceI> seqs)
1893 for (SequenceI seq : seqs)
1895 for (AlignedCodonFrame mapping : getCodonFrames())
1897 count += mapping.realiseWith(seq);
1904 * Returns the first AlignedCodonFrame that has a mapping between the given
1912 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1914 for (AlignedCodonFrame acf : getCodonFrames())
1916 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1925 public void setHiddenColumns(HiddenColumns cols)
1931 public void setupJPredAlignment()
1933 SequenceI repseq = getSequenceAt(0);
1935 HiddenColumns cs = new HiddenColumns();
1936 cs.hideList(repseq.getInsertions());
1937 setHiddenColumns(cs);
1941 public HiddenColumns propagateInsertions(SequenceI profileseq,
1942 AlignmentView input)
1946 char gc = getGapCharacter();
1947 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1948 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1949 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1950 return propagateInsertions(profileseq, origseq, nview);
1956 * sequence in al which corresponds to origseq
1958 * alignment which is to have gaps inserted into it
1960 * sequence corresponding to profileseq which defines gap map for
1963 private HiddenColumns propagateInsertions(SequenceI profileseq,
1964 SequenceI origseq, HiddenColumns hc)
1966 // take the set of hidden columns, and the set of gaps in origseq,
1967 // and remove all the hidden gaps from hiddenColumns
1969 // first get the gaps as a Bitset
1970 // then calculate hidden ^ not(gap)
1971 BitSet gaps = origseq.gapBitset();
1974 // for each sequence in the alignment, except the profile sequence,
1975 // insert gaps corresponding to each hidden region but where each hidden
1976 // column region is shifted backwards by the number of preceding visible
1977 // gaps update hidden columns at the same time
1978 HiddenColumns newhidden = new HiddenColumns();
1980 int numGapsBefore = 0;
1981 int gapPosition = 0;
1982 Iterator<int[]> it = hc.iterator();
1983 while (it.hasNext())
1985 int[] region = it.next();
1987 // get region coordinates accounting for gaps
1988 // we can rely on gaps not being *in* hidden regions because we already
1990 while (gapPosition < region[0])
1993 if (gaps.get(gapPosition))
1999 int left = region[0] - numGapsBefore;
2000 int right = region[1] - numGapsBefore;
2002 newhidden.hideColumns(left, right);
2003 padGaps(left, right, profileseq);
2009 * Pad gaps in all sequences in alignment except profileseq
2012 * position of first gap to insert
2014 * position of last gap to insert
2016 * sequence not to pad
2018 private void padGaps(int left, int right, SequenceI profileseq)
2020 char gc = getGapCharacter();
2022 // make a string with number of gaps = length of hidden region
2023 StringBuilder sb = new StringBuilder();
2024 for (int g = 0; g < right - left + 1; g++)
2029 // loop over the sequences and pad with gaps where required
2030 for (int s = 0, ns = getHeight(); s < ns; s++)
2032 SequenceI sqobj = getSequenceAt(s);
2033 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2035 String sq = sqobj.getSequenceAsString();
2037 sq.substring(0, left) + sb.toString() + sq.substring(left));