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);
190 public SequenceI getSequenceAt(int i)
192 synchronized (sequences)
194 if (i > -1 && i < sequences.size())
196 return sequences.get(i);
203 public SequenceI getSequenceAtAbsoluteIndex(int i)
205 SequenceI seq = null;
206 if (getHiddenSequences().getSize() > 0)
208 seq = getHiddenSequences().getHiddenSequence(i);
211 // didn't find the sequence in the hidden sequences, get it from the
213 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
214 seq = getSequenceAt(index);
219 seq = getSequenceAt(i);
225 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
226 * this currently does not recalculate whether or not the alignment is
227 * nucleotide, so mixed alignments may have undefined behaviour.
232 public void addSequence(SequenceI snew)
237 // maintain dataset integrity
238 SequenceI dsseq = snew.getDatasetSequence();
241 // derive new sequence
242 SequenceI adding = snew.deriveSequence();
244 dsseq = snew.getDatasetSequence();
246 if (getDataset().findIndex(dsseq) == -1)
248 getDataset().addSequence(dsseq);
252 if (sequences == null)
254 initAlignment(new SequenceI[] { snew });
258 synchronized (sequences)
263 if (hiddenSequences != null)
265 hiddenSequences.adjustHeightSequenceAdded();
270 public SequenceI replaceSequenceAt(int i, SequenceI snew)
272 synchronized (sequences)
274 if (sequences.size() > i)
276 return sequences.set(i, snew);
282 hiddenSequences.adjustHeightSequenceAdded();
291 * @return DOCUMENT ME!
294 public List<SequenceGroup> getGroups()
300 public void finalize() throws Throwable
302 if (getDataset() != null)
304 getDataset().removeAlignmentRef();
312 * Defensively nulls out references in case this object is not garbage
315 void nullReferences()
321 hiddenSequences = null;
325 * decrement the alignmentRefs counter by one and null references if it goes
330 private void removeAlignmentRef() throws Throwable
332 if (--alignmentRefs == 0)
345 public void deleteSequence(SequenceI s)
347 deleteSequence(findIndex(s));
357 public void deleteSequence(int i)
359 if (i > -1 && i < getHeight())
361 synchronized (sequences)
364 hiddenSequences.adjustHeightSequenceDeleted(i);
372 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
375 public SequenceGroup findGroup(SequenceI seq, int position)
377 synchronized (groups)
379 for (SequenceGroup sg : groups)
381 if (sg.getSequences(null).contains(seq))
383 if (position >= sg.getStartRes() && position <= sg.getEndRes())
397 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
400 public SequenceGroup[] findAllGroups(SequenceI s)
402 ArrayList<SequenceGroup> temp = new ArrayList<SequenceGroup>();
404 synchronized (groups)
406 int gSize = groups.size();
407 for (int i = 0; i < gSize; i++)
409 SequenceGroup sg = groups.get(i);
410 if (sg == null || sg.getSequences() == null)
412 this.deleteGroup(sg);
417 if (sg.getSequences().contains(s))
423 SequenceGroup[] ret = new SequenceGroup[temp.size()];
424 return temp.toArray(ret);
429 public void addGroup(SequenceGroup sg)
431 synchronized (groups)
433 if (!groups.contains(sg))
435 if (hiddenSequences.getSize() > 0)
437 int i, iSize = sg.getSize();
438 for (i = 0; i < iSize; i++)
440 if (!sequences.contains(sg.getSequenceAt(i)))
442 sg.deleteSequence(sg.getSequenceAt(i), false);
448 if (sg.getSize() < 1)
460 * remove any annotation that references gp
463 * (if null, removes all group associated annotation)
465 private void removeAnnotationForGroup(SequenceGroup gp)
467 if (annotations == null || annotations.length == 0)
471 // remove annotation very quickly
472 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
476 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
478 if (annotations[i].groupRef != null)
480 todelete[p++] = annotations[i];
484 tokeep[k++] = annotations[i];
490 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
492 if (annotations[i].groupRef == gp)
494 todelete[p++] = annotations[i];
498 tokeep[k++] = annotations[i];
504 // clear out the group associated annotation.
505 for (i = 0; i < p; i++)
507 unhookAnnotation(todelete[i]);
510 t = new AlignmentAnnotation[k];
511 for (i = 0; i < k; i++)
520 public void deleteAllGroups()
522 synchronized (groups)
524 if (annotations != null)
526 removeAnnotationForGroup(null);
528 for (SequenceGroup sg : groups)
538 public void deleteGroup(SequenceGroup g)
540 synchronized (groups)
542 if (groups.contains(g))
544 removeAnnotationForGroup(g);
553 public SequenceI findName(String name)
555 return findName(name, false);
561 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
564 public SequenceI findName(String token, boolean b)
566 return findName(null, token, b);
572 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
576 public SequenceI findName(SequenceI startAfter, String token, boolean b)
581 String sqname = null;
582 if (startAfter != null)
584 // try to find the sequence in the alignment
585 boolean matched = false;
586 while (i < sequences.size())
588 if (getSequenceAt(i++) == startAfter)
599 while (i < sequences.size())
601 sq = getSequenceAt(i);
602 sqname = sq.getName();
603 if (sqname.equals(token) // exact match
604 || (b && // allow imperfect matches - case varies
605 (sqname.equalsIgnoreCase(token))))
607 return getSequenceAt(i);
617 public SequenceI[] findSequenceMatch(String name)
619 Vector matches = new Vector();
622 while (i < sequences.size())
624 if (getSequenceAt(i).getName().equals(name))
626 matches.addElement(getSequenceAt(i));
631 SequenceI[] result = new SequenceI[matches.size()];
632 for (i = 0; i < result.length; i++)
634 result[i] = (SequenceI) matches.elementAt(i);
644 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
647 public int findIndex(SequenceI s)
651 while (i < sequences.size())
653 if (s == getSequenceAt(i))
668 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
671 public int findIndex(SearchResultsI results)
675 while (i < sequences.size())
677 if (results.involvesSequence(getSequenceAt(i)))
688 public int getHeight()
690 return sequences.size();
694 public int getAbsoluteHeight()
696 return sequences.size() + getHiddenSequences().getSize();
700 public int getWidth()
704 for (int i = 0; i < sequences.size(); i++)
706 if (getSequenceAt(i).getLength() > maxLength)
708 maxLength = getSequenceAt(i).getLength();
722 public void setGapCharacter(char gc)
725 synchronized (sequences)
727 for (SequenceI seq : sequences)
729 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
730 .replace('-', gc).replace(' ', gc));
738 * @return DOCUMENT ME!
741 public char getGapCharacter()
749 * @see jalview.datamodel.AlignmentI#isAligned()
752 public boolean isAligned()
754 return isAligned(false);
760 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
763 public boolean isAligned(boolean includeHidden)
765 int width = getWidth();
766 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
768 includeHidden = true; // no hidden sequences to check against.
770 for (int i = 0; i < sequences.size(); i++)
772 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
774 if (getSequenceAt(i).getLength() != width)
785 public boolean isHidden(int alignmentIndex)
787 return (getHiddenSequences().getHiddenSequence(alignmentIndex) == null);
791 * Delete all annotations, including auto-calculated if the flag is set true.
792 * Returns true if at least one annotation was deleted, else false.
794 * @param includingAutoCalculated
798 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
800 boolean result = false;
801 for (AlignmentAnnotation alan : getAlignmentAnnotation())
803 if (!alan.autoCalculated || includingAutoCalculated)
805 deleteAnnotation(alan);
815 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
816 * AlignmentAnnotation)
819 public boolean deleteAnnotation(AlignmentAnnotation aa)
821 return deleteAnnotation(aa, true);
825 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
829 if (annotations != null)
831 aSize = annotations.length;
839 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
841 boolean swap = false;
844 for (int i = 0; i < aSize; i++)
846 if (annotations[i] == aa)
851 if (tIndex < temp.length)
853 temp[tIndex++] = annotations[i];
862 unhookAnnotation(aa);
869 * remove any object references associated with this annotation
873 private void unhookAnnotation(AlignmentAnnotation aa)
875 if (aa.sequenceRef != null)
877 aa.sequenceRef.removeAlignmentAnnotation(aa);
879 if (aa.groupRef != null)
881 // probably need to do more here in the future (post 2.5.0)
889 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
890 * AlignmentAnnotation)
893 public void addAnnotation(AlignmentAnnotation aa)
895 addAnnotation(aa, -1);
901 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
902 * AlignmentAnnotation, int)
905 public void addAnnotation(AlignmentAnnotation aa, int pos)
907 if (aa.getRNAStruc() != null)
909 hasRNAStructure = true;
913 if (annotations != null)
915 aSize = annotations.length + 1;
918 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
920 if (pos == -1 || pos >= aSize)
922 temp[aSize - 1] = aa;
931 for (i = 0; i < (aSize - 1); i++, p++)
939 temp[p] = annotations[i];
948 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
950 if (aa == null || annotations == null || annotations.length - 1 < index)
955 int aSize = annotations.length;
956 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
960 for (int i = 0; i < aSize; i++)
969 temp[i] = annotations[i];
973 temp[i] = annotations[i - 1];
982 * returns all annotation on the alignment
984 public AlignmentAnnotation[] getAlignmentAnnotation()
990 public boolean isNucleotide()
996 public boolean hasRNAStructure()
998 // TODO can it happen that structure is removed from alignment?
999 return hasRNAStructure;
1003 public void setDataset(AlignmentI data)
1005 if (dataset == null && data == null)
1007 createDatasetAlignment();
1009 else if (dataset == null && data != null)
1011 if (!(data instanceof Alignment))
1014 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1016 dataset = (Alignment) data;
1017 for (int i = 0; i < getHeight(); i++)
1019 SequenceI currentSeq = getSequenceAt(i);
1020 SequenceI dsq = currentSeq.getDatasetSequence();
1023 dsq = currentSeq.createDatasetSequence();
1024 dataset.addSequence(dsq);
1028 while (dsq.getDatasetSequence() != null)
1030 dsq = dsq.getDatasetSequence();
1032 if (dataset.findIndex(dsq) == -1)
1034 dataset.addSequence(dsq);
1039 dataset.addAlignmentRef();
1043 * add dataset sequences to seq for currentSeq and any sequences it references
1045 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1046 Set<SequenceI> seqs, boolean createDatasetSequence)
1048 SequenceI alignedSeq = currentSeq;
1049 if (currentSeq.getDatasetSequence() != null)
1051 currentSeq = currentSeq.getDatasetSequence();
1055 if (createDatasetSequence)
1057 currentSeq = currentSeq.createDatasetSequence();
1060 if (seqs.contains(currentSeq))
1064 List<SequenceI> toProcess = new ArrayList<SequenceI>();
1065 toProcess.add(currentSeq);
1066 while (toProcess.size() > 0)
1069 SequenceI curDs = toProcess.remove(0);
1070 if (seqs.contains(curDs))
1075 // iterate over database references, making sure we add forward referenced
1077 if (curDs.getDBRefs() != null)
1079 for (DBRefEntry dbr : curDs.getDBRefs())
1081 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1083 if (dbr.getMap().getTo() == alignedSeq)
1086 * update mapping to be to the newly created dataset sequence
1088 dbr.getMap().setTo(currentSeq);
1090 if (dbr.getMap().getTo().getDatasetSequence() != null)
1093 "Implementation error: Map.getTo() for dbref " + dbr
1094 + " from " + curDs.getName()
1095 + " is not a dataset sequence.");
1097 // we recurse to add all forward references to dataset sequences via
1099 toProcess.add(dbr.getMap().getTo());
1107 * Creates a new dataset for this alignment. Can only be done once - if
1108 * dataset is not null this will not be performed.
1110 public void createDatasetAlignment()
1112 if (dataset != null)
1116 // try to avoid using SequenceI.equals at this stage, it will be expensive
1117 Set<SequenceI> seqs = new LinkedIdentityHashSet<SequenceI>();
1119 for (int i = 0; i < getHeight(); i++)
1121 SequenceI currentSeq = getSequenceAt(i);
1122 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1125 // verify all mappings are in dataset
1126 for (AlignedCodonFrame cf : codonFrameList)
1128 for (SequenceToSequenceMapping ssm : cf.getMappings())
1130 if (!seqs.contains(ssm.getFromSeq()))
1132 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1134 if (!seqs.contains(ssm.getMapping().getTo()))
1136 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1140 // finally construct dataset
1141 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1142 // move mappings to the dataset alignment
1143 dataset.codonFrameList = this.codonFrameList;
1144 this.codonFrameList = null;
1148 * reference count for number of alignments referencing this one.
1150 int alignmentRefs = 0;
1153 * increase reference count to this alignment.
1155 private void addAlignmentRef()
1161 public Alignment getDataset()
1167 public boolean padGaps()
1169 boolean modified = false;
1171 // Remove excess gaps from the end of alignment
1175 for (int i = 0; i < sequences.size(); i++)
1177 current = getSequenceAt(i);
1178 for (int j = current.getLength(); j > maxLength; j--)
1181 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1192 for (int i = 0; i < sequences.size(); i++)
1194 current = getSequenceAt(i);
1195 cLength = current.getLength();
1197 if (cLength < maxLength)
1199 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1202 else if (current.getLength() > maxLength)
1204 current.deleteChars(maxLength, current.getLength());
1211 * Justify the sequences to the left or right by deleting and inserting gaps
1212 * before the initial residue or after the terminal residue
1215 * true if alignment padded to right, false to justify to left
1216 * @return true if alignment was changed
1219 public boolean justify(boolean right)
1221 boolean modified = false;
1223 // Remove excess gaps from the end of alignment
1225 int ends[] = new int[sequences.size() * 2];
1227 for (int i = 0; i < sequences.size(); i++)
1229 current = getSequenceAt(i);
1230 // This should really be a sequence method
1231 ends[i * 2] = current.findIndex(current.getStart());
1232 ends[i * 2 + 1] = current.findIndex(current.getStart()
1233 + current.getLength());
1234 boolean hitres = false;
1235 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1237 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1246 ends[i * 2 + 1] = j;
1247 if (j - ends[i * 2] > maxLength)
1249 maxLength = j - ends[i * 2];
1257 // now edit the flanking gaps to justify to either left or right
1258 int cLength, extent, diff;
1259 for (int i = 0; i < sequences.size(); i++)
1261 current = getSequenceAt(i);
1263 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1264 diff = maxLength - cLength; // number of gaps to indent
1265 extent = current.getLength();
1269 if (extent > ends[i * 2 + 1])
1271 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1274 if (ends[i * 2] > diff)
1276 current.deleteChars(0, ends[i * 2] - diff);
1281 if (ends[i * 2] < diff)
1283 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1291 if (ends[i * 2] > 0)
1293 current.deleteChars(0, ends[i * 2]);
1295 ends[i * 2 + 1] -= ends[i * 2];
1296 extent -= ends[i * 2];
1298 if (extent > maxLength)
1300 current.deleteChars(maxLength + 1, extent);
1305 if (extent < maxLength)
1307 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1317 public HiddenSequences getHiddenSequences()
1319 return hiddenSequences;
1323 public CigarArray getCompactAlignment()
1325 synchronized (sequences)
1327 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1329 for (SequenceI seq : sequences)
1331 alseqs[i++] = new SeqCigar(seq);
1333 CigarArray cal = new CigarArray(alseqs);
1334 cal.addOperation(CigarArray.M, getWidth());
1340 public void setProperty(Object key, Object value)
1342 if (alignmentProperties == null)
1344 alignmentProperties = new Hashtable();
1347 alignmentProperties.put(key, value);
1351 public Object getProperty(Object key)
1353 if (alignmentProperties != null)
1355 return alignmentProperties.get(key);
1364 public Hashtable getProperties()
1366 return alignmentProperties;
1370 * Adds the given mapping to the stored set. Note this may be held on the
1371 * dataset alignment.
1374 public void addCodonFrame(AlignedCodonFrame codons)
1376 List<AlignedCodonFrame> acfs = getCodonFrames();
1377 if (codons != null && acfs != null && !acfs.contains(codons))
1387 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1390 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1396 List<AlignedCodonFrame> cframes = new ArrayList<AlignedCodonFrame>();
1397 for (AlignedCodonFrame acf : getCodonFrames())
1399 if (acf.involvesSequence(seq))
1408 * Sets the codon frame mappings (replacing any existing mappings). Note the
1409 * mappings are set on the dataset alignment instead if there is one.
1411 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1414 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1416 if (dataset != null)
1418 dataset.setCodonFrames(acfs);
1422 this.codonFrameList = acfs;
1427 * Returns the set of codon frame mappings. Any changes to the returned set
1428 * will affect the alignment. The mappings are held on (and read from) the
1429 * dataset alignment if there is one.
1431 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1434 public List<AlignedCodonFrame> getCodonFrames()
1436 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1437 // this behaviour is currently incorrect. method should return codon frames
1438 // for just the alignment,
1439 // selected from dataset
1440 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1444 * Removes the given mapping from the stored set. Note that the mappings are
1445 * held on the dataset alignment if there is one.
1448 public boolean removeCodonFrame(AlignedCodonFrame codons)
1450 List<AlignedCodonFrame> acfs = getCodonFrames();
1451 if (codons == null || acfs == null)
1455 return acfs.remove(codons);
1459 public void append(AlignmentI toappend)
1461 // TODO JAL-1270 needs test coverage
1462 // currently tested for use in jalview.gui.SequenceFetcher
1463 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1464 char oldc = toappend.getGapCharacter();
1465 boolean hashidden = toappend.getHiddenSequences() != null
1466 && toappend.getHiddenSequences().hiddenSequences != null;
1467 // get all sequences including any hidden ones
1468 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1469 .getFullAlignment().getSequences() : toappend.getSequences();
1472 // avoid self append deadlock by
1473 List<SequenceI> toappendsq = new ArrayList<SequenceI>();
1476 for (SequenceI addedsq : sqs)
1480 char[] oldseq = addedsq.getSequence();
1481 for (int c = 0; c < oldseq.length; c++)
1483 if (oldseq[c] == oldc)
1485 oldseq[c] = gapCharacter;
1489 toappendsq.add(addedsq);
1492 for (SequenceI addedsq : toappendsq)
1494 addSequence(addedsq);
1497 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1498 for (int a = 0; alan != null && a < alan.length; a++)
1500 addAnnotation(alan[a]);
1504 getCodonFrames().addAll(toappend.getCodonFrames());
1506 List<SequenceGroup> sg = toappend.getGroups();
1509 for (SequenceGroup _sg : sg)
1514 if (toappend.getHiddenSequences() != null)
1516 HiddenSequences hs = toappend.getHiddenSequences();
1517 if (hiddenSequences == null)
1519 hiddenSequences = new HiddenSequences(this);
1521 if (hs.hiddenSequences != null)
1523 for (int s = 0; s < hs.hiddenSequences.length; s++)
1525 // hide the newly appended sequence in the alignment
1526 if (hs.hiddenSequences[s] != null)
1528 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1533 if (toappend.getProperties() != null)
1535 // we really can't do very much here - just try to concatenate strings
1536 // where property collisions occur.
1537 Enumeration key = toappend.getProperties().keys();
1538 while (key.hasMoreElements())
1540 Object k = key.nextElement();
1541 Object ourval = this.getProperty(k);
1542 Object toapprop = toappend.getProperty(k);
1545 if (ourval.getClass().equals(toapprop.getClass())
1546 && !ourval.equals(toapprop))
1548 if (ourval instanceof String)
1551 this.setProperty(k, ((String) ourval) + "; "
1552 + ((String) toapprop));
1556 if (ourval instanceof Vector)
1559 Enumeration theirv = ((Vector) toapprop).elements();
1560 while (theirv.hasMoreElements())
1562 ((Vector) ourval).addElement(theirv);
1570 // just add new property directly
1571 setProperty(k, toapprop);
1579 public AlignmentAnnotation findOrCreateAnnotation(String name,
1580 String calcId, boolean autoCalc, SequenceI seqRef,
1581 SequenceGroup groupRef)
1583 if (annotations != null)
1585 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1587 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1588 && (calcId == null || annot.getCalcId().equals(calcId))
1589 && annot.sequenceRef == seqRef
1590 && annot.groupRef == groupRef)
1596 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1597 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1598 annot.hasText = false;
1599 annot.setCalcId(new String(calcId));
1600 annot.autoCalculated = autoCalc;
1603 annot.setSequenceRef(seqRef);
1605 annot.groupRef = groupRef;
1606 addAnnotation(annot);
1612 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1614 List<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1615 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1616 if (alignmentAnnotation != null)
1618 for (AlignmentAnnotation a : alignmentAnnotation)
1620 if (a.getCalcId() == calcId
1621 || (a.getCalcId() != null && calcId != null && a
1622 .getCalcId().equals(calcId)))
1632 * Returns an iterable collection of any annotations that match on given
1633 * sequence ref, calcId and label (ignoring null values).
1636 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1637 String calcId, String label)
1639 ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1640 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1642 if (ann.getCalcId() != null && ann.getCalcId().equals(calcId)
1643 && ann.sequenceRef != null && ann.sequenceRef == seq
1644 && ann.label != null && ann.label.equals(label))
1653 public void moveSelectedSequencesByOne(SequenceGroup sg,
1654 Map<SequenceI, SequenceCollectionI> map, boolean up)
1656 synchronized (sequences)
1661 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1663 SequenceI seq = sequences.get(i);
1664 if (!sg.getSequences(map).contains(seq))
1669 SequenceI temp = sequences.get(i - 1);
1670 if (sg.getSequences(null).contains(temp))
1675 sequences.set(i, temp);
1676 sequences.set(i - 1, seq);
1681 for (int i = sequences.size() - 2; i > -1; i--)
1683 SequenceI seq = sequences.get(i);
1684 if (!sg.getSequences(map).contains(seq))
1689 SequenceI temp = sequences.get(i + 1);
1690 if (sg.getSequences(map).contains(temp))
1695 sequences.set(i, temp);
1696 sequences.set(i + 1, seq);
1704 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1706 alignmentAnnotation.validateRangeAndDisplay();
1707 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1709 hasRNAStructure = true;
1713 private SequenceI seqrep = null;
1717 * @return the representative sequence for this group
1720 public SequenceI getSeqrep()
1726 * set the representative sequence for this group. Note - this affects the
1727 * interpretation of the Hidereps attribute.
1730 * the seqrep to set (null means no sequence representative)
1733 public void setSeqrep(SequenceI seqrep)
1735 this.seqrep = seqrep;
1740 * @return true if group has a sequence representative
1743 public boolean hasSeqrep()
1745 return seqrep != null;
1749 public int getEndRes()
1751 return getWidth() - 1;
1755 public int getStartRes()
1761 * In the case of AlignmentI - returns the dataset for the alignment, if set
1764 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1767 public AnnotatedCollectionI getContext()
1773 * Align this alignment like the given (mapped) one.
1776 public int alignAs(AlignmentI al)
1779 * Currently retains unmapped gaps (in introns), regaps mapped regions
1782 return alignAs(al, false, true);
1786 * Align this alignment 'the same as' the given one. Mapped sequences only are
1787 * realigned. If both of the same type (nucleotide/protein) then align both
1788 * identically. If this is nucleotide and the other is protein, make 3 gaps
1789 * for each gap in the protein sequences. If this is protein and the other is
1790 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1791 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1792 * protein to match the relative ordering of codons in the nucleotide.
1794 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1795 * regions are preserved. Gaps that connect introns to exons are treated
1796 * conservatively, i.e. only preserved if both intron and exon gaps are
1797 * preserved. TODO: check caveats below where the implementation fails
1800 * - must have same dataset, and sequences in al must have equivalent
1801 * dataset sequence and start/end bounds under given mapping
1802 * @param preserveMappedGaps
1803 * if true, gaps within and between mapped codons are preserved
1804 * @param preserveUnmappedGaps
1805 * if true, gaps within and between unmapped codons are preserved
1808 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1809 boolean preserveUnmappedGaps)
1811 // TODO should this method signature be the one in the interface?
1812 // JBPComment - yes - neither flag is used, so should be deleted.
1813 boolean thisIsNucleotide = this.isNucleotide();
1814 boolean thatIsProtein = !al.isNucleotide();
1815 if (!thatIsProtein && !thisIsNucleotide)
1817 return AlignmentUtils.alignProteinAsDna(this, al);
1819 else if (thatIsProtein && thisIsNucleotide)
1821 return AlignmentUtils.alignCdsAsProtein(this, al);
1823 return AlignmentUtils.alignAs(this, al);
1827 * Returns the alignment in Fasta format. Behaviour of this method is not
1828 * guaranteed between versions.
1831 public String toString()
1833 return new FastaFile().print(getSequencesArray(), true);
1837 * Returns the set of distinct sequence names. No ordering is guaranteed.
1840 public Set<String> getSequenceNames()
1842 Set<String> names = new HashSet<String>();
1843 for (SequenceI seq : getSequences())
1845 names.add(seq.getName());
1851 public boolean hasValidSequence()
1853 boolean hasValidSeq = false;
1854 for (SequenceI seq : getSequences())
1856 if ((seq.getEnd() - seq.getStart()) > 0)
1866 * Update any mappings to 'virtual' sequences to compatible real ones, if
1867 * present in the added sequences. Returns a count of mappings updated.
1873 public int realiseMappings(List<SequenceI> seqs)
1876 for (SequenceI seq : seqs)
1878 for (AlignedCodonFrame mapping : getCodonFrames())
1880 count += mapping.realiseWith(seq);
1887 * Returns the first AlignedCodonFrame that has a mapping between the given
1895 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1897 for (AlignedCodonFrame acf : getCodonFrames())
1899 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1908 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1910 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1911 int startPos = alignmentStartEnd[0];
1912 int endPos = alignmentStartEnd[1];
1914 int[] lowestRange = new int[] { -1, -1 };
1915 int[] higestRange = new int[] { -1, -1 };
1917 for (int[] hiddenCol : hiddenCols)
1919 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1920 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1923 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1925 startPos = alignmentStartEnd[0];
1929 startPos = lowestRange[1] + 1;
1932 if (higestRange[0] == -1 && higestRange[1] == -1)
1934 endPos = alignmentStartEnd[1];
1938 endPos = higestRange[0] - 1;
1940 return new int[] { startPos, endPos };