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 protected int type = NUCLEOTIDE;
59 public static final int PROTEIN = 0;
61 public static final int NUCLEOTIDE = 1;
63 public boolean hasRNAStructure = false;
65 public AlignmentAnnotation[] annotations;
67 HiddenSequences hiddenSequences;
69 public Hashtable alignmentProperties;
71 private List<AlignedCodonFrame> codonFrameList;
73 private void initAlignment(SequenceI[] seqs)
75 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
76 hiddenSequences = new HiddenSequences(this);
77 codonFrameList = new ArrayList<AlignedCodonFrame>();
79 if (Comparison.isNucleotide(seqs))
88 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
90 for (int i = 0; i < seqs.length; i++)
92 sequences.add(seqs[i]);
98 * Make a 'copy' alignment - sequences have new copies of features and
99 * annotations, but share the original dataset sequences.
101 public Alignment(AlignmentI al)
103 SequenceI[] seqs = al.getSequencesArray();
104 for (int i = 0; i < seqs.length; i++)
106 seqs[i] = new Sequence(seqs[i]);
112 * Share the same dataset sequence mappings (if any).
114 if (dataset == null && al.getDataset() == null)
116 this.setCodonFrames(al.getCodonFrames());
121 * Make an alignment from an array of Sequences.
125 public Alignment(SequenceI[] seqs)
131 * Make a new alignment from an array of SeqCigars
136 public Alignment(SeqCigar[] alseqs)
138 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
139 gapCharacter, new ColumnSelection(), null);
144 * Make a new alignment from an CigarArray JBPNote - can only do this when
145 * compactAlignment does not contain hidden regions. JBPNote - must also check
146 * that compactAlignment resolves to a set of SeqCigars - or construct them
149 * @param compactAlignment
152 public static AlignmentI createAlignment(CigarArray compactAlignment)
156 .getString("error.alignment_cigararray_not_implemented"));
157 // this(compactAlignment.refCigars);
161 public List<SequenceI> getSequences()
167 public List<SequenceI> getSequences(
168 Map<SequenceI, SequenceCollectionI> hiddenReps)
170 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
176 public SequenceI[] getSequencesArray()
178 if (sequences == null)
182 synchronized (sequences)
184 return sequences.toArray(new SequenceI[sequences.size()]);
189 * Returns a map of lists of sequences keyed by sequence name.
194 public Map<String, List<SequenceI>> getSequencesByName()
196 return AlignmentUtils.getSequencesByName(this);
205 * @return DOCUMENT ME!
208 public SequenceI getSequenceAt(int i)
210 synchronized (sequences)
212 if (i > -1 && i < sequences.size())
214 return sequences.get(i);
221 * Adds a sequence to the alignment. Recalculates maxLength and size.
226 public void addSequence(SequenceI snew)
231 // maintain dataset integrity
232 SequenceI dsseq = snew.getDatasetSequence();
235 // derive new sequence
236 SequenceI adding = snew.deriveSequence();
238 dsseq = snew.getDatasetSequence();
240 if (getDataset().findIndex(dsseq) == -1)
242 getDataset().addSequence(dsseq);
246 if (sequences == null)
248 initAlignment(new SequenceI[] { snew });
252 synchronized (sequences)
257 if (hiddenSequences != null)
259 hiddenSequences.adjustHeightSequenceAdded();
264 public SequenceI replaceSequenceAt(int i, SequenceI snew)
266 synchronized (sequences)
268 if (sequences.size() > i)
270 return sequences.set(i, snew);
276 hiddenSequences.adjustHeightSequenceAdded();
285 * @return DOCUMENT ME!
288 public List<SequenceGroup> getGroups()
294 public void finalize() throws Throwable
296 if (getDataset() != null)
298 getDataset().removeAlignmentRef();
306 * Defensively nulls out references in case this object is not garbage
309 void nullReferences()
315 hiddenSequences = null;
319 * decrement the alignmentRefs counter by one and null references if it goes
324 private void removeAlignmentRef() throws Throwable
326 if (--alignmentRefs == 0)
339 public void deleteSequence(SequenceI s)
341 deleteSequence(findIndex(s));
351 public void deleteSequence(int i)
353 if (i > -1 && i < getHeight())
355 synchronized (sequences)
358 hiddenSequences.adjustHeightSequenceDeleted(i);
366 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
369 public SequenceGroup findGroup(SequenceI s)
371 synchronized (groups)
373 for (int i = 0; i < this.groups.size(); i++)
375 SequenceGroup sg = groups.get(i);
377 if (sg.getSequences(null).contains(s))
390 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
393 public SequenceGroup[] findAllGroups(SequenceI s)
395 ArrayList<SequenceGroup> temp = new ArrayList<SequenceGroup>();
397 synchronized (groups)
399 int gSize = groups.size();
400 for (int i = 0; i < gSize; i++)
402 SequenceGroup sg = groups.get(i);
403 if (sg == null || sg.getSequences() == null)
405 this.deleteGroup(sg);
410 if (sg.getSequences().contains(s))
416 SequenceGroup[] ret = new SequenceGroup[temp.size()];
417 return temp.toArray(ret);
422 public void addGroup(SequenceGroup sg)
424 synchronized (groups)
426 if (!groups.contains(sg))
428 if (hiddenSequences.getSize() > 0)
430 int i, iSize = sg.getSize();
431 for (i = 0; i < iSize; i++)
433 if (!sequences.contains(sg.getSequenceAt(i)))
435 sg.deleteSequence(sg.getSequenceAt(i), false);
441 if (sg.getSize() < 1)
453 * remove any annotation that references gp
456 * (if null, removes all group associated annotation)
458 private void removeAnnotationForGroup(SequenceGroup gp)
460 if (annotations == null || annotations.length == 0)
464 // remove annotation very quickly
465 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
469 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
471 if (annotations[i].groupRef != null)
473 todelete[p++] = annotations[i];
477 tokeep[k++] = annotations[i];
483 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
485 if (annotations[i].groupRef == gp)
487 todelete[p++] = annotations[i];
491 tokeep[k++] = annotations[i];
497 // clear out the group associated annotation.
498 for (i = 0; i < p; i++)
500 unhookAnnotation(todelete[i]);
503 t = new AlignmentAnnotation[k];
504 for (i = 0; i < k; i++)
513 public void deleteAllGroups()
515 synchronized (groups)
517 if (annotations != null)
519 removeAnnotationForGroup(null);
521 for (SequenceGroup sg : groups)
531 public void deleteGroup(SequenceGroup g)
533 synchronized (groups)
535 if (groups.contains(g))
537 removeAnnotationForGroup(g);
546 public SequenceI findName(String name)
548 return findName(name, false);
554 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
557 public SequenceI findName(String token, boolean b)
559 return findName(null, token, b);
565 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
569 public SequenceI findName(SequenceI startAfter, String token, boolean b)
574 String sqname = null;
575 if (startAfter != null)
577 // try to find the sequence in the alignment
578 boolean matched = false;
579 while (i < sequences.size())
581 if (getSequenceAt(i++) == startAfter)
592 while (i < sequences.size())
594 sq = getSequenceAt(i);
595 sqname = sq.getName();
596 if (sqname.equals(token) // exact match
597 || (b && // allow imperfect matches - case varies
598 (sqname.equalsIgnoreCase(token))))
600 return getSequenceAt(i);
610 public SequenceI[] findSequenceMatch(String name)
612 Vector matches = new Vector();
615 while (i < sequences.size())
617 if (getSequenceAt(i).getName().equals(name))
619 matches.addElement(getSequenceAt(i));
624 SequenceI[] result = new SequenceI[matches.size()];
625 for (i = 0; i < result.length; i++)
627 result[i] = (SequenceI) matches.elementAt(i);
637 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
640 public int findIndex(SequenceI s)
644 while (i < sequences.size())
646 if (s == getSequenceAt(i))
661 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
664 public int findIndex(SearchResultsI results)
668 while (i < sequences.size())
670 if (results.involvesSequence(getSequenceAt(i)))
682 * @return DOCUMENT ME!
685 public int getHeight()
687 return sequences.size();
693 * @return DOCUMENT ME!
696 public int getWidth()
700 for (int i = 0; i < sequences.size(); i++)
702 if (getSequenceAt(i).getLength() > maxLength)
704 maxLength = getSequenceAt(i).getLength();
718 public void setGapCharacter(char gc)
721 synchronized (sequences)
723 for (SequenceI seq : sequences)
725 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
726 .replace('-', gc).replace(' ', gc));
734 * @return DOCUMENT ME!
737 public char getGapCharacter()
745 * @see jalview.datamodel.AlignmentI#isAligned()
748 public boolean isAligned()
750 return isAligned(false);
756 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
759 public boolean isAligned(boolean includeHidden)
761 int width = getWidth();
762 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
764 includeHidden = true; // no hidden sequences to check against.
766 for (int i = 0; i < sequences.size(); i++)
768 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
770 if (getSequenceAt(i).getLength() != width)
781 * Delete all annotations, including auto-calculated if the flag is set true.
782 * Returns true if at least one annotation was deleted, else false.
784 * @param includingAutoCalculated
788 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
790 boolean result = false;
791 for (AlignmentAnnotation alan : getAlignmentAnnotation())
793 if (!alan.autoCalculated || includingAutoCalculated)
795 deleteAnnotation(alan);
805 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
806 * AlignmentAnnotation)
809 public boolean deleteAnnotation(AlignmentAnnotation aa)
811 return deleteAnnotation(aa, true);
815 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
819 if (annotations != null)
821 aSize = annotations.length;
829 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
831 boolean swap = false;
834 for (int i = 0; i < aSize; i++)
836 if (annotations[i] == aa)
841 if (tIndex < temp.length)
843 temp[tIndex++] = annotations[i];
852 unhookAnnotation(aa);
859 * remove any object references associated with this annotation
863 private void unhookAnnotation(AlignmentAnnotation aa)
865 if (aa.sequenceRef != null)
867 aa.sequenceRef.removeAlignmentAnnotation(aa);
869 if (aa.groupRef != null)
871 // probably need to do more here in the future (post 2.5.0)
879 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
880 * AlignmentAnnotation)
883 public void addAnnotation(AlignmentAnnotation aa)
885 addAnnotation(aa, -1);
891 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
892 * AlignmentAnnotation, int)
895 public void addAnnotation(AlignmentAnnotation aa, int pos)
897 if (aa.getRNAStruc() != null)
899 hasRNAStructure = true;
903 if (annotations != null)
905 aSize = annotations.length + 1;
908 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
910 if (pos == -1 || pos >= aSize)
912 temp[aSize - 1] = aa;
921 for (i = 0; i < (aSize - 1); i++, p++)
929 temp[p] = annotations[i];
938 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
940 if (aa == null || annotations == null || annotations.length - 1 < index)
945 int aSize = annotations.length;
946 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
950 for (int i = 0; i < aSize; i++)
959 temp[i] = annotations[i];
963 temp[i] = annotations[i - 1];
972 * returns all annotation on the alignment
974 public AlignmentAnnotation[] getAlignmentAnnotation()
980 public void setNucleotide(boolean b)
993 public boolean isNucleotide()
995 if (type == NUCLEOTIDE)
1006 public boolean hasRNAStructure()
1008 // TODO can it happen that structure is removed from alignment?
1009 return hasRNAStructure;
1013 public void setDataset(AlignmentI data)
1015 if (dataset == null && data == null)
1017 createDatasetAlignment();
1019 else if (dataset == null && data != null)
1021 if (!(data instanceof Alignment))
1024 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1026 dataset = (Alignment) data;
1027 for (int i = 0; i < getHeight(); i++)
1029 SequenceI currentSeq = getSequenceAt(i);
1030 SequenceI dsq = currentSeq.getDatasetSequence();
1033 dsq = currentSeq.createDatasetSequence();
1034 dataset.addSequence(dsq);
1038 while (dsq.getDatasetSequence() != null)
1040 dsq = dsq.getDatasetSequence();
1042 if (dataset.findIndex(dsq) == -1)
1044 dataset.addSequence(dsq);
1049 dataset.addAlignmentRef();
1053 * add dataset sequences to seq for currentSeq and any sequences it references
1055 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1056 Set<SequenceI> seqs, boolean createDatasetSequence)
1058 SequenceI alignedSeq = currentSeq;
1059 if (currentSeq.getDatasetSequence() != null)
1061 currentSeq = currentSeq.getDatasetSequence();
1065 if (createDatasetSequence)
1067 currentSeq = currentSeq.createDatasetSequence();
1070 if (seqs.contains(currentSeq))
1074 List<SequenceI> toProcess = new ArrayList<SequenceI>();
1075 toProcess.add(currentSeq);
1076 while (toProcess.size() > 0)
1079 SequenceI curDs = toProcess.remove(0);
1080 if (seqs.contains(curDs))
1085 // iterate over database references, making sure we add forward referenced
1087 if (curDs.getDBRefs() != null)
1089 for (DBRefEntry dbr : curDs.getDBRefs())
1091 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1093 if (dbr.getMap().getTo() == alignedSeq)
1096 * update mapping to be to the newly created dataset sequence
1098 dbr.getMap().setTo(currentSeq);
1100 if (dbr.getMap().getTo().getDatasetSequence() != null)
1103 "Implementation error: Map.getTo() for dbref " + dbr
1104 + " from " + curDs.getName()
1105 + " is not a dataset sequence.");
1107 // we recurse to add all forward references to dataset sequences via
1109 toProcess.add(dbr.getMap().getTo());
1117 * Creates a new dataset for this alignment. Can only be done once - if
1118 * dataset is not null this will not be performed.
1120 public void createDatasetAlignment()
1122 if (dataset != null)
1126 // try to avoid using SequenceI.equals at this stage, it will be expensive
1127 Set<SequenceI> seqs = new LinkedIdentityHashSet<SequenceI>();
1129 for (int i = 0; i < getHeight(); i++)
1131 SequenceI currentSeq = getSequenceAt(i);
1132 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1135 // verify all mappings are in dataset
1136 for (AlignedCodonFrame cf : codonFrameList)
1138 for (SequenceToSequenceMapping ssm : cf.getMappings())
1140 if (!seqs.contains(ssm.getFromSeq()))
1142 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1144 if (!seqs.contains(ssm.getMapping().getTo()))
1146 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1150 // finally construct dataset
1151 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1152 // move mappings to the dataset alignment
1153 dataset.codonFrameList = this.codonFrameList;
1154 this.codonFrameList = null;
1158 * reference count for number of alignments referencing this one.
1160 int alignmentRefs = 0;
1163 * increase reference count to this alignment.
1165 private void addAlignmentRef()
1171 public Alignment getDataset()
1177 public boolean padGaps()
1179 boolean modified = false;
1181 // Remove excess gaps from the end of alignment
1185 for (int i = 0; i < sequences.size(); i++)
1187 current = getSequenceAt(i);
1188 for (int j = current.getLength(); j > maxLength; j--)
1191 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1202 for (int i = 0; i < sequences.size(); i++)
1204 current = getSequenceAt(i);
1205 cLength = current.getLength();
1207 if (cLength < maxLength)
1209 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1212 else if (current.getLength() > maxLength)
1214 current.deleteChars(maxLength, current.getLength());
1221 * Justify the sequences to the left or right by deleting and inserting gaps
1222 * before the initial residue or after the terminal residue
1225 * true if alignment padded to right, false to justify to left
1226 * @return true if alignment was changed
1229 public boolean justify(boolean right)
1231 boolean modified = false;
1233 // Remove excess gaps from the end of alignment
1235 int ends[] = new int[sequences.size() * 2];
1237 for (int i = 0; i < sequences.size(); i++)
1239 current = getSequenceAt(i);
1240 // This should really be a sequence method
1241 ends[i * 2] = current.findIndex(current.getStart());
1242 ends[i * 2 + 1] = current.findIndex(current.getStart()
1243 + current.getLength());
1244 boolean hitres = false;
1245 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1247 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1256 ends[i * 2 + 1] = j;
1257 if (j - ends[i * 2] > maxLength)
1259 maxLength = j - ends[i * 2];
1267 // now edit the flanking gaps to justify to either left or right
1268 int cLength, extent, diff;
1269 for (int i = 0; i < sequences.size(); i++)
1271 current = getSequenceAt(i);
1273 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1274 diff = maxLength - cLength; // number of gaps to indent
1275 extent = current.getLength();
1279 if (extent > ends[i * 2 + 1])
1281 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1284 if (ends[i * 2] > diff)
1286 current.deleteChars(0, ends[i * 2] - diff);
1291 if (ends[i * 2] < diff)
1293 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1301 if (ends[i * 2] > 0)
1303 current.deleteChars(0, ends[i * 2]);
1305 ends[i * 2 + 1] -= ends[i * 2];
1306 extent -= ends[i * 2];
1308 if (extent > maxLength)
1310 current.deleteChars(maxLength + 1, extent);
1315 if (extent < maxLength)
1317 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1327 public HiddenSequences getHiddenSequences()
1329 return hiddenSequences;
1333 public CigarArray getCompactAlignment()
1335 synchronized (sequences)
1337 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1339 for (SequenceI seq : sequences)
1341 alseqs[i++] = new SeqCigar(seq);
1343 CigarArray cal = new CigarArray(alseqs);
1344 cal.addOperation(CigarArray.M, getWidth());
1350 public void setProperty(Object key, Object value)
1352 if (alignmentProperties == null)
1354 alignmentProperties = new Hashtable();
1357 alignmentProperties.put(key, value);
1361 public Object getProperty(Object key)
1363 if (alignmentProperties != null)
1365 return alignmentProperties.get(key);
1374 public Hashtable getProperties()
1376 return alignmentProperties;
1380 * Adds the given mapping to the stored set. Note this may be held on the
1381 * dataset alignment.
1384 public void addCodonFrame(AlignedCodonFrame codons)
1386 List<AlignedCodonFrame> acfs = getCodonFrames();
1387 if (codons != null && acfs != null && !acfs.contains(codons))
1397 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1400 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1406 List<AlignedCodonFrame> cframes = new ArrayList<AlignedCodonFrame>();
1407 for (AlignedCodonFrame acf : getCodonFrames())
1409 if (acf.involvesSequence(seq))
1418 * Sets the codon frame mappings (replacing any existing mappings). Note the
1419 * mappings are set on the dataset alignment instead if there is one.
1421 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1424 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1426 if (dataset != null)
1428 dataset.setCodonFrames(acfs);
1432 this.codonFrameList = acfs;
1437 * Returns the set of codon frame mappings. Any changes to the returned set
1438 * will affect the alignment. The mappings are held on (and read from) the
1439 * dataset alignment if there is one.
1441 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1444 public List<AlignedCodonFrame> getCodonFrames()
1446 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1447 // this behaviour is currently incorrect. method should return codon frames
1448 // for just the alignment,
1449 // selected from dataset
1450 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1454 * Removes the given mapping from the stored set. Note that the mappings are
1455 * held on the dataset alignment if there is one.
1458 public boolean removeCodonFrame(AlignedCodonFrame codons)
1460 List<AlignedCodonFrame> acfs = getCodonFrames();
1461 if (codons == null || acfs == null)
1465 return acfs.remove(codons);
1469 public void append(AlignmentI toappend)
1471 // TODO JAL-1270 needs test coverage
1472 // currently tested for use in jalview.gui.SequenceFetcher
1473 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1474 char oldc = toappend.getGapCharacter();
1475 boolean hashidden = toappend.getHiddenSequences() != null
1476 && toappend.getHiddenSequences().hiddenSequences != null;
1477 // get all sequences including any hidden ones
1478 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1479 .getFullAlignment().getSequences() : toappend.getSequences();
1482 // avoid self append deadlock by
1483 List<SequenceI> toappendsq = new ArrayList<SequenceI>();
1486 for (SequenceI addedsq : sqs)
1490 char[] oldseq = addedsq.getSequence();
1491 for (int c = 0; c < oldseq.length; c++)
1493 if (oldseq[c] == oldc)
1495 oldseq[c] = gapCharacter;
1499 toappendsq.add(addedsq);
1502 for (SequenceI addedsq : toappendsq)
1504 addSequence(addedsq);
1507 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1508 for (int a = 0; alan != null && a < alan.length; a++)
1510 addAnnotation(alan[a]);
1514 getCodonFrames().addAll(toappend.getCodonFrames());
1516 List<SequenceGroup> sg = toappend.getGroups();
1519 for (SequenceGroup _sg : sg)
1524 if (toappend.getHiddenSequences() != null)
1526 HiddenSequences hs = toappend.getHiddenSequences();
1527 if (hiddenSequences == null)
1529 hiddenSequences = new HiddenSequences(this);
1531 if (hs.hiddenSequences != null)
1533 for (int s = 0; s < hs.hiddenSequences.length; s++)
1535 // hide the newly appended sequence in the alignment
1536 if (hs.hiddenSequences[s] != null)
1538 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1543 if (toappend.getProperties() != null)
1545 // we really can't do very much here - just try to concatenate strings
1546 // where property collisions occur.
1547 Enumeration key = toappend.getProperties().keys();
1548 while (key.hasMoreElements())
1550 Object k = key.nextElement();
1551 Object ourval = this.getProperty(k);
1552 Object toapprop = toappend.getProperty(k);
1555 if (ourval.getClass().equals(toapprop.getClass())
1556 && !ourval.equals(toapprop))
1558 if (ourval instanceof String)
1561 this.setProperty(k, ((String) ourval) + "; "
1562 + ((String) toapprop));
1566 if (ourval instanceof Vector)
1569 Enumeration theirv = ((Vector) toapprop).elements();
1570 while (theirv.hasMoreElements())
1572 ((Vector) ourval).addElement(theirv);
1580 // just add new property directly
1581 setProperty(k, toapprop);
1589 public AlignmentAnnotation findOrCreateAnnotation(String name,
1590 String calcId, boolean autoCalc, SequenceI seqRef,
1591 SequenceGroup groupRef)
1593 assert (name != null);
1594 if (annotations != null)
1596 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1598 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1599 && (calcId == null || annot.getCalcId().equals(calcId))
1600 && annot.sequenceRef == seqRef
1601 && annot.groupRef == groupRef)
1607 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1608 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1609 annot.hasText = false;
1610 annot.setCalcId(new String(calcId));
1611 annot.autoCalculated = autoCalc;
1614 annot.setSequenceRef(seqRef);
1616 annot.groupRef = groupRef;
1617 addAnnotation(annot);
1623 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1625 ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1626 for (AlignmentAnnotation a : getAlignmentAnnotation())
1628 if (a.getCalcId() == calcId
1629 || (a.getCalcId() != null && calcId != null && a.getCalcId()
1639 * Returns an iterable collection of any annotations that match on given
1640 * sequence ref, calcId and label (ignoring null values).
1643 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1644 String calcId, String label)
1646 ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1647 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1649 if (ann.getCalcId() != null && ann.getCalcId().equals(calcId)
1650 && ann.sequenceRef != null && ann.sequenceRef == seq
1651 && ann.label != null && ann.label.equals(label))
1660 public void moveSelectedSequencesByOne(SequenceGroup sg,
1661 Map<SequenceI, SequenceCollectionI> map, boolean up)
1663 synchronized (sequences)
1668 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1670 SequenceI seq = sequences.get(i);
1671 if (!sg.getSequences(map).contains(seq))
1676 SequenceI temp = sequences.get(i - 1);
1677 if (sg.getSequences(null).contains(temp))
1682 sequences.set(i, temp);
1683 sequences.set(i - 1, seq);
1688 for (int i = sequences.size() - 2; i > -1; i--)
1690 SequenceI seq = sequences.get(i);
1691 if (!sg.getSequences(map).contains(seq))
1696 SequenceI temp = sequences.get(i + 1);
1697 if (sg.getSequences(map).contains(temp))
1702 sequences.set(i, temp);
1703 sequences.set(i + 1, seq);
1711 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1713 alignmentAnnotation.validateRangeAndDisplay();
1714 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1716 hasRNAStructure = true;
1720 private SequenceI seqrep = null;
1724 * @return the representative sequence for this group
1727 public SequenceI getSeqrep()
1733 * set the representative sequence for this group. Note - this affects the
1734 * interpretation of the Hidereps attribute.
1737 * the seqrep to set (null means no sequence representative)
1740 public void setSeqrep(SequenceI seqrep)
1742 this.seqrep = seqrep;
1747 * @return true if group has a sequence representative
1750 public boolean hasSeqrep()
1752 return seqrep != null;
1756 public int getEndRes()
1758 return getWidth() - 1;
1762 public int getStartRes()
1768 * In the case of AlignmentI - returns the dataset for the alignment, if set
1771 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1774 public AnnotatedCollectionI getContext()
1780 * Align this alignment like the given (mapped) one.
1783 public int alignAs(AlignmentI al)
1786 * Currently retains unmapped gaps (in introns), regaps mapped regions
1789 return alignAs(al, false, true);
1793 * Align this alignment 'the same as' the given one. Mapped sequences only are
1794 * realigned. If both of the same type (nucleotide/protein) then align both
1795 * identically. If this is nucleotide and the other is protein, make 3 gaps
1796 * for each gap in the protein sequences. If this is protein and the other is
1797 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1798 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1799 * protein to match the relative ordering of codons in the nucleotide.
1801 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1802 * regions are preserved. Gaps that connect introns to exons are treated
1803 * conservatively, i.e. only preserved if both intron and exon gaps are
1804 * preserved. TODO: check caveats below where the implementation fails
1807 * - must have same dataset, and sequences in al must have equivalent
1808 * dataset sequence and start/end bounds under given mapping
1809 * @param preserveMappedGaps
1810 * if true, gaps within and between mapped codons are preserved
1811 * @param preserveUnmappedGaps
1812 * if true, gaps within and between unmapped codons are preserved
1815 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1816 boolean preserveUnmappedGaps)
1818 // TODO should this method signature be the one in the interface?
1819 // JBPComment - yes - neither flag is used, so should be deleted.
1820 boolean thisIsNucleotide = this.isNucleotide();
1821 boolean thatIsProtein = !al.isNucleotide();
1822 if (!thatIsProtein && !thisIsNucleotide)
1824 return AlignmentUtils.alignProteinAsDna(this, al);
1826 else if (thatIsProtein && thisIsNucleotide)
1828 return AlignmentUtils.alignCdsAsProtein(this, al);
1830 return AlignmentUtils.alignAs(this, al);
1834 * Returns the alignment in Fasta format. Behaviour of this method is not
1835 * guaranteed between versions.
1838 public String toString()
1840 return new FastaFile().print(getSequencesArray(), true);
1844 * Returns the set of distinct sequence names. No ordering is guaranteed.
1847 public Set<String> getSequenceNames()
1849 Set<String> names = new HashSet<String>();
1850 for (SequenceI seq : getSequences())
1852 names.add(seq.getName());
1858 public boolean hasValidSequence()
1860 boolean hasValidSeq = false;
1861 for (SequenceI seq : getSequences())
1863 if ((seq.getEnd() - seq.getStart()) > 0)
1873 * Update any mappings to 'virtual' sequences to compatible real ones, if
1874 * present in the added sequences. Returns a count of mappings updated.
1880 public int realiseMappings(List<SequenceI> seqs)
1883 for (SequenceI seq : seqs)
1885 for (AlignedCodonFrame mapping : getCodonFrames())
1887 count += mapping.realiseWith(seq);
1894 * Returns the first AlignedCodonFrame that has a mapping between the given
1902 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1904 for (AlignedCodonFrame acf : getCodonFrames())
1906 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1915 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1917 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1918 int startPos = alignmentStartEnd[0];
1919 int endPos = alignmentStartEnd[1];
1921 int[] lowestRange = new int[] { -1, -1 };
1922 int[] higestRange = new int[] { -1, -1 };
1924 for (int[] hiddenCol : hiddenCols)
1926 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1927 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1930 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1932 startPos = alignmentStartEnd[0];
1936 startPos = lowestRange[1] + 1;
1939 if (higestRange[0] == -1 && higestRange[1] == -1)
1941 endPos = alignmentStartEnd[1];
1945 endPos = higestRange[0] - 1;
1947 return new int[] { startPos, endPos };