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 protected 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);
207 public SequenceI getSequenceAtAbsoluteIndex(int i)
209 SequenceI seq = null;
210 if (getHiddenSequences().getSize() > 0)
212 seq = getHiddenSequences().getHiddenSequence(i);
215 // didn't find the sequence in the hidden sequences, get it from the
217 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
218 seq = getSequenceAt(index);
223 seq = getSequenceAt(i);
229 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
230 * this currently does not recalculate whether or not the alignment is
231 * nucleotide, so mixed alignments may have undefined behaviour.
236 public void addSequence(SequenceI snew)
241 // maintain dataset integrity
242 SequenceI dsseq = snew.getDatasetSequence();
245 // derive new sequence
246 SequenceI adding = snew.deriveSequence();
248 dsseq = snew.getDatasetSequence();
250 if (getDataset().findIndex(dsseq) == -1)
252 getDataset().addSequence(dsseq);
256 if (sequences == null)
258 initAlignment(new SequenceI[] { snew });
262 synchronized (sequences)
267 if (hiddenSequences != null)
269 hiddenSequences.adjustHeightSequenceAdded();
274 public SequenceI replaceSequenceAt(int i, SequenceI snew)
276 synchronized (sequences)
278 if (sequences.size() > i)
280 return sequences.set(i, snew);
286 hiddenSequences.adjustHeightSequenceAdded();
295 * @return DOCUMENT ME!
298 public List<SequenceGroup> getGroups()
304 public void finalize() throws Throwable
306 if (getDataset() != null)
308 getDataset().removeAlignmentRef();
316 * Defensively nulls out references in case this object is not garbage
319 void nullReferences()
325 hiddenSequences = null;
329 * decrement the alignmentRefs counter by one and null references if it goes
334 private void removeAlignmentRef() throws Throwable
336 if (--alignmentRefs == 0)
343 public void deleteSequence(SequenceI s)
345 synchronized (sequences)
347 deleteSequence(findIndex(s));
352 public void deleteSequence(int i)
354 synchronized (sequences)
356 if (i > -1 && i < getHeight())
359 hiddenSequences.adjustHeightSequenceDeleted(i);
365 public void deleteHiddenSequence(int i)
367 synchronized (sequences)
369 if (i > -1 && i < getHeight())
379 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
382 public SequenceGroup findGroup(SequenceI seq, int position)
384 synchronized (groups)
386 for (SequenceGroup sg : groups)
388 if (sg.getSequences(null).contains(seq))
390 if (position >= sg.getStartRes() && position <= sg.getEndRes())
404 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
407 public SequenceGroup[] findAllGroups(SequenceI s)
409 ArrayList<SequenceGroup> temp = new ArrayList<>();
411 synchronized (groups)
413 int gSize = groups.size();
414 for (int i = 0; i < gSize; i++)
416 SequenceGroup sg = groups.get(i);
417 if (sg == null || sg.getSequences() == null)
419 this.deleteGroup(sg);
424 if (sg.getSequences().contains(s))
430 SequenceGroup[] ret = new SequenceGroup[temp.size()];
431 return temp.toArray(ret);
436 public void addGroup(SequenceGroup sg)
438 synchronized (groups)
440 if (!groups.contains(sg))
442 if (hiddenSequences.getSize() > 0)
444 int i, iSize = sg.getSize();
445 for (i = 0; i < iSize; i++)
447 if (!sequences.contains(sg.getSequenceAt(i)))
449 sg.deleteSequence(sg.getSequenceAt(i), false);
455 if (sg.getSize() < 1)
460 sg.setContext(this, true);
467 * remove any annotation that references gp
470 * (if null, removes all group associated annotation)
472 private void removeAnnotationForGroup(SequenceGroup gp)
474 if (annotations == null || annotations.length == 0)
478 // remove annotation very quickly
479 AlignmentAnnotation[] t,
480 todelete = new AlignmentAnnotation[annotations.length],
481 tokeep = new AlignmentAnnotation[annotations.length];
485 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
487 if (annotations[i].groupRef != null)
489 todelete[p++] = annotations[i];
493 tokeep[k++] = annotations[i];
499 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
501 if (annotations[i].groupRef == gp)
503 todelete[p++] = annotations[i];
507 tokeep[k++] = annotations[i];
513 // clear out the group associated annotation.
514 for (i = 0; i < p; i++)
516 unhookAnnotation(todelete[i]);
519 t = new AlignmentAnnotation[k];
520 for (i = 0; i < k; i++)
529 public void deleteAllGroups()
531 synchronized (groups)
533 if (annotations != null)
535 removeAnnotationForGroup(null);
537 for (SequenceGroup sg : groups)
539 sg.setContext(null, false);
547 public void deleteGroup(SequenceGroup g)
549 synchronized (groups)
551 if (groups.contains(g))
553 removeAnnotationForGroup(g);
555 g.setContext(null, false);
562 public SequenceI findName(String name)
564 return findName(name, false);
570 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
573 public SequenceI findName(String token, boolean b)
575 return findName(null, token, b);
581 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
585 public SequenceI findName(SequenceI startAfter, String token, boolean b)
590 String sqname = null;
591 if (startAfter != null)
593 // try to find the sequence in the alignment
594 boolean matched = false;
595 while (i < sequences.size())
597 if (getSequenceAt(i++) == startAfter)
608 while (i < sequences.size())
610 sq = getSequenceAt(i);
611 sqname = sq.getName();
612 if (sqname.equals(token) // exact match
613 || (b && // allow imperfect matches - case varies
614 (sqname.equalsIgnoreCase(token))))
616 return getSequenceAt(i);
626 public SequenceI[] findSequenceMatch(String name)
628 Vector matches = new Vector();
631 while (i < sequences.size())
633 if (getSequenceAt(i).getName().equals(name))
635 matches.addElement(getSequenceAt(i));
640 SequenceI[] result = new SequenceI[matches.size()];
641 for (i = 0; i < result.length; i++)
643 result[i] = (SequenceI) matches.elementAt(i);
653 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
656 public int findIndex(SequenceI s)
660 while (i < sequences.size())
662 if (s == getSequenceAt(i))
677 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
680 public int findIndex(SearchResultsI results)
684 while (i < sequences.size())
686 if (results.involvesSequence(getSequenceAt(i)))
696 public int getHeight()
698 return sequences.size();
702 public int getAbsoluteHeight()
704 return sequences.size() + getHiddenSequences().getSize();
708 public int getWidth()
712 for (int i = 0; i < sequences.size(); i++)
714 if (getSequenceAt(i).getLength() > maxLength)
716 maxLength = getSequenceAt(i).getLength();
730 public void setGapCharacter(char gc)
733 synchronized (sequences)
735 for (SequenceI seq : sequences)
737 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
738 .replace('-', gc).replace(' ', gc));
746 * @return DOCUMENT ME!
749 public char getGapCharacter()
757 * @see jalview.datamodel.AlignmentI#isAligned()
760 public boolean isAligned()
762 return isAligned(false);
768 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
771 public boolean isAligned(boolean includeHidden)
773 int width = getWidth();
774 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
776 includeHidden = true; // no hidden sequences to check against.
778 for (int i = 0; i < sequences.size(); i++)
780 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
782 if (getSequenceAt(i).getLength() != width)
793 public boolean isHidden(int alignmentIndex)
795 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
799 * Delete all annotations, including auto-calculated if the flag is set true.
800 * Returns true if at least one annotation was deleted, else false.
802 * @param includingAutoCalculated
806 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
808 boolean result = false;
809 for (AlignmentAnnotation alan : getAlignmentAnnotation())
811 if (!alan.autoCalculated || includingAutoCalculated)
813 deleteAnnotation(alan);
823 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
824 * AlignmentAnnotation)
827 public boolean deleteAnnotation(AlignmentAnnotation aa)
829 return deleteAnnotation(aa, true);
833 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
837 if (annotations != null)
839 aSize = annotations.length;
847 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
849 boolean swap = false;
852 for (int i = 0; i < aSize; i++)
854 if (annotations[i] == aa)
859 if (tIndex < temp.length)
861 temp[tIndex++] = annotations[i];
870 unhookAnnotation(aa);
877 * remove any object references associated with this annotation
881 private void unhookAnnotation(AlignmentAnnotation aa)
883 if (aa.sequenceRef != null)
885 aa.sequenceRef.removeAlignmentAnnotation(aa);
887 if (aa.groupRef != null)
889 // probably need to do more here in the future (post 2.5.0)
897 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
898 * AlignmentAnnotation)
901 public void addAnnotation(AlignmentAnnotation aa)
903 addAnnotation(aa, -1);
909 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
910 * AlignmentAnnotation, int)
913 public void addAnnotation(AlignmentAnnotation aa, int pos)
915 if (aa.getRNAStruc() != null)
917 hasRNAStructure = true;
921 if (annotations != null)
923 aSize = annotations.length + 1;
926 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
928 if (pos == -1 || pos >= aSize)
930 temp[aSize - 1] = aa;
939 for (i = 0; i < (aSize - 1); i++, p++)
947 temp[p] = annotations[i];
956 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
958 if (aa == null || annotations == null || annotations.length - 1 < index)
963 int aSize = annotations.length;
964 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
968 for (int i = 0; i < aSize; i++)
977 temp[i] = annotations[i];
981 temp[i] = annotations[i - 1];
990 * returns all annotation on the alignment
992 public AlignmentAnnotation[] getAlignmentAnnotation()
998 public boolean isNucleotide()
1004 public boolean hasRNAStructure()
1006 // TODO can it happen that structure is removed from alignment?
1007 return hasRNAStructure;
1011 public void setDataset(AlignmentI data)
1013 if (dataset == null && data == null)
1015 createDatasetAlignment();
1017 else if (dataset == null && data != null)
1021 throw new IllegalArgumentException("Circular dataset reference");
1023 if (!(data instanceof Alignment))
1026 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1028 dataset = (Alignment) data;
1029 for (int i = 0; i < getHeight(); i++)
1031 SequenceI currentSeq = getSequenceAt(i);
1032 SequenceI dsq = currentSeq.getDatasetSequence();
1035 dsq = currentSeq.createDatasetSequence();
1036 dataset.addSequence(dsq);
1040 while (dsq.getDatasetSequence() != null)
1042 dsq = dsq.getDatasetSequence();
1044 if (dataset.findIndex(dsq) == -1)
1046 dataset.addSequence(dsq);
1051 dataset.addAlignmentRef();
1055 * add dataset sequences to seq for currentSeq and any sequences it references
1057 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1058 Set<SequenceI> seqs, boolean createDatasetSequence)
1060 SequenceI alignedSeq = currentSeq;
1061 if (currentSeq.getDatasetSequence() != null)
1063 currentSeq = currentSeq.getDatasetSequence();
1067 if (createDatasetSequence)
1069 currentSeq = currentSeq.createDatasetSequence();
1073 List<SequenceI> toProcess = new ArrayList<>();
1074 toProcess.add(currentSeq);
1075 while (toProcess.size() > 0)
1078 SequenceI curDs = toProcess.remove(0);
1080 if (!seqs.add(curDs))
1084 // iterate over database references, making sure we add forward referenced
1086 if (curDs.getDBRefs() != null)
1088 for (DBRefEntry dbr : curDs.getDBRefs())
1090 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1092 if (dbr.getMap().getTo() == alignedSeq)
1095 * update mapping to be to the newly created dataset sequence
1097 dbr.getMap().setTo(currentSeq);
1099 if (dbr.getMap().getTo().getDatasetSequence() != null)
1101 throw new Error("Implementation error: Map.getTo() for dbref "
1102 + dbr + " from " + curDs.getName()
1103 + " is not a dataset sequence.");
1105 // we recurse to add all forward references to dataset sequences via
1107 toProcess.add(dbr.getMap().getTo());
1115 * Creates a new dataset for this alignment. Can only be done once - if
1116 * dataset is not null this will not be performed.
1118 public void createDatasetAlignment()
1120 if (dataset != null)
1124 // try to avoid using SequenceI.equals at this stage, it will be expensive
1125 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1127 for (int i = 0; i < getHeight(); i++)
1129 SequenceI currentSeq = getSequenceAt(i);
1130 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1133 // verify all mappings are in dataset
1134 for (AlignedCodonFrame cf : codonFrameList)
1136 for (SequenceToSequenceMapping ssm : cf.getMappings())
1138 if (!seqs.contains(ssm.getFromSeq()))
1140 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1142 if (!seqs.contains(ssm.getMapping().getTo()))
1144 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1148 // finally construct dataset
1149 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1150 // move mappings to the dataset alignment
1151 dataset.codonFrameList = this.codonFrameList;
1152 this.codonFrameList = null;
1156 * reference count for number of alignments referencing this one.
1158 int alignmentRefs = 0;
1161 * increase reference count to this alignment.
1163 private void addAlignmentRef()
1169 public Alignment getDataset()
1175 public boolean padGaps()
1177 boolean modified = false;
1179 // Remove excess gaps from the end of alignment
1183 for (int i = 0; i < sequences.size(); i++)
1185 current = getSequenceAt(i);
1186 for (int j = current.getLength(); j > maxLength; j--)
1189 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1200 for (int i = 0; i < sequences.size(); i++)
1202 current = getSequenceAt(i);
1203 cLength = current.getLength();
1205 if (cLength < maxLength)
1207 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1210 else if (current.getLength() > maxLength)
1212 current.deleteChars(maxLength, current.getLength());
1219 * Justify the sequences to the left or right by deleting and inserting gaps
1220 * before the initial residue or after the terminal residue
1223 * true if alignment padded to right, false to justify to left
1224 * @return true if alignment was changed
1227 public boolean justify(boolean right)
1229 boolean modified = false;
1231 // Remove excess gaps from the end of alignment
1233 int ends[] = new int[sequences.size() * 2];
1235 for (int i = 0; i < sequences.size(); i++)
1237 current = getSequenceAt(i);
1238 // This should really be a sequence method
1239 ends[i * 2] = current.findIndex(current.getStart());
1240 ends[i * 2 + 1] = current
1241 .findIndex(current.getStart() + current.getLength());
1242 boolean hitres = false;
1243 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1245 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1254 ends[i * 2 + 1] = j;
1255 if (j - ends[i * 2] > maxLength)
1257 maxLength = j - ends[i * 2];
1265 // now edit the flanking gaps to justify to either left or right
1266 int cLength, extent, diff;
1267 for (int i = 0; i < sequences.size(); i++)
1269 current = getSequenceAt(i);
1271 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1272 diff = maxLength - cLength; // number of gaps to indent
1273 extent = current.getLength();
1277 if (extent > ends[i * 2 + 1])
1279 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1282 if (ends[i * 2] > diff)
1284 current.deleteChars(0, ends[i * 2] - diff);
1289 if (ends[i * 2] < diff)
1291 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1299 if (ends[i * 2] > 0)
1301 current.deleteChars(0, ends[i * 2]);
1303 ends[i * 2 + 1] -= ends[i * 2];
1304 extent -= ends[i * 2];
1306 if (extent > maxLength)
1308 current.deleteChars(maxLength + 1, extent);
1313 if (extent < maxLength)
1315 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1325 public HiddenSequences getHiddenSequences()
1327 return hiddenSequences;
1331 public HiddenColumns getHiddenColumns()
1337 public CigarArray getCompactAlignment()
1339 synchronized (sequences)
1341 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1343 for (SequenceI seq : sequences)
1345 alseqs[i++] = new SeqCigar(seq);
1347 CigarArray cal = new CigarArray(alseqs);
1348 cal.addOperation(CigarArray.M, getWidth());
1354 public void setProperty(Object key, Object value)
1356 if (alignmentProperties == null)
1358 alignmentProperties = new Hashtable();
1361 alignmentProperties.put(key, value);
1365 public Object getProperty(Object key)
1367 if (alignmentProperties != null)
1369 return alignmentProperties.get(key);
1378 public Hashtable getProperties()
1380 return alignmentProperties;
1384 * Adds the given mapping to the stored set. Note this may be held on the
1385 * dataset alignment.
1388 public void addCodonFrame(AlignedCodonFrame codons)
1390 List<AlignedCodonFrame> acfs = getCodonFrames();
1391 if (codons != null && acfs != null && !acfs.contains(codons))
1401 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1404 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1410 List<AlignedCodonFrame> cframes = new ArrayList<>();
1411 for (AlignedCodonFrame acf : getCodonFrames())
1413 if (acf.involvesSequence(seq))
1422 * Sets the codon frame mappings (replacing any existing mappings). Note the
1423 * mappings are set on the dataset alignment instead if there is one.
1425 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1428 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1430 if (dataset != null)
1432 dataset.setCodonFrames(acfs);
1436 this.codonFrameList = acfs;
1441 * Returns the set of codon frame mappings. Any changes to the returned set
1442 * will affect the alignment. The mappings are held on (and read from) the
1443 * dataset alignment if there is one.
1445 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1448 public List<AlignedCodonFrame> getCodonFrames()
1450 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1451 // this behaviour is currently incorrect. method should return codon frames
1452 // for just the alignment,
1453 // selected from dataset
1454 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1458 * Removes the given mapping from the stored set. Note that the mappings are
1459 * held on the dataset alignment if there is one.
1462 public boolean removeCodonFrame(AlignedCodonFrame codons)
1464 List<AlignedCodonFrame> acfs = getCodonFrames();
1465 if (codons == null || acfs == null)
1469 return acfs.remove(codons);
1473 public void append(AlignmentI toappend)
1475 // TODO JAL-1270 needs test coverage
1476 // currently tested for use in jalview.gui.SequenceFetcher
1477 char oldc = toappend.getGapCharacter();
1478 boolean samegap = oldc == getGapCharacter();
1479 boolean hashidden = toappend.getHiddenSequences() != null
1480 && toappend.getHiddenSequences().hiddenSequences != null;
1481 // get all sequences including any hidden ones
1482 List<SequenceI> sqs = (hashidden)
1483 ? toappend.getHiddenSequences().getFullAlignment()
1485 : toappend.getSequences();
1488 // avoid self append deadlock by
1489 List<SequenceI> toappendsq = new ArrayList<>();
1492 for (SequenceI addedsq : sqs)
1496 addedsq.replace(oldc, gapCharacter);
1498 toappendsq.add(addedsq);
1501 for (SequenceI addedsq : toappendsq)
1503 addSequence(addedsq);
1506 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1507 for (int a = 0; alan != null && a < alan.length; a++)
1509 addAnnotation(alan[a]);
1513 getCodonFrames().addAll(toappend.getCodonFrames());
1515 List<SequenceGroup> sg = toappend.getGroups();
1518 for (SequenceGroup _sg : sg)
1523 if (toappend.getHiddenSequences() != null)
1525 HiddenSequences hs = toappend.getHiddenSequences();
1526 if (hiddenSequences == null)
1528 hiddenSequences = new HiddenSequences(this);
1530 if (hs.hiddenSequences != null)
1532 for (int s = 0; s < hs.hiddenSequences.length; s++)
1534 // hide the newly appended sequence in the alignment
1535 if (hs.hiddenSequences[s] != null)
1537 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1542 if (toappend.getProperties() != null)
1544 // we really can't do very much here - just try to concatenate strings
1545 // where property collisions occur.
1546 Enumeration key = toappend.getProperties().keys();
1547 while (key.hasMoreElements())
1549 Object k = key.nextElement();
1550 Object ourval = this.getProperty(k);
1551 Object toapprop = toappend.getProperty(k);
1554 if (ourval.getClass().equals(toapprop.getClass())
1555 && !ourval.equals(toapprop))
1557 if (ourval instanceof String)
1561 ((String) ourval) + "; " + ((String) toapprop));
1565 if (ourval instanceof Vector)
1568 Enumeration theirv = ((Vector) toapprop).elements();
1569 while (theirv.hasMoreElements())
1571 ((Vector) ourval).addElement(theirv);
1579 // just add new property directly
1580 setProperty(k, toapprop);
1588 public AlignmentAnnotation findOrCreateAnnotation(String name,
1589 String calcId, boolean autoCalc, SequenceI seqRef,
1590 SequenceGroup groupRef)
1592 if (annotations != null)
1594 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1596 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1597 && (calcId == null || annot.getCalcId().equals(calcId))
1598 && annot.sequenceRef == seqRef
1599 && annot.groupRef == groupRef)
1605 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1606 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1607 annot.hasText = false;
1608 annot.setCalcId(new String(calcId));
1609 annot.autoCalculated = autoCalc;
1612 annot.setSequenceRef(seqRef);
1614 annot.groupRef = groupRef;
1615 addAnnotation(annot);
1621 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1623 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1624 if (alignmentAnnotation != null)
1626 return AlignmentAnnotation.findAnnotation(
1627 Arrays.asList(getAlignmentAnnotation()), calcId);
1629 return Arrays.asList(new AlignmentAnnotation[] {});
1633 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1634 String calcId, String label)
1636 return AlignmentAnnotation.findAnnotations(
1637 Arrays.asList(getAlignmentAnnotation()), seq, calcId, label);
1641 public void moveSelectedSequencesByOne(SequenceGroup sg,
1642 Map<SequenceI, SequenceCollectionI> map, boolean up)
1644 synchronized (sequences)
1649 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1651 SequenceI seq = sequences.get(i);
1652 if (!sg.getSequences(map).contains(seq))
1657 SequenceI temp = sequences.get(i - 1);
1658 if (sg.getSequences(null).contains(temp))
1663 sequences.set(i, temp);
1664 sequences.set(i - 1, seq);
1669 for (int i = sequences.size() - 2; i > -1; i--)
1671 SequenceI seq = sequences.get(i);
1672 if (!sg.getSequences(map).contains(seq))
1677 SequenceI temp = sequences.get(i + 1);
1678 if (sg.getSequences(map).contains(temp))
1683 sequences.set(i, temp);
1684 sequences.set(i + 1, seq);
1692 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1694 alignmentAnnotation.validateRangeAndDisplay();
1695 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1697 hasRNAStructure = true;
1701 private SequenceI seqrep = null;
1705 * @return the representative sequence for this group
1708 public SequenceI getSeqrep()
1714 * set the representative sequence for this group. Note - this affects the
1715 * interpretation of the Hidereps attribute.
1718 * the seqrep to set (null means no sequence representative)
1721 public void setSeqrep(SequenceI seqrep)
1723 this.seqrep = seqrep;
1728 * @return true if group has a sequence representative
1731 public boolean hasSeqrep()
1733 return seqrep != null;
1737 public int getEndRes()
1739 return getWidth() - 1;
1743 public int getStartRes()
1749 * In the case of AlignmentI - returns the dataset for the alignment, if set
1752 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1755 public AnnotatedCollectionI getContext()
1761 * Align this alignment like the given (mapped) one.
1764 public int alignAs(AlignmentI al)
1767 * Currently retains unmapped gaps (in introns), regaps mapped regions
1770 return alignAs(al, false, true);
1774 * Align this alignment 'the same as' the given one. Mapped sequences only are
1775 * realigned. If both of the same type (nucleotide/protein) then align both
1776 * identically. If this is nucleotide and the other is protein, make 3 gaps
1777 * for each gap in the protein sequences. If this is protein and the other is
1778 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1779 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1780 * protein to match the relative ordering of codons in the nucleotide.
1782 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1783 * regions are preserved. Gaps that connect introns to exons are treated
1784 * conservatively, i.e. only preserved if both intron and exon gaps are
1785 * preserved. TODO: check caveats below where the implementation fails
1788 * - must have same dataset, and sequences in al must have equivalent
1789 * dataset sequence and start/end bounds under given mapping
1790 * @param preserveMappedGaps
1791 * if true, gaps within and between mapped codons are preserved
1792 * @param preserveUnmappedGaps
1793 * if true, gaps within and between unmapped codons are preserved
1796 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1797 boolean preserveUnmappedGaps)
1799 // TODO should this method signature be the one in the interface?
1800 // JBPComment - yes - neither flag is used, so should be deleted.
1801 boolean thisIsNucleotide = this.isNucleotide();
1802 boolean thatIsProtein = !al.isNucleotide();
1803 if (!thatIsProtein && !thisIsNucleotide)
1805 return AlignmentUtils.alignProteinAsDna(this, al);
1807 else if (thatIsProtein && thisIsNucleotide)
1809 return AlignmentUtils.alignCdsAsProtein(this, al);
1811 return AlignmentUtils.alignAs(this, al);
1815 * Returns the alignment in Fasta format. Behaviour of this method is not
1816 * guaranteed between versions.
1819 public String toString()
1821 return new FastaFile().print(getSequencesArray(), true);
1825 * Returns the set of distinct sequence names. No ordering is guaranteed.
1828 public Set<String> getSequenceNames()
1830 Set<String> names = new HashSet<>();
1831 for (SequenceI seq : getSequences())
1833 names.add(seq.getName());
1839 public boolean hasValidSequence()
1841 boolean hasValidSeq = false;
1842 for (SequenceI seq : getSequences())
1844 if ((seq.getEnd() - seq.getStart()) > 0)
1854 * Update any mappings to 'virtual' sequences to compatible real ones, if
1855 * present in the added sequences. Returns a count of mappings updated.
1861 public int realiseMappings(List<SequenceI> seqs)
1864 for (SequenceI seq : seqs)
1866 for (AlignedCodonFrame mapping : getCodonFrames())
1868 count += mapping.realiseWith(seq);
1875 * Returns the first AlignedCodonFrame that has a mapping between the given
1883 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1885 for (AlignedCodonFrame acf : getCodonFrames())
1887 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1896 public void setHiddenColumns(HiddenColumns cols)
1902 public void setupJPredAlignment()
1904 SequenceI repseq = getSequenceAt(0);
1906 HiddenColumns cs = new HiddenColumns();
1907 cs.hideList(repseq.getInsertions());
1908 setHiddenColumns(cs);
1912 public HiddenColumns propagateInsertions(SequenceI profileseq,
1913 AlignmentView input)
1917 char gc = getGapCharacter();
1918 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1919 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1920 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1921 return propagateInsertions(profileseq, origseq, nview);
1927 * sequence in al which corresponds to origseq
1929 * alignment which is to have gaps inserted into it
1931 * sequence corresponding to profileseq which defines gap map for
1934 private HiddenColumns propagateInsertions(SequenceI profileseq,
1935 SequenceI origseq, HiddenColumns hc)
1937 // take the set of hidden columns, and the set of gaps in origseq,
1938 // and remove all the hidden gaps from hiddenColumns
1940 // first get the gaps as a Bitset
1941 // then calculate hidden ^ not(gap)
1942 BitSet gaps = origseq.gapBitset();
1945 // for each sequence in the alignment, except the profile sequence,
1946 // insert gaps corresponding to each hidden region but where each hidden
1947 // column region is shifted backwards by the number of preceding visible
1948 // gaps update hidden columns at the same time
1949 HiddenColumns newhidden = new HiddenColumns();
1951 int numGapsBefore = 0;
1952 int gapPosition = 0;
1953 Iterator<int[]> it = hc.iterator();
1954 while (it.hasNext())
1956 int[] region = it.next();
1958 // get region coordinates accounting for gaps
1959 // we can rely on gaps not being *in* hidden regions because we already
1961 while (gapPosition < region[0])
1964 if (gaps.get(gapPosition))
1970 int left = region[0] - numGapsBefore;
1971 int right = region[1] - numGapsBefore;
1973 newhidden.hideColumns(left, right);
1974 padGaps(left, right, profileseq);
1980 * Pad gaps in all sequences in alignment except profileseq
1983 * position of first gap to insert
1985 * position of last gap to insert
1987 * sequence not to pad
1989 private void padGaps(int left, int right, SequenceI profileseq)
1991 char gc = getGapCharacter();
1993 // make a string with number of gaps = length of hidden region
1994 StringBuilder sb = new StringBuilder();
1995 for (int g = 0; g < right - left + 1; g++)
2000 // loop over the sequences and pad with gaps where required
2001 for (int s = 0, ns = getHeight(); s < ns; s++)
2003 SequenceI sqobj = getSequenceAt(s);
2004 if ((sqobj != profileseq) && (sqobj.getLength() >= left))
2006 String sq = sqobj.getSequenceAsString();
2008 sq.substring(0, left) + sb.toString() + sq.substring(left));