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.Collections;
32 import java.util.Enumeration;
33 import java.util.HashSet;
34 import java.util.Hashtable;
35 import java.util.List;
38 import java.util.Vector;
41 * Data structure to hold and manipulate a multiple sequence alignment
47 public class Alignment implements AlignmentI
49 private Alignment dataset;
51 protected List<SequenceI> sequences;
53 protected List<SequenceGroup> groups;
55 protected char gapCharacter = '-';
57 private boolean nucleotide = true;
59 public boolean hasRNAStructure = false;
61 public AlignmentAnnotation[] annotations;
63 HiddenSequences hiddenSequences;
65 HiddenColumns hiddenCols;
67 public Hashtable alignmentProperties;
69 private List<AlignedCodonFrame> codonFrameList;
71 private void initAlignment(SequenceI[] seqs)
73 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
74 hiddenSequences = new HiddenSequences(this);
75 hiddenCols = new HiddenColumns();
76 codonFrameList = new ArrayList<>();
78 nucleotide = Comparison.isNucleotide(seqs);
80 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
82 for (int i = 0; i < seqs.length; i++)
84 sequences.add(seqs[i]);
90 * Make a 'copy' alignment - sequences have new copies of features and
91 * annotations, but share the original dataset sequences.
93 public Alignment(AlignmentI al)
95 SequenceI[] seqs = al.getSequencesArray();
96 for (int i = 0; i < seqs.length; i++)
98 seqs[i] = new Sequence(seqs[i]);
104 * Share the same dataset sequence mappings (if any).
106 if (dataset == null && al.getDataset() == null)
108 this.setCodonFrames(al.getCodonFrames());
113 * Make an alignment from an array of Sequences.
117 public Alignment(SequenceI[] seqs)
123 * Make a new alignment from an array of SeqCigars
128 public Alignment(SeqCigar[] alseqs)
130 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
131 gapCharacter, new HiddenColumns(), null);
136 * Make a new alignment from an CigarArray JBPNote - can only do this when
137 * compactAlignment does not contain hidden regions. JBPNote - must also check
138 * that compactAlignment resolves to a set of SeqCigars - or construct them
141 * @param compactAlignment
144 public static AlignmentI createAlignment(CigarArray compactAlignment)
148 .getString("error.alignment_cigararray_not_implemented"));
149 // this(compactAlignment.refCigars);
153 public List<SequenceI> getSequences()
159 public List<SequenceI> getSequences(
160 Map<SequenceI, SequenceCollectionI> hiddenReps)
162 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
168 public SequenceI[] getSequencesArray()
170 if (sequences == null)
174 synchronized (sequences)
176 return sequences.toArray(new SequenceI[sequences.size()]);
181 * Returns a map of lists of sequences keyed by sequence name.
186 public Map<String, List<SequenceI>> getSequencesByName()
188 return AlignmentUtils.getSequencesByName(this);
193 public SequenceI getSequenceAt(int i)
195 synchronized (sequences)
197 if (i > -1 && i < sequences.size())
199 return sequences.get(i);
206 public SequenceI getSequenceAtAbsoluteIndex(int i)
208 SequenceI seq = null;
209 if (getHiddenSequences().getSize() > 0)
211 seq = getHiddenSequences().getHiddenSequence(i);
214 // didn't find the sequence in the hidden sequences, get it from the
216 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
217 seq = getSequenceAt(index);
222 seq = getSequenceAt(i);
228 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
229 * this currently does not recalculate whether or not the alignment is
230 * nucleotide, so mixed alignments may have undefined behaviour.
235 public void addSequence(SequenceI snew)
240 // maintain dataset integrity
241 SequenceI dsseq = snew.getDatasetSequence();
244 // derive new sequence
245 SequenceI adding = snew.deriveSequence();
247 dsseq = snew.getDatasetSequence();
249 if (getDataset().findIndex(dsseq) == -1)
251 getDataset().addSequence(dsseq);
255 if (sequences == null)
257 initAlignment(new SequenceI[] { snew });
261 synchronized (sequences)
266 if (hiddenSequences != null)
268 hiddenSequences.adjustHeightSequenceAdded();
273 public SequenceI replaceSequenceAt(int i, SequenceI snew)
275 synchronized (sequences)
277 if (sequences.size() > i)
279 return sequences.set(i, snew);
285 hiddenSequences.adjustHeightSequenceAdded();
292 public void insertSequenceAt(int i, SequenceI snew)
294 synchronized (sequences)
296 if (sequences.size() > i)
298 sequences.add(i, snew);
305 hiddenSequences.adjustHeightSequenceAdded();
314 * @return DOCUMENT ME!
317 public List<SequenceGroup> getGroups()
323 public void finalize() throws Throwable
325 if (getDataset() != null)
327 getDataset().removeAlignmentRef();
335 * Defensively nulls out references in case this object is not garbage
338 void nullReferences()
344 hiddenSequences = null;
348 * decrement the alignmentRefs counter by one and null references if it goes
353 private void removeAlignmentRef() throws Throwable
355 if (--alignmentRefs == 0)
362 public void deleteSequence(SequenceI s)
364 synchronized (sequences)
366 deleteSequence(findIndex(s));
371 public void deleteSequence(int i)
373 synchronized (sequences)
375 if (i > -1 && i < getHeight())
378 hiddenSequences.adjustHeightSequenceDeleted(i);
384 public void deleteHiddenSequence(int i)
386 synchronized (sequences)
388 if (i > -1 && i < getHeight())
398 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
401 public SequenceGroup findGroup(SequenceI seq, int position)
403 synchronized (groups)
405 for (SequenceGroup sg : groups)
407 if (sg.getSequences(null).contains(seq))
409 if (position >= sg.getStartRes() && position <= sg.getEndRes())
423 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
426 public SequenceGroup[] findAllGroups(SequenceI s)
428 ArrayList<SequenceGroup> temp = new ArrayList<>();
430 synchronized (groups)
432 int gSize = groups.size();
433 for (int i = 0; i < gSize; i++)
435 SequenceGroup sg = groups.get(i);
436 if (sg == null || sg.getSequences() == null)
438 this.deleteGroup(sg);
443 if (sg.getSequences().contains(s))
449 SequenceGroup[] ret = new SequenceGroup[temp.size()];
450 return temp.toArray(ret);
455 public void addGroup(SequenceGroup sg)
457 synchronized (groups)
459 if (!groups.contains(sg))
461 if (hiddenSequences.getSize() > 0)
463 int i, iSize = sg.getSize();
464 for (i = 0; i < iSize; i++)
466 if (!sequences.contains(sg.getSequenceAt(i)))
468 sg.deleteSequence(sg.getSequenceAt(i), false);
474 if (sg.getSize() < 1)
479 sg.setContext(this, true);
486 * remove any annotation that references gp
489 * (if null, removes all group associated annotation)
491 private void removeAnnotationForGroup(SequenceGroup gp)
493 if (annotations == null || annotations.length == 0)
497 // remove annotation very quickly
498 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
502 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
504 if (annotations[i].groupRef != null)
506 todelete[p++] = annotations[i];
510 tokeep[k++] = annotations[i];
516 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
518 if (annotations[i].groupRef == gp)
520 todelete[p++] = annotations[i];
524 tokeep[k++] = annotations[i];
530 // clear out the group associated annotation.
531 for (i = 0; i < p; i++)
533 unhookAnnotation(todelete[i]);
536 t = new AlignmentAnnotation[k];
537 for (i = 0; i < k; i++)
546 public void deleteAllGroups()
548 synchronized (groups)
550 if (annotations != null)
552 removeAnnotationForGroup(null);
554 for (SequenceGroup sg : groups)
556 sg.setContext(null, false);
564 public void deleteGroup(SequenceGroup g)
566 synchronized (groups)
568 if (groups.contains(g))
570 removeAnnotationForGroup(g);
572 g.setContext(null, false);
579 public SequenceI findName(String name)
581 return findName(name, false);
587 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
590 public SequenceI findName(String token, boolean b)
592 return findName(null, token, b);
598 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
602 public SequenceI findName(SequenceI startAfter, String token, boolean b)
607 String sqname = null;
608 if (startAfter != null)
610 // try to find the sequence in the alignment
611 boolean matched = false;
612 while (i < sequences.size())
614 if (getSequenceAt(i++) == startAfter)
625 while (i < sequences.size())
627 sq = getSequenceAt(i);
628 sqname = sq.getName();
629 if (sqname.equals(token) // exact match
630 || (b && // allow imperfect matches - case varies
631 (sqname.equalsIgnoreCase(token))))
633 return getSequenceAt(i);
643 public SequenceI[] findSequenceMatch(String name)
645 Vector matches = new Vector();
648 while (i < sequences.size())
650 if (getSequenceAt(i).getName().equals(name))
652 matches.addElement(getSequenceAt(i));
657 SequenceI[] result = new SequenceI[matches.size()];
658 for (i = 0; i < result.length; i++)
660 result[i] = (SequenceI) matches.elementAt(i);
670 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
673 public int findIndex(SequenceI s)
677 while (i < sequences.size())
679 if (s == getSequenceAt(i))
694 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
697 public int findIndex(SearchResultsI results)
701 while (i < sequences.size())
703 if (results.involvesSequence(getSequenceAt(i)))
714 public int getHeight()
716 return sequences.size();
720 public int getAbsoluteHeight()
722 return sequences.size() + getHiddenSequences().getSize();
726 public int getWidth()
730 for (int i = 0; i < sequences.size(); i++)
732 if (getSequenceAt(i).getLength() > maxLength)
734 maxLength = getSequenceAt(i).getLength();
748 public void setGapCharacter(char gc)
751 synchronized (sequences)
753 for (SequenceI seq : sequences)
755 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
756 .replace('-', gc).replace(' ', gc));
764 * @return DOCUMENT ME!
767 public char getGapCharacter()
775 * @see jalview.datamodel.AlignmentI#isAligned()
778 public boolean isAligned()
780 return isAligned(false);
786 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
789 public boolean isAligned(boolean includeHidden)
791 int width = getWidth();
792 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
794 includeHidden = true; // no hidden sequences to check against.
796 for (int i = 0; i < sequences.size(); i++)
798 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
800 if (getSequenceAt(i).getLength() != width)
811 public boolean isHidden(int alignmentIndex)
813 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
817 * Delete all annotations, including auto-calculated if the flag is set true.
818 * Returns true if at least one annotation was deleted, else false.
820 * @param includingAutoCalculated
824 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
826 boolean result = false;
827 for (AlignmentAnnotation alan : getAlignmentAnnotation())
829 if (!alan.autoCalculated || includingAutoCalculated)
831 deleteAnnotation(alan);
841 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
842 * AlignmentAnnotation)
845 public boolean deleteAnnotation(AlignmentAnnotation aa)
847 return deleteAnnotation(aa, true);
851 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
855 if (annotations != null)
857 aSize = annotations.length;
865 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
867 boolean swap = false;
870 for (int i = 0; i < aSize; i++)
872 if (annotations[i] == aa)
877 if (tIndex < temp.length)
879 temp[tIndex++] = annotations[i];
888 unhookAnnotation(aa);
895 * remove any object references associated with this annotation
899 private void unhookAnnotation(AlignmentAnnotation aa)
901 if (aa.sequenceRef != null)
903 aa.sequenceRef.removeAlignmentAnnotation(aa);
905 if (aa.groupRef != null)
907 // probably need to do more here in the future (post 2.5.0)
915 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
916 * AlignmentAnnotation)
919 public void addAnnotation(AlignmentAnnotation aa)
921 addAnnotation(aa, -1);
927 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
928 * AlignmentAnnotation, int)
931 public void addAnnotation(AlignmentAnnotation aa, int pos)
933 if (aa.getRNAStruc() != null)
935 hasRNAStructure = true;
939 if (annotations != null)
941 aSize = annotations.length + 1;
944 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
946 if (pos == -1 || pos >= aSize)
948 temp[aSize - 1] = aa;
957 for (i = 0; i < (aSize - 1); i++, p++)
965 temp[p] = annotations[i];
974 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
976 if (aa == null || annotations == null || annotations.length - 1 < index)
981 int aSize = annotations.length;
982 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
986 for (int i = 0; i < aSize; i++)
995 temp[i] = annotations[i];
999 temp[i] = annotations[i - 1];
1008 * returns all annotation on the alignment
1010 public AlignmentAnnotation[] getAlignmentAnnotation()
1016 public boolean isNucleotide()
1022 public boolean hasRNAStructure()
1024 // TODO can it happen that structure is removed from alignment?
1025 return hasRNAStructure;
1029 public void setDataset(AlignmentI data)
1031 if (dataset == null && data == null)
1033 createDatasetAlignment();
1035 else if (dataset == null && data != null)
1039 throw new IllegalArgumentException("Circular dataset reference");
1041 if (!(data instanceof Alignment))
1044 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1046 dataset = (Alignment) data;
1047 for (int i = 0; i < getHeight(); i++)
1049 SequenceI currentSeq = getSequenceAt(i);
1050 SequenceI dsq = currentSeq.getDatasetSequence();
1053 dsq = currentSeq.createDatasetSequence();
1054 dataset.addSequence(dsq);
1058 while (dsq.getDatasetSequence() != null)
1060 dsq = dsq.getDatasetSequence();
1062 if (dataset.findIndex(dsq) == -1)
1064 dataset.addSequence(dsq);
1069 dataset.addAlignmentRef();
1073 * add dataset sequences to seq for currentSeq and any sequences it references
1075 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1076 Set<SequenceI> seqs, boolean createDatasetSequence)
1078 SequenceI alignedSeq = currentSeq;
1079 if (currentSeq.getDatasetSequence() != null)
1081 currentSeq = currentSeq.getDatasetSequence();
1085 if (createDatasetSequence)
1087 currentSeq = currentSeq.createDatasetSequence();
1090 if (seqs.contains(currentSeq))
1094 List<SequenceI> toProcess = new ArrayList<>();
1095 toProcess.add(currentSeq);
1096 while (toProcess.size() > 0)
1099 SequenceI curDs = toProcess.remove(0);
1100 if (seqs.contains(curDs))
1105 // iterate over database references, making sure we add forward referenced
1107 if (curDs.getDBRefs() != null)
1109 for (DBRefEntry dbr : curDs.getDBRefs())
1111 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1113 if (dbr.getMap().getTo() == alignedSeq)
1116 * update mapping to be to the newly created dataset sequence
1118 dbr.getMap().setTo(currentSeq);
1120 if (dbr.getMap().getTo().getDatasetSequence() != null)
1123 "Implementation error: Map.getTo() for dbref " + dbr
1124 + " from " + curDs.getName()
1125 + " is not a dataset sequence.");
1127 // we recurse to add all forward references to dataset sequences via
1129 toProcess.add(dbr.getMap().getTo());
1137 * Creates a new dataset for this alignment. Can only be done once - if
1138 * dataset is not null this will not be performed.
1140 public void createDatasetAlignment()
1142 if (dataset != null)
1146 // try to avoid using SequenceI.equals at this stage, it will be expensive
1147 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1149 for (int i = 0; i < getHeight(); i++)
1151 SequenceI currentSeq = getSequenceAt(i);
1152 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1155 // verify all mappings are in dataset
1156 for (AlignedCodonFrame cf : codonFrameList)
1158 for (SequenceToSequenceMapping ssm : cf.getMappings())
1160 if (!seqs.contains(ssm.getFromSeq()))
1162 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1164 if (!seqs.contains(ssm.getMapping().getTo()))
1166 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1170 // finally construct dataset
1171 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1172 // move mappings to the dataset alignment
1173 dataset.codonFrameList = this.codonFrameList;
1174 this.codonFrameList = null;
1178 * reference count for number of alignments referencing this one.
1180 int alignmentRefs = 0;
1183 * increase reference count to this alignment.
1185 private void addAlignmentRef()
1191 public Alignment getDataset()
1197 public boolean padGaps()
1199 boolean modified = false;
1201 // Remove excess gaps from the end of alignment
1205 for (int i = 0; i < sequences.size(); i++)
1207 current = getSequenceAt(i);
1208 for (int j = current.getLength(); j > maxLength; j--)
1211 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1222 for (int i = 0; i < sequences.size(); i++)
1224 current = getSequenceAt(i);
1225 cLength = current.getLength();
1227 if (cLength < maxLength)
1229 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1232 else if (current.getLength() > maxLength)
1234 current.deleteChars(maxLength, current.getLength());
1241 * Justify the sequences to the left or right by deleting and inserting gaps
1242 * before the initial residue or after the terminal residue
1245 * true if alignment padded to right, false to justify to left
1246 * @return true if alignment was changed
1249 public boolean justify(boolean right)
1251 boolean modified = false;
1253 // Remove excess gaps from the end of alignment
1255 int ends[] = new int[sequences.size() * 2];
1257 for (int i = 0; i < sequences.size(); i++)
1259 current = getSequenceAt(i);
1260 // This should really be a sequence method
1261 ends[i * 2] = current.findIndex(current.getStart());
1262 ends[i * 2 + 1] = current.findIndex(current.getStart()
1263 + current.getLength());
1264 boolean hitres = false;
1265 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1267 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1276 ends[i * 2 + 1] = j;
1277 if (j - ends[i * 2] > maxLength)
1279 maxLength = j - ends[i * 2];
1287 // now edit the flanking gaps to justify to either left or right
1288 int cLength, extent, diff;
1289 for (int i = 0; i < sequences.size(); i++)
1291 current = getSequenceAt(i);
1293 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1294 diff = maxLength - cLength; // number of gaps to indent
1295 extent = current.getLength();
1299 if (extent > ends[i * 2 + 1])
1301 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1304 if (ends[i * 2] > diff)
1306 current.deleteChars(0, ends[i * 2] - diff);
1311 if (ends[i * 2] < diff)
1313 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1321 if (ends[i * 2] > 0)
1323 current.deleteChars(0, ends[i * 2]);
1325 ends[i * 2 + 1] -= ends[i * 2];
1326 extent -= ends[i * 2];
1328 if (extent > maxLength)
1330 current.deleteChars(maxLength + 1, extent);
1335 if (extent < maxLength)
1337 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1347 public HiddenSequences getHiddenSequences()
1349 return hiddenSequences;
1353 public HiddenColumns getHiddenColumns()
1359 public CigarArray getCompactAlignment()
1361 synchronized (sequences)
1363 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1365 for (SequenceI seq : sequences)
1367 alseqs[i++] = new SeqCigar(seq);
1369 CigarArray cal = new CigarArray(alseqs);
1370 cal.addOperation(CigarArray.M, getWidth());
1376 public void setProperty(Object key, Object value)
1378 if (alignmentProperties == null)
1380 alignmentProperties = new Hashtable();
1383 alignmentProperties.put(key, value);
1387 public Object getProperty(Object key)
1389 if (alignmentProperties != null)
1391 return alignmentProperties.get(key);
1400 public Hashtable getProperties()
1402 return alignmentProperties;
1406 * Adds the given mapping to the stored set. Note this may be held on the
1407 * dataset alignment.
1410 public void addCodonFrame(AlignedCodonFrame codons)
1412 List<AlignedCodonFrame> acfs = getCodonFrames();
1413 if (codons != null && acfs != null && !acfs.contains(codons))
1423 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1426 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1432 List<AlignedCodonFrame> cframes = new ArrayList<>();
1433 for (AlignedCodonFrame acf : getCodonFrames())
1435 if (acf.involvesSequence(seq))
1444 * Sets the codon frame mappings (replacing any existing mappings). Note the
1445 * mappings are set on the dataset alignment instead if there is one.
1447 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1450 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1452 if (dataset != null)
1454 dataset.setCodonFrames(acfs);
1458 this.codonFrameList = acfs;
1463 * Returns the set of codon frame mappings. Any changes to the returned set
1464 * will affect the alignment. The mappings are held on (and read from) the
1465 * dataset alignment if there is one.
1467 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1470 public List<AlignedCodonFrame> getCodonFrames()
1472 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1473 // this behaviour is currently incorrect. method should return codon frames
1474 // for just the alignment,
1475 // selected from dataset
1476 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1480 * Removes the given mapping from the stored set. Note that the mappings are
1481 * held on the dataset alignment if there is one.
1484 public boolean removeCodonFrame(AlignedCodonFrame codons)
1486 List<AlignedCodonFrame> acfs = getCodonFrames();
1487 if (codons == null || acfs == null)
1491 return acfs.remove(codons);
1495 public void append(AlignmentI toappend)
1497 // TODO JAL-1270 needs test coverage
1498 // currently tested for use in jalview.gui.SequenceFetcher
1499 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1500 char oldc = toappend.getGapCharacter();
1501 boolean hashidden = toappend.getHiddenSequences() != null
1502 && toappend.getHiddenSequences().hiddenSequences != null;
1503 // get all sequences including any hidden ones
1504 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1505 .getFullAlignment().getSequences() : toappend.getSequences();
1508 // avoid self append deadlock by
1509 List<SequenceI> toappendsq = new ArrayList<>();
1512 for (SequenceI addedsq : sqs)
1516 char[] oldseq = addedsq.getSequence();
1517 for (int c = 0; c < oldseq.length; c++)
1519 if (oldseq[c] == oldc)
1521 oldseq[c] = gapCharacter;
1525 toappendsq.add(addedsq);
1528 for (SequenceI addedsq : toappendsq)
1530 addSequence(addedsq);
1533 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1534 for (int a = 0; alan != null && a < alan.length; a++)
1536 addAnnotation(alan[a]);
1540 getCodonFrames().addAll(toappend.getCodonFrames());
1542 List<SequenceGroup> sg = toappend.getGroups();
1545 for (SequenceGroup _sg : sg)
1550 if (toappend.getHiddenSequences() != null)
1552 HiddenSequences hs = toappend.getHiddenSequences();
1553 if (hiddenSequences == null)
1555 hiddenSequences = new HiddenSequences(this);
1557 if (hs.hiddenSequences != null)
1559 for (int s = 0; s < hs.hiddenSequences.length; s++)
1561 // hide the newly appended sequence in the alignment
1562 if (hs.hiddenSequences[s] != null)
1564 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1569 if (toappend.getProperties() != null)
1571 // we really can't do very much here - just try to concatenate strings
1572 // where property collisions occur.
1573 Enumeration key = toappend.getProperties().keys();
1574 while (key.hasMoreElements())
1576 Object k = key.nextElement();
1577 Object ourval = this.getProperty(k);
1578 Object toapprop = toappend.getProperty(k);
1581 if (ourval.getClass().equals(toapprop.getClass())
1582 && !ourval.equals(toapprop))
1584 if (ourval instanceof String)
1587 this.setProperty(k, ((String) ourval) + "; "
1588 + ((String) toapprop));
1592 if (ourval instanceof Vector)
1595 Enumeration theirv = ((Vector) toapprop).elements();
1596 while (theirv.hasMoreElements())
1598 ((Vector) ourval).addElement(theirv);
1606 // just add new property directly
1607 setProperty(k, toapprop);
1615 public AlignmentAnnotation findOrCreateAnnotation(String name,
1616 String calcId, boolean autoCalc, SequenceI seqRef,
1617 SequenceGroup groupRef)
1619 if (annotations != null)
1621 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1623 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1624 && (calcId == null || annot.getCalcId().equals(calcId))
1625 && annot.sequenceRef == seqRef
1626 && annot.groupRef == groupRef)
1632 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1633 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1634 annot.hasText = false;
1635 annot.setCalcId(new String(calcId));
1636 annot.autoCalculated = autoCalc;
1639 annot.setSequenceRef(seqRef);
1641 annot.groupRef = groupRef;
1642 addAnnotation(annot);
1648 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1650 List<AlignmentAnnotation> aa = new ArrayList<>();
1651 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1652 if (alignmentAnnotation != null)
1654 for (AlignmentAnnotation a : alignmentAnnotation)
1656 if (a.getCalcId() == calcId
1657 || (a.getCalcId() != null && calcId != null && a
1658 .getCalcId().equals(calcId)))
1668 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1669 String calcId, String label)
1671 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1672 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1674 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1676 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1677 && (label == null || (ann.label != null && ann.label
1687 public void moveSelectedSequencesByOne(SequenceGroup sg,
1688 Map<SequenceI, SequenceCollectionI> map, boolean up)
1690 synchronized (sequences)
1695 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1697 SequenceI seq = sequences.get(i);
1698 if (!sg.getSequences(map).contains(seq))
1703 SequenceI temp = sequences.get(i - 1);
1704 if (sg.getSequences(null).contains(temp))
1709 sequences.set(i, temp);
1710 sequences.set(i - 1, seq);
1715 for (int i = sequences.size() - 2; i > -1; i--)
1717 SequenceI seq = sequences.get(i);
1718 if (!sg.getSequences(map).contains(seq))
1723 SequenceI temp = sequences.get(i + 1);
1724 if (sg.getSequences(map).contains(temp))
1729 sequences.set(i, temp);
1730 sequences.set(i + 1, seq);
1738 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1740 alignmentAnnotation.validateRangeAndDisplay();
1741 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1743 hasRNAStructure = true;
1747 private SequenceI seqrep = null;
1751 * @return the representative sequence for this group
1754 public SequenceI getSeqrep()
1760 * set the representative sequence for this group. Note - this affects the
1761 * interpretation of the Hidereps attribute.
1764 * the seqrep to set (null means no sequence representative)
1767 public void setSeqrep(SequenceI seqrep)
1769 this.seqrep = seqrep;
1774 * @return true if group has a sequence representative
1777 public boolean hasSeqrep()
1779 return seqrep != null;
1783 public int getEndRes()
1785 return getWidth() - 1;
1789 public int getStartRes()
1795 * In the case of AlignmentI - returns the dataset for the alignment, if set
1798 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1801 public AnnotatedCollectionI getContext()
1807 * Align this alignment like the given (mapped) one.
1810 public int alignAs(AlignmentI al)
1813 * Currently retains unmapped gaps (in introns), regaps mapped regions
1816 return alignAs(al, false, true);
1820 * Align this alignment 'the same as' the given one. Mapped sequences only are
1821 * realigned. If both of the same type (nucleotide/protein) then align both
1822 * identically. If this is nucleotide and the other is protein, make 3 gaps
1823 * for each gap in the protein sequences. If this is protein and the other is
1824 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1825 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1826 * protein to match the relative ordering of codons in the nucleotide.
1828 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1829 * regions are preserved. Gaps that connect introns to exons are treated
1830 * conservatively, i.e. only preserved if both intron and exon gaps are
1831 * preserved. TODO: check caveats below where the implementation fails
1834 * - must have same dataset, and sequences in al must have equivalent
1835 * dataset sequence and start/end bounds under given mapping
1836 * @param preserveMappedGaps
1837 * if true, gaps within and between mapped codons are preserved
1838 * @param preserveUnmappedGaps
1839 * if true, gaps within and between unmapped codons are preserved
1842 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1843 boolean preserveUnmappedGaps)
1845 // TODO should this method signature be the one in the interface?
1846 // JBPComment - yes - neither flag is used, so should be deleted.
1847 boolean thisIsNucleotide = this.isNucleotide();
1848 boolean thatIsProtein = !al.isNucleotide();
1849 if (!thatIsProtein && !thisIsNucleotide)
1851 return AlignmentUtils.alignProteinAsDna(this, al);
1853 else if (thatIsProtein && thisIsNucleotide)
1855 return AlignmentUtils.alignCdsAsProtein(this, al);
1857 return AlignmentUtils.alignAs(this, al);
1861 * Returns the alignment in Fasta format. Behaviour of this method is not
1862 * guaranteed between versions.
1865 public String toString()
1867 return new FastaFile().print(getSequencesArray(), true);
1871 * Returns the set of distinct sequence names. No ordering is guaranteed.
1874 public Set<String> getSequenceNames()
1876 Set<String> names = new HashSet<>();
1877 for (SequenceI seq : getSequences())
1879 names.add(seq.getName());
1885 public boolean hasValidSequence()
1887 boolean hasValidSeq = false;
1888 for (SequenceI seq : getSequences())
1890 if ((seq.getEnd() - seq.getStart()) > 0)
1900 * Update any mappings to 'virtual' sequences to compatible real ones, if
1901 * present in the added sequences. Returns a count of mappings updated.
1907 public int realiseMappings(List<SequenceI> seqs)
1910 for (SequenceI seq : seqs)
1912 for (AlignedCodonFrame mapping : getCodonFrames())
1914 count += mapping.realiseWith(seq);
1921 * Returns the first AlignedCodonFrame that has a mapping between the given
1929 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1931 for (AlignedCodonFrame acf : getCodonFrames())
1933 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1942 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1944 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1945 int startPos = alignmentStartEnd[0];
1946 int endPos = alignmentStartEnd[1];
1948 int[] lowestRange = new int[] { -1, -1 };
1949 int[] higestRange = new int[] { -1, -1 };
1951 for (int[] hiddenCol : hiddenCols)
1953 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1954 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1957 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1959 startPos = alignmentStartEnd[0];
1963 startPos = lowestRange[1] + 1;
1966 if (higestRange[0] == -1 && higestRange[1] == -1)
1968 endPos = alignmentStartEnd[1];
1972 endPos = higestRange[0] - 1;
1974 return new int[] { startPos, endPos };
1978 public void setHiddenColumns(HiddenColumns cols)
1985 public List<SequenceI> getHMMConsensusSequences(boolean remove)
1987 List<SequenceI> seqs = new ArrayList<>();
1989 int seqsRemoved = 0;
1990 boolean endReached = false;
1994 SequenceI seq = sequences.get(position);
1995 if (seq.isHMMConsensusSequence())
1999 sequences.remove(position);
2001 seq.setPreviousPosition(seqsRemoved + position - 1);
2014 if (position >= sequences.size())