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 * Inserts a sequence at a point in the alignment.
295 * the index of the position the sequence is to be inserted in.
298 public void insertSequenceAt(int i, SequenceI snew)
300 synchronized (sequences)
302 if (sequences.size() > i)
304 sequences.add(i, snew);
311 hiddenSequences.adjustHeightSequenceAdded();
320 * @return DOCUMENT ME!
323 public List<SequenceGroup> getGroups()
329 public void finalize() throws Throwable
331 if (getDataset() != null)
333 getDataset().removeAlignmentRef();
341 * Defensively nulls out references in case this object is not garbage
344 void nullReferences()
350 hiddenSequences = null;
354 * decrement the alignmentRefs counter by one and null references if it goes
359 private void removeAlignmentRef() throws Throwable
361 if (--alignmentRefs == 0)
368 public void deleteSequence(SequenceI s)
370 synchronized (sequences)
372 deleteSequence(findIndex(s));
377 public void deleteSequence(int i)
379 synchronized (sequences)
381 if (i > -1 && i < getHeight())
384 hiddenSequences.adjustHeightSequenceDeleted(i);
390 public void deleteHiddenSequence(int i)
392 synchronized (sequences)
394 if (i > -1 && i < getHeight())
404 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
407 public SequenceGroup findGroup(SequenceI seq, int position)
409 synchronized (groups)
411 for (SequenceGroup sg : groups)
413 if (sg.getSequences(null).contains(seq))
415 if (position >= sg.getStartRes() && position <= sg.getEndRes())
429 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
432 public SequenceGroup[] findAllGroups(SequenceI s)
434 ArrayList<SequenceGroup> temp = new ArrayList<>();
436 synchronized (groups)
438 int gSize = groups.size();
439 for (int i = 0; i < gSize; i++)
441 SequenceGroup sg = groups.get(i);
442 if (sg == null || sg.getSequences() == null)
444 this.deleteGroup(sg);
449 if (sg.getSequences().contains(s))
455 SequenceGroup[] ret = new SequenceGroup[temp.size()];
456 return temp.toArray(ret);
461 public void addGroup(SequenceGroup sg)
463 synchronized (groups)
465 if (!groups.contains(sg))
467 if (hiddenSequences.getSize() > 0)
469 int i, iSize = sg.getSize();
470 for (i = 0; i < iSize; i++)
472 if (!sequences.contains(sg.getSequenceAt(i)))
474 sg.deleteSequence(sg.getSequenceAt(i), false);
480 if (sg.getSize() < 1)
485 sg.setContext(this, true);
492 * remove any annotation that references gp
495 * (if null, removes all group associated annotation)
497 private void removeAnnotationForGroup(SequenceGroup gp)
499 if (annotations == null || annotations.length == 0)
503 // remove annotation very quickly
504 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
508 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
510 if (annotations[i].groupRef != null)
512 todelete[p++] = annotations[i];
516 tokeep[k++] = annotations[i];
522 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
524 if (annotations[i].groupRef == gp)
526 todelete[p++] = annotations[i];
530 tokeep[k++] = annotations[i];
536 // clear out the group associated annotation.
537 for (i = 0; i < p; i++)
539 unhookAnnotation(todelete[i]);
542 t = new AlignmentAnnotation[k];
543 for (i = 0; i < k; i++)
552 public void deleteAllGroups()
554 synchronized (groups)
556 if (annotations != null)
558 removeAnnotationForGroup(null);
560 for (SequenceGroup sg : groups)
562 sg.setContext(null, false);
570 public void deleteGroup(SequenceGroup g)
572 synchronized (groups)
574 if (groups.contains(g))
576 removeAnnotationForGroup(g);
578 g.setContext(null, false);
585 public SequenceI findName(String name)
587 return findName(name, false);
593 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
596 public SequenceI findName(String token, boolean b)
598 return findName(null, token, b);
604 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
608 public SequenceI findName(SequenceI startAfter, String token, boolean b)
613 String sqname = null;
614 if (startAfter != null)
616 // try to find the sequence in the alignment
617 boolean matched = false;
618 while (i < sequences.size())
620 if (getSequenceAt(i++) == startAfter)
631 while (i < sequences.size())
633 sq = getSequenceAt(i);
634 sqname = sq.getName();
635 if (sqname.equals(token) // exact match
636 || (b && // allow imperfect matches - case varies
637 (sqname.equalsIgnoreCase(token))))
639 return getSequenceAt(i);
649 public SequenceI[] findSequenceMatch(String name)
651 Vector matches = new Vector();
654 while (i < sequences.size())
656 if (getSequenceAt(i).getName().equals(name))
658 matches.addElement(getSequenceAt(i));
663 SequenceI[] result = new SequenceI[matches.size()];
664 for (i = 0; i < result.length; i++)
666 result[i] = (SequenceI) matches.elementAt(i);
676 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
679 public int findIndex(SequenceI s)
683 while (i < sequences.size())
685 if (s == getSequenceAt(i))
700 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
703 public int findIndex(SearchResultsI results)
707 while (i < sequences.size())
709 if (results.involvesSequence(getSequenceAt(i)))
720 public int getHeight()
722 return sequences.size();
726 public int getAbsoluteHeight()
728 return sequences.size() + getHiddenSequences().getSize();
732 public int getWidth()
736 for (int i = 0; i < sequences.size(); i++)
738 if (getSequenceAt(i).getLength() > maxLength)
740 maxLength = getSequenceAt(i).getLength();
754 public void setGapCharacter(char gc)
757 synchronized (sequences)
759 for (SequenceI seq : sequences)
761 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
762 .replace('-', gc).replace(' ', gc));
770 * @return DOCUMENT ME!
773 public char getGapCharacter()
781 * @see jalview.datamodel.AlignmentI#isAligned()
784 public boolean isAligned()
786 return isAligned(false);
792 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
795 public boolean isAligned(boolean includeHidden)
797 int width = getWidth();
798 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
800 includeHidden = true; // no hidden sequences to check against.
802 for (int i = 0; i < sequences.size(); i++)
804 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
806 if (getSequenceAt(i).getLength() != width)
817 public boolean isHidden(int alignmentIndex)
819 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
823 * Delete all annotations, including auto-calculated if the flag is set true.
824 * Returns true if at least one annotation was deleted, else false.
826 * @param includingAutoCalculated
830 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
832 boolean result = false;
833 for (AlignmentAnnotation alan : getAlignmentAnnotation())
835 if (!alan.autoCalculated || includingAutoCalculated)
837 deleteAnnotation(alan);
847 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
848 * AlignmentAnnotation)
851 public boolean deleteAnnotation(AlignmentAnnotation aa)
853 return deleteAnnotation(aa, true);
857 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
861 if (annotations != null)
863 aSize = annotations.length;
871 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
873 boolean swap = false;
876 for (int i = 0; i < aSize; i++)
878 if (annotations[i] == aa)
883 if (tIndex < temp.length)
885 temp[tIndex++] = annotations[i];
894 unhookAnnotation(aa);
901 * remove any object references associated with this annotation
905 private void unhookAnnotation(AlignmentAnnotation aa)
907 if (aa.sequenceRef != null)
909 aa.sequenceRef.removeAlignmentAnnotation(aa);
911 if (aa.groupRef != null)
913 // probably need to do more here in the future (post 2.5.0)
921 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
922 * AlignmentAnnotation)
925 public void addAnnotation(AlignmentAnnotation aa)
927 addAnnotation(aa, -1);
933 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
934 * AlignmentAnnotation, int)
937 public void addAnnotation(AlignmentAnnotation aa, int pos)
939 if (aa.getRNAStruc() != null)
941 hasRNAStructure = true;
945 if (annotations != null)
947 aSize = annotations.length + 1;
950 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
952 if (pos == -1 || pos >= aSize)
954 temp[aSize - 1] = aa;
963 for (i = 0; i < (aSize - 1); i++, p++)
971 temp[p] = annotations[i];
980 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
982 if (aa == null || annotations == null || annotations.length - 1 < index)
987 int aSize = annotations.length;
988 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
992 for (int i = 0; i < aSize; i++)
1001 temp[i] = annotations[i];
1005 temp[i] = annotations[i - 1];
1014 * returns all annotation on the alignment
1016 public AlignmentAnnotation[] getAlignmentAnnotation()
1022 public boolean isNucleotide()
1028 public boolean hasRNAStructure()
1030 // TODO can it happen that structure is removed from alignment?
1031 return hasRNAStructure;
1035 public void setDataset(AlignmentI data)
1037 if (dataset == null && data == null)
1039 createDatasetAlignment();
1041 else if (dataset == null && data != null)
1045 throw new IllegalArgumentException("Circular dataset reference");
1047 if (!(data instanceof Alignment))
1050 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1052 dataset = (Alignment) data;
1053 for (int i = 0; i < getHeight(); i++)
1055 SequenceI currentSeq = getSequenceAt(i);
1056 SequenceI dsq = currentSeq.getDatasetSequence();
1059 dsq = currentSeq.createDatasetSequence();
1060 dataset.addSequence(dsq);
1064 while (dsq.getDatasetSequence() != null)
1066 dsq = dsq.getDatasetSequence();
1068 if (dataset.findIndex(dsq) == -1)
1070 dataset.addSequence(dsq);
1075 dataset.addAlignmentRef();
1079 * add dataset sequences to seq for currentSeq and any sequences it references
1081 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1082 Set<SequenceI> seqs, boolean createDatasetSequence)
1084 SequenceI alignedSeq = currentSeq;
1085 if (currentSeq.getDatasetSequence() != null)
1087 currentSeq = currentSeq.getDatasetSequence();
1091 if (createDatasetSequence)
1093 currentSeq = currentSeq.createDatasetSequence();
1096 if (seqs.contains(currentSeq))
1100 List<SequenceI> toProcess = new ArrayList<>();
1101 toProcess.add(currentSeq);
1102 while (toProcess.size() > 0)
1105 SequenceI curDs = toProcess.remove(0);
1106 if (seqs.contains(curDs))
1111 // iterate over database references, making sure we add forward referenced
1113 if (curDs.getDBRefs() != null)
1115 for (DBRefEntry dbr : curDs.getDBRefs())
1117 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1119 if (dbr.getMap().getTo() == alignedSeq)
1122 * update mapping to be to the newly created dataset sequence
1124 dbr.getMap().setTo(currentSeq);
1126 if (dbr.getMap().getTo().getDatasetSequence() != null)
1129 "Implementation error: Map.getTo() for dbref " + dbr
1130 + " from " + curDs.getName()
1131 + " is not a dataset sequence.");
1133 // we recurse to add all forward references to dataset sequences via
1135 toProcess.add(dbr.getMap().getTo());
1143 * Creates a new dataset for this alignment. Can only be done once - if
1144 * dataset is not null this will not be performed.
1146 public void createDatasetAlignment()
1148 if (dataset != null)
1152 // try to avoid using SequenceI.equals at this stage, it will be expensive
1153 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1155 for (int i = 0; i < getHeight(); i++)
1157 SequenceI currentSeq = getSequenceAt(i);
1158 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1161 // verify all mappings are in dataset
1162 for (AlignedCodonFrame cf : codonFrameList)
1164 for (SequenceToSequenceMapping ssm : cf.getMappings())
1166 if (!seqs.contains(ssm.getFromSeq()))
1168 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1170 if (!seqs.contains(ssm.getMapping().getTo()))
1172 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1176 // finally construct dataset
1177 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1178 // move mappings to the dataset alignment
1179 dataset.codonFrameList = this.codonFrameList;
1180 this.codonFrameList = null;
1184 * reference count for number of alignments referencing this one.
1186 int alignmentRefs = 0;
1189 * increase reference count to this alignment.
1191 private void addAlignmentRef()
1197 public Alignment getDataset()
1203 public boolean padGaps()
1205 boolean modified = false;
1207 // Remove excess gaps from the end of alignment
1211 for (int i = 0; i < sequences.size(); i++)
1213 current = getSequenceAt(i);
1214 for (int j = current.getLength(); j > maxLength; j--)
1217 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1228 for (int i = 0; i < sequences.size(); i++)
1230 current = getSequenceAt(i);
1231 cLength = current.getLength();
1233 if (cLength < maxLength)
1235 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1238 else if (current.getLength() > maxLength)
1240 current.deleteChars(maxLength, current.getLength());
1247 * Justify the sequences to the left or right by deleting and inserting gaps
1248 * before the initial residue or after the terminal residue
1251 * true if alignment padded to right, false to justify to left
1252 * @return true if alignment was changed
1255 public boolean justify(boolean right)
1257 boolean modified = false;
1259 // Remove excess gaps from the end of alignment
1261 int ends[] = new int[sequences.size() * 2];
1263 for (int i = 0; i < sequences.size(); i++)
1265 current = getSequenceAt(i);
1266 // This should really be a sequence method
1267 ends[i * 2] = current.findIndex(current.getStart());
1268 ends[i * 2 + 1] = current.findIndex(current.getStart()
1269 + current.getLength());
1270 boolean hitres = false;
1271 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1273 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1282 ends[i * 2 + 1] = j;
1283 if (j - ends[i * 2] > maxLength)
1285 maxLength = j - ends[i * 2];
1293 // now edit the flanking gaps to justify to either left or right
1294 int cLength, extent, diff;
1295 for (int i = 0; i < sequences.size(); i++)
1297 current = getSequenceAt(i);
1299 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1300 diff = maxLength - cLength; // number of gaps to indent
1301 extent = current.getLength();
1305 if (extent > ends[i * 2 + 1])
1307 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1310 if (ends[i * 2] > diff)
1312 current.deleteChars(0, ends[i * 2] - diff);
1317 if (ends[i * 2] < diff)
1319 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1327 if (ends[i * 2] > 0)
1329 current.deleteChars(0, ends[i * 2]);
1331 ends[i * 2 + 1] -= ends[i * 2];
1332 extent -= ends[i * 2];
1334 if (extent > maxLength)
1336 current.deleteChars(maxLength + 1, extent);
1341 if (extent < maxLength)
1343 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1353 public HiddenSequences getHiddenSequences()
1355 return hiddenSequences;
1359 public HiddenColumns getHiddenColumns()
1365 public CigarArray getCompactAlignment()
1367 synchronized (sequences)
1369 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1371 for (SequenceI seq : sequences)
1373 alseqs[i++] = new SeqCigar(seq);
1375 CigarArray cal = new CigarArray(alseqs);
1376 cal.addOperation(CigarArray.M, getWidth());
1382 public void setProperty(Object key, Object value)
1384 if (alignmentProperties == null)
1386 alignmentProperties = new Hashtable();
1389 alignmentProperties.put(key, value);
1393 public Object getProperty(Object key)
1395 if (alignmentProperties != null)
1397 return alignmentProperties.get(key);
1406 public Hashtable getProperties()
1408 return alignmentProperties;
1412 * Adds the given mapping to the stored set. Note this may be held on the
1413 * dataset alignment.
1416 public void addCodonFrame(AlignedCodonFrame codons)
1418 List<AlignedCodonFrame> acfs = getCodonFrames();
1419 if (codons != null && acfs != null && !acfs.contains(codons))
1429 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1432 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1438 List<AlignedCodonFrame> cframes = new ArrayList<>();
1439 for (AlignedCodonFrame acf : getCodonFrames())
1441 if (acf.involvesSequence(seq))
1450 * Sets the codon frame mappings (replacing any existing mappings). Note the
1451 * mappings are set on the dataset alignment instead if there is one.
1453 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1456 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1458 if (dataset != null)
1460 dataset.setCodonFrames(acfs);
1464 this.codonFrameList = acfs;
1469 * Returns the set of codon frame mappings. Any changes to the returned set
1470 * will affect the alignment. The mappings are held on (and read from) the
1471 * dataset alignment if there is one.
1473 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1476 public List<AlignedCodonFrame> getCodonFrames()
1478 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1479 // this behaviour is currently incorrect. method should return codon frames
1480 // for just the alignment,
1481 // selected from dataset
1482 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1486 * Removes the given mapping from the stored set. Note that the mappings are
1487 * held on the dataset alignment if there is one.
1490 public boolean removeCodonFrame(AlignedCodonFrame codons)
1492 List<AlignedCodonFrame> acfs = getCodonFrames();
1493 if (codons == null || acfs == null)
1497 return acfs.remove(codons);
1501 public void append(AlignmentI toappend)
1503 // TODO JAL-1270 needs test coverage
1504 // currently tested for use in jalview.gui.SequenceFetcher
1505 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1506 char oldc = toappend.getGapCharacter();
1507 boolean hashidden = toappend.getHiddenSequences() != null
1508 && toappend.getHiddenSequences().hiddenSequences != null;
1509 // get all sequences including any hidden ones
1510 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1511 .getFullAlignment().getSequences() : toappend.getSequences();
1514 // avoid self append deadlock by
1515 List<SequenceI> toappendsq = new ArrayList<>();
1518 for (SequenceI addedsq : sqs)
1522 char[] oldseq = addedsq.getSequence();
1523 for (int c = 0; c < oldseq.length; c++)
1525 if (oldseq[c] == oldc)
1527 oldseq[c] = gapCharacter;
1531 toappendsq.add(addedsq);
1534 for (SequenceI addedsq : toappendsq)
1536 addSequence(addedsq);
1539 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1540 for (int a = 0; alan != null && a < alan.length; a++)
1542 addAnnotation(alan[a]);
1546 getCodonFrames().addAll(toappend.getCodonFrames());
1548 List<SequenceGroup> sg = toappend.getGroups();
1551 for (SequenceGroup _sg : sg)
1556 if (toappend.getHiddenSequences() != null)
1558 HiddenSequences hs = toappend.getHiddenSequences();
1559 if (hiddenSequences == null)
1561 hiddenSequences = new HiddenSequences(this);
1563 if (hs.hiddenSequences != null)
1565 for (int s = 0; s < hs.hiddenSequences.length; s++)
1567 // hide the newly appended sequence in the alignment
1568 if (hs.hiddenSequences[s] != null)
1570 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1575 if (toappend.getProperties() != null)
1577 // we really can't do very much here - just try to concatenate strings
1578 // where property collisions occur.
1579 Enumeration key = toappend.getProperties().keys();
1580 while (key.hasMoreElements())
1582 Object k = key.nextElement();
1583 Object ourval = this.getProperty(k);
1584 Object toapprop = toappend.getProperty(k);
1587 if (ourval.getClass().equals(toapprop.getClass())
1588 && !ourval.equals(toapprop))
1590 if (ourval instanceof String)
1593 this.setProperty(k, ((String) ourval) + "; "
1594 + ((String) toapprop));
1598 if (ourval instanceof Vector)
1601 Enumeration theirv = ((Vector) toapprop).elements();
1602 while (theirv.hasMoreElements())
1604 ((Vector) ourval).addElement(theirv);
1612 // just add new property directly
1613 setProperty(k, toapprop);
1621 public AlignmentAnnotation findOrCreateAnnotation(String name,
1622 String calcId, boolean autoCalc, SequenceI seqRef,
1623 SequenceGroup groupRef)
1625 if (annotations != null)
1627 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1629 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1630 && (calcId == null || annot.getCalcId().equals(calcId))
1631 && annot.sequenceRef == seqRef
1632 && annot.groupRef == groupRef)
1638 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1639 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1640 annot.hasText = false;
1641 annot.setCalcId(new String(calcId));
1642 annot.autoCalculated = autoCalc;
1645 annot.setSequenceRef(seqRef);
1647 annot.groupRef = groupRef;
1648 addAnnotation(annot);
1654 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1656 List<AlignmentAnnotation> aa = new ArrayList<>();
1657 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1658 if (alignmentAnnotation != null)
1660 for (AlignmentAnnotation a : alignmentAnnotation)
1662 if (a.getCalcId() == calcId
1663 || (a.getCalcId() != null && calcId != null && a
1664 .getCalcId().equals(calcId)))
1674 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1675 String calcId, String label)
1677 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1678 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1680 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1682 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1683 && (label == null || (ann.label != null && ann.label
1693 public void moveSelectedSequencesByOne(SequenceGroup sg,
1694 Map<SequenceI, SequenceCollectionI> map, boolean up)
1696 synchronized (sequences)
1701 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1703 SequenceI seq = sequences.get(i);
1704 if (!sg.getSequences(map).contains(seq))
1709 SequenceI temp = sequences.get(i - 1);
1710 if (sg.getSequences(null).contains(temp))
1715 sequences.set(i, temp);
1716 sequences.set(i - 1, seq);
1721 for (int i = sequences.size() - 2; i > -1; i--)
1723 SequenceI seq = sequences.get(i);
1724 if (!sg.getSequences(map).contains(seq))
1729 SequenceI temp = sequences.get(i + 1);
1730 if (sg.getSequences(map).contains(temp))
1735 sequences.set(i, temp);
1736 sequences.set(i + 1, seq);
1744 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1746 alignmentAnnotation.validateRangeAndDisplay();
1747 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1749 hasRNAStructure = true;
1753 private SequenceI seqrep = null;
1757 * @return the representative sequence for this group
1760 public SequenceI getSeqrep()
1766 * set the representative sequence for this group. Note - this affects the
1767 * interpretation of the Hidereps attribute.
1770 * the seqrep to set (null means no sequence representative)
1773 public void setSeqrep(SequenceI seqrep)
1775 this.seqrep = seqrep;
1780 * @return true if group has a sequence representative
1783 public boolean hasSeqrep()
1785 return seqrep != null;
1789 public int getEndRes()
1791 return getWidth() - 1;
1795 public int getStartRes()
1801 * In the case of AlignmentI - returns the dataset for the alignment, if set
1804 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1807 public AnnotatedCollectionI getContext()
1813 * Align this alignment like the given (mapped) one.
1816 public int alignAs(AlignmentI al)
1819 * Currently retains unmapped gaps (in introns), regaps mapped regions
1822 return alignAs(al, false, true);
1826 * Align this alignment 'the same as' the given one. Mapped sequences only are
1827 * realigned. If both of the same type (nucleotide/protein) then align both
1828 * identically. If this is nucleotide and the other is protein, make 3 gaps
1829 * for each gap in the protein sequences. If this is protein and the other is
1830 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1831 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1832 * protein to match the relative ordering of codons in the nucleotide.
1834 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1835 * regions are preserved. Gaps that connect introns to exons are treated
1836 * conservatively, i.e. only preserved if both intron and exon gaps are
1837 * preserved. TODO: check caveats below where the implementation fails
1840 * - must have same dataset, and sequences in al must have equivalent
1841 * dataset sequence and start/end bounds under given mapping
1842 * @param preserveMappedGaps
1843 * if true, gaps within and between mapped codons are preserved
1844 * @param preserveUnmappedGaps
1845 * if true, gaps within and between unmapped codons are preserved
1848 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1849 boolean preserveUnmappedGaps)
1851 // TODO should this method signature be the one in the interface?
1852 // JBPComment - yes - neither flag is used, so should be deleted.
1853 boolean thisIsNucleotide = this.isNucleotide();
1854 boolean thatIsProtein = !al.isNucleotide();
1855 if (!thatIsProtein && !thisIsNucleotide)
1857 return AlignmentUtils.alignProteinAsDna(this, al);
1859 else if (thatIsProtein && thisIsNucleotide)
1861 return AlignmentUtils.alignCdsAsProtein(this, al);
1863 return AlignmentUtils.alignAs(this, al);
1867 * Returns the alignment in Fasta format. Behaviour of this method is not
1868 * guaranteed between versions.
1871 public String toString()
1873 return new FastaFile().print(getSequencesArray(), true);
1877 * Returns the set of distinct sequence names. No ordering is guaranteed.
1880 public Set<String> getSequenceNames()
1882 Set<String> names = new HashSet<>();
1883 for (SequenceI seq : getSequences())
1885 names.add(seq.getName());
1891 public boolean hasValidSequence()
1893 boolean hasValidSeq = false;
1894 for (SequenceI seq : getSequences())
1896 if ((seq.getEnd() - seq.getStart()) > 0)
1906 * Update any mappings to 'virtual' sequences to compatible real ones, if
1907 * present in the added sequences. Returns a count of mappings updated.
1913 public int realiseMappings(List<SequenceI> seqs)
1916 for (SequenceI seq : seqs)
1918 for (AlignedCodonFrame mapping : getCodonFrames())
1920 count += mapping.realiseWith(seq);
1927 * Returns the first AlignedCodonFrame that has a mapping between the given
1935 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1937 for (AlignedCodonFrame acf : getCodonFrames())
1939 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1948 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1950 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1951 int startPos = alignmentStartEnd[0];
1952 int endPos = alignmentStartEnd[1];
1954 int[] lowestRange = new int[] { -1, -1 };
1955 int[] higestRange = new int[] { -1, -1 };
1957 for (int[] hiddenCol : hiddenCols)
1959 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1960 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1963 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1965 startPos = alignmentStartEnd[0];
1969 startPos = lowestRange[1] + 1;
1972 if (higestRange[0] == -1 && higestRange[1] == -1)
1974 endPos = alignmentStartEnd[1];
1978 endPos = higestRange[0] - 1;
1980 return new int[] { startPos, endPos };
1984 public void setHiddenColumns(HiddenColumns cols)
1990 * Returns all HMM consensus sequences. This will not return real sequences
1991 * with HMMs. If remove is set to true, the consensus sequences will be
1992 * removed from the alignment.
1995 public List<SequenceI> getHMMConsensusSequences(boolean remove)
1997 List<SequenceI> seqs = new ArrayList<>();
1999 int seqsRemoved = 0;
2000 boolean endReached = false;
2004 SequenceI seq = sequences.get(position);
2005 if (seq.isHMMConsensusSequence())
2009 sequences.remove(position);
2011 seq.setPreviousPosition(seqsRemoved + position - 1);
2024 if (position >= sequences.size())