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 public Hashtable alignmentProperties;
67 private List<AlignedCodonFrame> codonFrameList;
69 private void initAlignment(SequenceI[] seqs)
71 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
72 hiddenSequences = new HiddenSequences(this);
73 codonFrameList = new ArrayList<AlignedCodonFrame>();
75 nucleotide = Comparison.isNucleotide(seqs);
77 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
79 for (int i = 0; i < seqs.length; i++)
81 sequences.add(seqs[i]);
87 * Make a 'copy' alignment - sequences have new copies of features and
88 * annotations, but share the original dataset sequences.
90 public Alignment(AlignmentI al)
92 SequenceI[] seqs = al.getSequencesArray();
93 for (int i = 0; i < seqs.length; i++)
95 seqs[i] = new Sequence(seqs[i]);
101 * Share the same dataset sequence mappings (if any).
103 if (dataset == null && al.getDataset() == null)
105 this.setCodonFrames(al.getCodonFrames());
110 * Make an alignment from an array of Sequences.
114 public Alignment(SequenceI[] seqs)
120 * Make a new alignment from an array of SeqCigars
125 public Alignment(SeqCigar[] alseqs)
127 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
128 gapCharacter, new ColumnSelection(), null);
133 * Make a new alignment from an CigarArray JBPNote - can only do this when
134 * compactAlignment does not contain hidden regions. JBPNote - must also check
135 * that compactAlignment resolves to a set of SeqCigars - or construct them
138 * @param compactAlignment
141 public static AlignmentI createAlignment(CigarArray compactAlignment)
145 .getString("error.alignment_cigararray_not_implemented"));
146 // this(compactAlignment.refCigars);
150 public List<SequenceI> getSequences()
156 public List<SequenceI> getSequences(
157 Map<SequenceI, SequenceCollectionI> hiddenReps)
159 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
165 public SequenceI[] getSequencesArray()
167 if (sequences == null)
171 synchronized (sequences)
173 return sequences.toArray(new SequenceI[sequences.size()]);
178 * Returns a map of lists of sequences keyed by sequence name.
183 public Map<String, List<SequenceI>> getSequencesByName()
185 return AlignmentUtils.getSequencesByName(this);
194 * @return DOCUMENT ME!
197 public SequenceI getSequenceAt(int i)
199 synchronized (sequences)
201 if (i > -1 && i < sequences.size())
203 return sequences.get(i);
210 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
211 * this currently does not recalculate whether or not the alignment is
212 * nucleotide, so mixed alignments may have undefined behaviour.
217 public void addSequence(SequenceI snew)
222 // maintain dataset integrity
223 SequenceI dsseq = snew.getDatasetSequence();
226 // derive new sequence
227 SequenceI adding = snew.deriveSequence();
229 dsseq = snew.getDatasetSequence();
231 if (getDataset().findIndex(dsseq) == -1)
233 getDataset().addSequence(dsseq);
237 if (sequences == null)
239 initAlignment(new SequenceI[] { snew });
243 synchronized (sequences)
248 if (hiddenSequences != null)
250 hiddenSequences.adjustHeightSequenceAdded();
255 public SequenceI replaceSequenceAt(int i, SequenceI snew)
257 synchronized (sequences)
259 if (sequences.size() > i)
261 return sequences.set(i, snew);
267 hiddenSequences.adjustHeightSequenceAdded();
276 * @return DOCUMENT ME!
279 public List<SequenceGroup> getGroups()
285 public void finalize() throws Throwable
287 if (getDataset() != null)
289 getDataset().removeAlignmentRef();
297 * Defensively nulls out references in case this object is not garbage
300 void nullReferences()
306 hiddenSequences = null;
310 * decrement the alignmentRefs counter by one and null references if it goes
315 private void removeAlignmentRef() throws Throwable
317 if (--alignmentRefs == 0)
330 public void deleteSequence(SequenceI s)
332 deleteSequence(findIndex(s));
342 public void deleteSequence(int i)
344 if (i > -1 && i < getHeight())
346 synchronized (sequences)
349 hiddenSequences.adjustHeightSequenceDeleted(i);
357 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
360 public SequenceGroup findGroup(SequenceI seq, int position)
362 synchronized (groups)
364 for (SequenceGroup sg : groups)
366 if (sg.getSequences(null).contains(seq))
368 if (position >= sg.getStartRes() && position <= sg.getEndRes())
382 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
385 public SequenceGroup[] findAllGroups(SequenceI s)
387 ArrayList<SequenceGroup> temp = new ArrayList<SequenceGroup>();
389 synchronized (groups)
391 int gSize = groups.size();
392 for (int i = 0; i < gSize; i++)
394 SequenceGroup sg = groups.get(i);
395 if (sg == null || sg.getSequences() == null)
397 this.deleteGroup(sg);
402 if (sg.getSequences().contains(s))
408 SequenceGroup[] ret = new SequenceGroup[temp.size()];
409 return temp.toArray(ret);
414 public void addGroup(SequenceGroup sg)
416 synchronized (groups)
418 if (!groups.contains(sg))
420 if (hiddenSequences.getSize() > 0)
422 int i, iSize = sg.getSize();
423 for (i = 0; i < iSize; i++)
425 if (!sequences.contains(sg.getSequenceAt(i)))
427 sg.deleteSequence(sg.getSequenceAt(i), false);
433 if (sg.getSize() < 1)
445 * remove any annotation that references gp
448 * (if null, removes all group associated annotation)
450 private void removeAnnotationForGroup(SequenceGroup gp)
452 if (annotations == null || annotations.length == 0)
456 // remove annotation very quickly
457 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
461 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
463 if (annotations[i].groupRef != null)
465 todelete[p++] = annotations[i];
469 tokeep[k++] = annotations[i];
475 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
477 if (annotations[i].groupRef == gp)
479 todelete[p++] = annotations[i];
483 tokeep[k++] = annotations[i];
489 // clear out the group associated annotation.
490 for (i = 0; i < p; i++)
492 unhookAnnotation(todelete[i]);
495 t = new AlignmentAnnotation[k];
496 for (i = 0; i < k; i++)
505 public void deleteAllGroups()
507 synchronized (groups)
509 if (annotations != null)
511 removeAnnotationForGroup(null);
513 for (SequenceGroup sg : groups)
523 public void deleteGroup(SequenceGroup g)
525 synchronized (groups)
527 if (groups.contains(g))
529 removeAnnotationForGroup(g);
538 public SequenceI findName(String name)
540 return findName(name, false);
546 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
549 public SequenceI findName(String token, boolean b)
551 return findName(null, token, b);
557 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
561 public SequenceI findName(SequenceI startAfter, String token, boolean b)
566 String sqname = null;
567 if (startAfter != null)
569 // try to find the sequence in the alignment
570 boolean matched = false;
571 while (i < sequences.size())
573 if (getSequenceAt(i++) == startAfter)
584 while (i < sequences.size())
586 sq = getSequenceAt(i);
587 sqname = sq.getName();
588 if (sqname.equals(token) // exact match
589 || (b && // allow imperfect matches - case varies
590 (sqname.equalsIgnoreCase(token))))
592 return getSequenceAt(i);
602 public SequenceI[] findSequenceMatch(String name)
604 Vector matches = new Vector();
607 while (i < sequences.size())
609 if (getSequenceAt(i).getName().equals(name))
611 matches.addElement(getSequenceAt(i));
616 SequenceI[] result = new SequenceI[matches.size()];
617 for (i = 0; i < result.length; i++)
619 result[i] = (SequenceI) matches.elementAt(i);
629 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
632 public int findIndex(SequenceI s)
636 while (i < sequences.size())
638 if (s == getSequenceAt(i))
653 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
656 public int findIndex(SearchResultsI results)
660 while (i < sequences.size())
662 if (results.involvesSequence(getSequenceAt(i)))
674 * @return DOCUMENT ME!
677 public int getHeight()
679 return sequences.size();
685 * @return DOCUMENT ME!
688 public int getWidth()
692 for (int i = 0; i < sequences.size(); i++)
694 if (getSequenceAt(i).getLength() > maxLength)
696 maxLength = getSequenceAt(i).getLength();
710 public void setGapCharacter(char gc)
713 synchronized (sequences)
715 for (SequenceI seq : sequences)
717 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
718 .replace('-', gc).replace(' ', gc));
726 * @return DOCUMENT ME!
729 public char getGapCharacter()
737 * @see jalview.datamodel.AlignmentI#isAligned()
740 public boolean isAligned()
742 return isAligned(false);
748 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
751 public boolean isAligned(boolean includeHidden)
753 int width = getWidth();
754 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
756 includeHidden = true; // no hidden sequences to check against.
758 for (int i = 0; i < sequences.size(); i++)
760 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
762 if (getSequenceAt(i).getLength() != width)
773 * Delete all annotations, including auto-calculated if the flag is set true.
774 * Returns true if at least one annotation was deleted, else false.
776 * @param includingAutoCalculated
780 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
782 boolean result = false;
783 for (AlignmentAnnotation alan : getAlignmentAnnotation())
785 if (!alan.autoCalculated || includingAutoCalculated)
787 deleteAnnotation(alan);
797 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
798 * AlignmentAnnotation)
801 public boolean deleteAnnotation(AlignmentAnnotation aa)
803 return deleteAnnotation(aa, true);
807 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
811 if (annotations != null)
813 aSize = annotations.length;
821 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
823 boolean swap = false;
826 for (int i = 0; i < aSize; i++)
828 if (annotations[i] == aa)
833 if (tIndex < temp.length)
835 temp[tIndex++] = annotations[i];
844 unhookAnnotation(aa);
851 * remove any object references associated with this annotation
855 private void unhookAnnotation(AlignmentAnnotation aa)
857 if (aa.sequenceRef != null)
859 aa.sequenceRef.removeAlignmentAnnotation(aa);
861 if (aa.groupRef != null)
863 // probably need to do more here in the future (post 2.5.0)
871 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
872 * AlignmentAnnotation)
875 public void addAnnotation(AlignmentAnnotation aa)
877 addAnnotation(aa, -1);
883 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
884 * AlignmentAnnotation, int)
887 public void addAnnotation(AlignmentAnnotation aa, int pos)
889 if (aa.getRNAStruc() != null)
891 hasRNAStructure = true;
895 if (annotations != null)
897 aSize = annotations.length + 1;
900 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
902 if (pos == -1 || pos >= aSize)
904 temp[aSize - 1] = aa;
913 for (i = 0; i < (aSize - 1); i++, p++)
921 temp[p] = annotations[i];
930 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
932 if (aa == null || annotations == null || annotations.length - 1 < index)
937 int aSize = annotations.length;
938 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
942 for (int i = 0; i < aSize; i++)
951 temp[i] = annotations[i];
955 temp[i] = annotations[i - 1];
964 * returns all annotation on the alignment
966 public AlignmentAnnotation[] getAlignmentAnnotation()
972 public boolean isNucleotide()
978 public boolean hasRNAStructure()
980 // TODO can it happen that structure is removed from alignment?
981 return hasRNAStructure;
985 public void setDataset(AlignmentI data)
987 if (dataset == null && data == null)
989 createDatasetAlignment();
991 else if (dataset == null && data != null)
993 if (!(data instanceof Alignment))
996 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
998 dataset = (Alignment) data;
999 for (int i = 0; i < getHeight(); i++)
1001 SequenceI currentSeq = getSequenceAt(i);
1002 SequenceI dsq = currentSeq.getDatasetSequence();
1005 dsq = currentSeq.createDatasetSequence();
1006 dataset.addSequence(dsq);
1010 while (dsq.getDatasetSequence() != null)
1012 dsq = dsq.getDatasetSequence();
1014 if (dataset.findIndex(dsq) == -1)
1016 dataset.addSequence(dsq);
1021 dataset.addAlignmentRef();
1025 * add dataset sequences to seq for currentSeq and any sequences it references
1027 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1028 Set<SequenceI> seqs, boolean createDatasetSequence)
1030 SequenceI alignedSeq = currentSeq;
1031 if (currentSeq.getDatasetSequence() != null)
1033 currentSeq = currentSeq.getDatasetSequence();
1037 if (createDatasetSequence)
1039 currentSeq = currentSeq.createDatasetSequence();
1042 if (seqs.contains(currentSeq))
1046 List<SequenceI> toProcess = new ArrayList<SequenceI>();
1047 toProcess.add(currentSeq);
1048 while (toProcess.size() > 0)
1051 SequenceI curDs = toProcess.remove(0);
1052 if (seqs.contains(curDs))
1057 // iterate over database references, making sure we add forward referenced
1059 if (curDs.getDBRefs() != null)
1061 for (DBRefEntry dbr : curDs.getDBRefs())
1063 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1065 if (dbr.getMap().getTo() == alignedSeq)
1068 * update mapping to be to the newly created dataset sequence
1070 dbr.getMap().setTo(currentSeq);
1072 if (dbr.getMap().getTo().getDatasetSequence() != null)
1075 "Implementation error: Map.getTo() for dbref " + dbr
1076 + " from " + curDs.getName()
1077 + " is not a dataset sequence.");
1079 // we recurse to add all forward references to dataset sequences via
1081 toProcess.add(dbr.getMap().getTo());
1089 * Creates a new dataset for this alignment. Can only be done once - if
1090 * dataset is not null this will not be performed.
1092 public void createDatasetAlignment()
1094 if (dataset != null)
1098 // try to avoid using SequenceI.equals at this stage, it will be expensive
1099 Set<SequenceI> seqs = new LinkedIdentityHashSet<SequenceI>();
1101 for (int i = 0; i < getHeight(); i++)
1103 SequenceI currentSeq = getSequenceAt(i);
1104 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1107 // verify all mappings are in dataset
1108 for (AlignedCodonFrame cf : codonFrameList)
1110 for (SequenceToSequenceMapping ssm : cf.getMappings())
1112 if (!seqs.contains(ssm.getFromSeq()))
1114 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1116 if (!seqs.contains(ssm.getMapping().getTo()))
1118 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1122 // finally construct dataset
1123 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1124 // move mappings to the dataset alignment
1125 dataset.codonFrameList = this.codonFrameList;
1126 this.codonFrameList = null;
1130 * reference count for number of alignments referencing this one.
1132 int alignmentRefs = 0;
1135 * increase reference count to this alignment.
1137 private void addAlignmentRef()
1143 public Alignment getDataset()
1149 public boolean padGaps()
1151 boolean modified = false;
1153 // Remove excess gaps from the end of alignment
1157 for (int i = 0; i < sequences.size(); i++)
1159 current = getSequenceAt(i);
1160 for (int j = current.getLength(); j > maxLength; j--)
1163 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1174 for (int i = 0; i < sequences.size(); i++)
1176 current = getSequenceAt(i);
1177 cLength = current.getLength();
1179 if (cLength < maxLength)
1181 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1184 else if (current.getLength() > maxLength)
1186 current.deleteChars(maxLength, current.getLength());
1193 * Justify the sequences to the left or right by deleting and inserting gaps
1194 * before the initial residue or after the terminal residue
1197 * true if alignment padded to right, false to justify to left
1198 * @return true if alignment was changed
1201 public boolean justify(boolean right)
1203 boolean modified = false;
1205 // Remove excess gaps from the end of alignment
1207 int ends[] = new int[sequences.size() * 2];
1209 for (int i = 0; i < sequences.size(); i++)
1211 current = getSequenceAt(i);
1212 // This should really be a sequence method
1213 ends[i * 2] = current.findIndex(current.getStart());
1214 ends[i * 2 + 1] = current.findIndex(current.getStart()
1215 + current.getLength());
1216 boolean hitres = false;
1217 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1219 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1228 ends[i * 2 + 1] = j;
1229 if (j - ends[i * 2] > maxLength)
1231 maxLength = j - ends[i * 2];
1239 // now edit the flanking gaps to justify to either left or right
1240 int cLength, extent, diff;
1241 for (int i = 0; i < sequences.size(); i++)
1243 current = getSequenceAt(i);
1245 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1246 diff = maxLength - cLength; // number of gaps to indent
1247 extent = current.getLength();
1251 if (extent > ends[i * 2 + 1])
1253 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1256 if (ends[i * 2] > diff)
1258 current.deleteChars(0, ends[i * 2] - diff);
1263 if (ends[i * 2] < diff)
1265 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1273 if (ends[i * 2] > 0)
1275 current.deleteChars(0, ends[i * 2]);
1277 ends[i * 2 + 1] -= ends[i * 2];
1278 extent -= ends[i * 2];
1280 if (extent > maxLength)
1282 current.deleteChars(maxLength + 1, extent);
1287 if (extent < maxLength)
1289 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1299 public HiddenSequences getHiddenSequences()
1301 return hiddenSequences;
1305 public CigarArray getCompactAlignment()
1307 synchronized (sequences)
1309 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1311 for (SequenceI seq : sequences)
1313 alseqs[i++] = new SeqCigar(seq);
1315 CigarArray cal = new CigarArray(alseqs);
1316 cal.addOperation(CigarArray.M, getWidth());
1322 public void setProperty(Object key, Object value)
1324 if (alignmentProperties == null)
1326 alignmentProperties = new Hashtable();
1329 alignmentProperties.put(key, value);
1333 public Object getProperty(Object key)
1335 if (alignmentProperties != null)
1337 return alignmentProperties.get(key);
1346 public Hashtable getProperties()
1348 return alignmentProperties;
1352 * Adds the given mapping to the stored set. Note this may be held on the
1353 * dataset alignment.
1356 public void addCodonFrame(AlignedCodonFrame codons)
1358 List<AlignedCodonFrame> acfs = getCodonFrames();
1359 if (codons != null && acfs != null && !acfs.contains(codons))
1369 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1372 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1378 List<AlignedCodonFrame> cframes = new ArrayList<AlignedCodonFrame>();
1379 for (AlignedCodonFrame acf : getCodonFrames())
1381 if (acf.involvesSequence(seq))
1390 * Sets the codon frame mappings (replacing any existing mappings). Note the
1391 * mappings are set on the dataset alignment instead if there is one.
1393 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1396 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1398 if (dataset != null)
1400 dataset.setCodonFrames(acfs);
1404 this.codonFrameList = acfs;
1409 * Returns the set of codon frame mappings. Any changes to the returned set
1410 * will affect the alignment. The mappings are held on (and read from) the
1411 * dataset alignment if there is one.
1413 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1416 public List<AlignedCodonFrame> getCodonFrames()
1418 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1419 // this behaviour is currently incorrect. method should return codon frames
1420 // for just the alignment,
1421 // selected from dataset
1422 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1426 * Removes the given mapping from the stored set. Note that the mappings are
1427 * held on the dataset alignment if there is one.
1430 public boolean removeCodonFrame(AlignedCodonFrame codons)
1432 List<AlignedCodonFrame> acfs = getCodonFrames();
1433 if (codons == null || acfs == null)
1437 return acfs.remove(codons);
1441 public void append(AlignmentI toappend)
1443 // TODO JAL-1270 needs test coverage
1444 // currently tested for use in jalview.gui.SequenceFetcher
1445 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1446 char oldc = toappend.getGapCharacter();
1447 boolean hashidden = toappend.getHiddenSequences() != null
1448 && toappend.getHiddenSequences().hiddenSequences != null;
1449 // get all sequences including any hidden ones
1450 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1451 .getFullAlignment().getSequences() : toappend.getSequences();
1454 // avoid self append deadlock by
1455 List<SequenceI> toappendsq = new ArrayList<SequenceI>();
1458 for (SequenceI addedsq : sqs)
1462 char[] oldseq = addedsq.getSequence();
1463 for (int c = 0; c < oldseq.length; c++)
1465 if (oldseq[c] == oldc)
1467 oldseq[c] = gapCharacter;
1471 toappendsq.add(addedsq);
1474 for (SequenceI addedsq : toappendsq)
1476 addSequence(addedsq);
1479 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1480 for (int a = 0; alan != null && a < alan.length; a++)
1482 addAnnotation(alan[a]);
1486 getCodonFrames().addAll(toappend.getCodonFrames());
1488 List<SequenceGroup> sg = toappend.getGroups();
1491 for (SequenceGroup _sg : sg)
1496 if (toappend.getHiddenSequences() != null)
1498 HiddenSequences hs = toappend.getHiddenSequences();
1499 if (hiddenSequences == null)
1501 hiddenSequences = new HiddenSequences(this);
1503 if (hs.hiddenSequences != null)
1505 for (int s = 0; s < hs.hiddenSequences.length; s++)
1507 // hide the newly appended sequence in the alignment
1508 if (hs.hiddenSequences[s] != null)
1510 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1515 if (toappend.getProperties() != null)
1517 // we really can't do very much here - just try to concatenate strings
1518 // where property collisions occur.
1519 Enumeration key = toappend.getProperties().keys();
1520 while (key.hasMoreElements())
1522 Object k = key.nextElement();
1523 Object ourval = this.getProperty(k);
1524 Object toapprop = toappend.getProperty(k);
1527 if (ourval.getClass().equals(toapprop.getClass())
1528 && !ourval.equals(toapprop))
1530 if (ourval instanceof String)
1533 this.setProperty(k, ((String) ourval) + "; "
1534 + ((String) toapprop));
1538 if (ourval instanceof Vector)
1541 Enumeration theirv = ((Vector) toapprop).elements();
1542 while (theirv.hasMoreElements())
1544 ((Vector) ourval).addElement(theirv);
1552 // just add new property directly
1553 setProperty(k, toapprop);
1561 public AlignmentAnnotation findOrCreateAnnotation(String name,
1562 String calcId, boolean autoCalc, SequenceI seqRef,
1563 SequenceGroup groupRef)
1565 if (annotations != null)
1567 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1569 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1570 && (calcId == null || annot.getCalcId().equals(calcId))
1571 && annot.sequenceRef == seqRef
1572 && annot.groupRef == groupRef)
1578 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1579 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1580 annot.hasText = false;
1581 annot.setCalcId(new String(calcId));
1582 annot.autoCalculated = autoCalc;
1585 annot.setSequenceRef(seqRef);
1587 annot.groupRef = groupRef;
1588 addAnnotation(annot);
1594 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1596 List<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1597 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1598 if (alignmentAnnotation != null)
1600 for (AlignmentAnnotation a : alignmentAnnotation)
1602 if (a.getCalcId() == calcId
1603 || (a.getCalcId() != null && calcId != null && a
1604 .getCalcId().equals(calcId)))
1614 * Returns an iterable collection of any annotations that match on given
1615 * sequence ref, calcId and label (ignoring null values).
1618 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1619 String calcId, String label)
1621 ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1622 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1624 if (ann.getCalcId() != null && ann.getCalcId().equals(calcId)
1625 && ann.sequenceRef != null && ann.sequenceRef == seq
1626 && ann.label != null && ann.label.equals(label))
1635 public void moveSelectedSequencesByOne(SequenceGroup sg,
1636 Map<SequenceI, SequenceCollectionI> map, boolean up)
1638 synchronized (sequences)
1643 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1645 SequenceI seq = sequences.get(i);
1646 if (!sg.getSequences(map).contains(seq))
1651 SequenceI temp = sequences.get(i - 1);
1652 if (sg.getSequences(null).contains(temp))
1657 sequences.set(i, temp);
1658 sequences.set(i - 1, seq);
1663 for (int i = sequences.size() - 2; i > -1; i--)
1665 SequenceI seq = sequences.get(i);
1666 if (!sg.getSequences(map).contains(seq))
1671 SequenceI temp = sequences.get(i + 1);
1672 if (sg.getSequences(map).contains(temp))
1677 sequences.set(i, temp);
1678 sequences.set(i + 1, seq);
1686 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1688 alignmentAnnotation.validateRangeAndDisplay();
1689 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1691 hasRNAStructure = true;
1695 private SequenceI seqrep = null;
1699 * @return the representative sequence for this group
1702 public SequenceI getSeqrep()
1708 * set the representative sequence for this group. Note - this affects the
1709 * interpretation of the Hidereps attribute.
1712 * the seqrep to set (null means no sequence representative)
1715 public void setSeqrep(SequenceI seqrep)
1717 this.seqrep = seqrep;
1722 * @return true if group has a sequence representative
1725 public boolean hasSeqrep()
1727 return seqrep != null;
1731 public int getEndRes()
1733 return getWidth() - 1;
1737 public int getStartRes()
1743 * In the case of AlignmentI - returns the dataset for the alignment, if set
1746 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1749 public AnnotatedCollectionI getContext()
1755 * Align this alignment like the given (mapped) one.
1758 public int alignAs(AlignmentI al)
1761 * Currently retains unmapped gaps (in introns), regaps mapped regions
1764 return alignAs(al, false, true);
1768 * Align this alignment 'the same as' the given one. Mapped sequences only are
1769 * realigned. If both of the same type (nucleotide/protein) then align both
1770 * identically. If this is nucleotide and the other is protein, make 3 gaps
1771 * for each gap in the protein sequences. If this is protein and the other is
1772 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1773 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1774 * protein to match the relative ordering of codons in the nucleotide.
1776 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1777 * regions are preserved. Gaps that connect introns to exons are treated
1778 * conservatively, i.e. only preserved if both intron and exon gaps are
1779 * preserved. TODO: check caveats below where the implementation fails
1782 * - must have same dataset, and sequences in al must have equivalent
1783 * dataset sequence and start/end bounds under given mapping
1784 * @param preserveMappedGaps
1785 * if true, gaps within and between mapped codons are preserved
1786 * @param preserveUnmappedGaps
1787 * if true, gaps within and between unmapped codons are preserved
1790 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1791 boolean preserveUnmappedGaps)
1793 // TODO should this method signature be the one in the interface?
1794 // JBPComment - yes - neither flag is used, so should be deleted.
1795 boolean thisIsNucleotide = this.isNucleotide();
1796 boolean thatIsProtein = !al.isNucleotide();
1797 if (!thatIsProtein && !thisIsNucleotide)
1799 return AlignmentUtils.alignProteinAsDna(this, al);
1801 else if (thatIsProtein && thisIsNucleotide)
1803 return AlignmentUtils.alignCdsAsProtein(this, al);
1805 return AlignmentUtils.alignAs(this, al);
1809 * Returns the alignment in Fasta format. Behaviour of this method is not
1810 * guaranteed between versions.
1813 public String toString()
1815 return new FastaFile().print(getSequencesArray(), true);
1819 * Returns the set of distinct sequence names. No ordering is guaranteed.
1822 public Set<String> getSequenceNames()
1824 Set<String> names = new HashSet<String>();
1825 for (SequenceI seq : getSequences())
1827 names.add(seq.getName());
1833 public boolean hasValidSequence()
1835 boolean hasValidSeq = false;
1836 for (SequenceI seq : getSequences())
1838 if ((seq.getEnd() - seq.getStart()) > 0)
1848 * Update any mappings to 'virtual' sequences to compatible real ones, if
1849 * present in the added sequences. Returns a count of mappings updated.
1855 public int realiseMappings(List<SequenceI> seqs)
1858 for (SequenceI seq : seqs)
1860 for (AlignedCodonFrame mapping : getCodonFrames())
1862 count += mapping.realiseWith(seq);
1869 * Returns the first AlignedCodonFrame that has a mapping between the given
1877 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1879 for (AlignedCodonFrame acf : getCodonFrames())
1881 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1890 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1892 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1893 int startPos = alignmentStartEnd[0];
1894 int endPos = alignmentStartEnd[1];
1896 int[] lowestRange = new int[] { -1, -1 };
1897 int[] higestRange = new int[] { -1, -1 };
1899 for (int[] hiddenCol : hiddenCols)
1901 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1902 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1905 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1907 startPos = alignmentStartEnd[0];
1911 startPos = lowestRange[1] + 1;
1914 if (higestRange[0] == -1 && higestRange[1] == -1)
1916 endPos = alignmentStartEnd[1];
1920 endPos = higestRange[0] - 1;
1922 return new int[] { startPos, endPos };