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.HashMap;
34 import java.util.HashSet;
35 import java.util.Hashtable;
36 import java.util.List;
39 import java.util.Vector;
42 * Data structure to hold and manipulate a multiple sequence alignment
48 public class Alignment implements AlignmentI
50 private Alignment dataset;
52 protected List<SequenceI> sequences;
54 protected List<SequenceGroup> groups;
56 protected char gapCharacter = '-';
58 private boolean nucleotide = true;
60 public boolean hasRNAStructure = false;
62 public AlignmentAnnotation[] annotations;
64 HiddenSequences hiddenSequences;
66 public Hashtable alignmentProperties;
68 private List<AlignedCodonFrame> codonFrameList;
70 private void initAlignment(SequenceI[] seqs)
72 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
73 hiddenSequences = new HiddenSequences(this);
74 codonFrameList = new ArrayList<AlignedCodonFrame>();
76 nucleotide = Comparison.isNucleotide(seqs);
78 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
80 for (int i = 0; i < seqs.length; i++)
82 sequences.add(seqs[i]);
88 * Make a 'copy' alignment - sequences have new copies of features and
89 * annotations, but share the original dataset sequences.
91 public Alignment(AlignmentI al)
93 SequenceI[] seqs = al.getSequencesArray();
94 for (int i = 0; i < seqs.length; i++)
96 seqs[i] = new Sequence(seqs[i]);
102 * Share the same dataset sequence mappings (if any).
104 if (dataset == null && al.getDataset() == null)
106 this.setCodonFrames(al.getCodonFrames());
111 * Make an alignment from an array of Sequences.
115 public Alignment(SequenceI[] seqs)
121 * Make a new alignment from an array of SeqCigars
126 public Alignment(SeqCigar[] alseqs)
128 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
129 gapCharacter, new ColumnSelection(), null);
134 * Make a new alignment from an CigarArray JBPNote - can only do this when
135 * compactAlignment does not contain hidden regions. JBPNote - must also check
136 * that compactAlignment resolves to a set of SeqCigars - or construct them
139 * @param compactAlignment
142 public static AlignmentI createAlignment(CigarArray compactAlignment)
146 .getString("error.alignment_cigararray_not_implemented"));
147 // this(compactAlignment.refCigars);
151 public List<SequenceI> getSequences()
157 public List<SequenceI> getSequences(
158 Map<SequenceI, SequenceCollectionI> hiddenReps)
160 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
166 public SequenceI[] getSequencesArray()
168 if (sequences == null)
172 synchronized (sequences)
174 return sequences.toArray(new SequenceI[sequences.size()]);
179 * Returns a map of lists of sequences keyed by sequence name.
184 public Map<String, List<SequenceI>> getSequencesByName()
186 return AlignmentUtils.getSequencesByName(this);
195 * @return DOCUMENT ME!
198 public SequenceI getSequenceAt(int i)
200 synchronized (sequences)
202 if (i > -1 && i < sequences.size())
204 return sequences.get(i);
211 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
212 * this currently does not recalculate whether or not the alignment is
213 * nucleotide, so mixed alignments may have undefined behaviour.
218 public void addSequence(SequenceI snew)
223 // maintain dataset integrity
224 SequenceI dsseq = snew.getDatasetSequence();
227 // derive new sequence
228 SequenceI adding = snew.deriveSequence();
230 dsseq = snew.getDatasetSequence();
232 if (getDataset().findIndex(dsseq) == -1)
234 getDataset().addSequence(dsseq);
238 if (sequences == null)
240 initAlignment(new SequenceI[] { snew });
244 synchronized (sequences)
249 if (hiddenSequences != null)
251 hiddenSequences.adjustHeightSequenceAdded();
256 public SequenceI replaceSequenceAt(int i, SequenceI snew)
258 synchronized (sequences)
260 if (sequences.size() > i)
262 return sequences.set(i, snew);
268 hiddenSequences.adjustHeightSequenceAdded();
277 * @return DOCUMENT ME!
280 public List<SequenceGroup> getGroups()
286 public void finalize() throws Throwable
288 if (getDataset() != null)
290 getDataset().removeAlignmentRef();
298 * Defensively nulls out references in case this object is not garbage
301 void nullReferences()
307 hiddenSequences = null;
311 * decrement the alignmentRefs counter by one and null references if it goes
316 private void removeAlignmentRef() throws Throwable
318 if (--alignmentRefs == 0)
331 public void deleteSequence(SequenceI s)
333 deleteSequence(findIndex(s));
343 public void deleteSequence(int i)
345 if (i > -1 && i < getHeight())
347 synchronized (sequences)
350 hiddenSequences.adjustHeightSequenceDeleted(i);
358 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
361 public SequenceGroup findGroup(SequenceI seq, int position)
363 synchronized (groups)
365 for (SequenceGroup sg : groups)
367 if (sg.getSequences(null).contains(seq))
369 if (position >= sg.getStartRes() && position <= sg.getEndRes())
383 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
386 public SequenceGroup[] findAllGroups(SequenceI s)
388 ArrayList<SequenceGroup> temp = new ArrayList<SequenceGroup>();
390 synchronized (groups)
392 int gSize = groups.size();
393 for (int i = 0; i < gSize; i++)
395 SequenceGroup sg = groups.get(i);
396 if (sg == null || sg.getSequences() == null)
398 this.deleteGroup(sg);
403 if (sg.getSequences().contains(s))
409 SequenceGroup[] ret = new SequenceGroup[temp.size()];
410 return temp.toArray(ret);
415 public void addGroup(SequenceGroup sg)
417 synchronized (groups)
419 if (!groups.contains(sg))
421 if (hiddenSequences.getSize() > 0)
423 int i, iSize = sg.getSize();
424 for (i = 0; i < iSize; i++)
426 if (!sequences.contains(sg.getSequenceAt(i)))
428 sg.deleteSequence(sg.getSequenceAt(i), false);
434 if (sg.getSize() < 1)
446 * remove any annotation that references gp
449 * (if null, removes all group associated annotation)
451 private void removeAnnotationForGroup(SequenceGroup gp)
453 if (annotations == null || annotations.length == 0)
457 // remove annotation very quickly
458 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
462 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
464 if (annotations[i].groupRef != null)
466 todelete[p++] = annotations[i];
470 tokeep[k++] = annotations[i];
476 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
478 if (annotations[i].groupRef == gp)
480 todelete[p++] = annotations[i];
484 tokeep[k++] = annotations[i];
490 // clear out the group associated annotation.
491 for (i = 0; i < p; i++)
493 unhookAnnotation(todelete[i]);
496 t = new AlignmentAnnotation[k];
497 for (i = 0; i < k; i++)
506 public void deleteAllGroups()
508 synchronized (groups)
510 if (annotations != null)
512 removeAnnotationForGroup(null);
514 for (SequenceGroup sg : groups)
524 public void deleteGroup(SequenceGroup g)
526 synchronized (groups)
528 if (groups.contains(g))
530 removeAnnotationForGroup(g);
539 public SequenceI findName(String name)
541 return findName(name, false);
547 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
550 public SequenceI findName(String token, boolean b)
552 return findName(null, token, b);
558 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
562 public SequenceI findName(SequenceI startAfter, String token, boolean b)
567 String sqname = null;
568 if (startAfter != null)
570 // try to find the sequence in the alignment
571 boolean matched = false;
572 while (i < sequences.size())
574 if (getSequenceAt(i++) == startAfter)
585 while (i < sequences.size())
587 sq = getSequenceAt(i);
588 sqname = sq.getName();
589 if (sqname.equals(token) // exact match
590 || (b && // allow imperfect matches - case varies
591 (sqname.equalsIgnoreCase(token))))
593 return getSequenceAt(i);
603 public SequenceI[] findSequenceMatch(String name)
605 Vector matches = new Vector();
608 while (i < sequences.size())
610 if (getSequenceAt(i).getName().equals(name))
612 matches.addElement(getSequenceAt(i));
617 SequenceI[] result = new SequenceI[matches.size()];
618 for (i = 0; i < result.length; i++)
620 result[i] = (SequenceI) matches.elementAt(i);
630 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
633 public int findIndex(SequenceI s)
637 while (i < sequences.size())
639 if (s == getSequenceAt(i))
654 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
657 public int findIndex(SearchResultsI results)
661 while (i < sequences.size())
663 if (results.involvesSequence(getSequenceAt(i)))
675 * @return DOCUMENT ME!
678 public int getHeight()
680 return sequences.size();
686 * @return DOCUMENT ME!
689 public int getWidth()
693 for (int i = 0; i < sequences.size(); i++)
695 if (getSequenceAt(i).getLength() > maxLength)
697 maxLength = getSequenceAt(i).getLength();
711 public void setGapCharacter(char gc)
714 synchronized (sequences)
716 for (SequenceI seq : sequences)
718 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
719 .replace('-', gc).replace(' ', gc));
727 * @return DOCUMENT ME!
730 public char getGapCharacter()
738 * @see jalview.datamodel.AlignmentI#isAligned()
741 public boolean isAligned()
743 return isAligned(false);
749 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
752 public boolean isAligned(boolean includeHidden)
754 int width = getWidth();
755 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
757 includeHidden = true; // no hidden sequences to check against.
759 for (int i = 0; i < sequences.size(); i++)
761 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
763 if (getSequenceAt(i).getLength() != width)
774 * Delete all annotations, including auto-calculated if the flag is set true.
775 * Returns true if at least one annotation was deleted, else false.
777 * @param includingAutoCalculated
781 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
783 boolean result = false;
784 for (AlignmentAnnotation alan : getAlignmentAnnotation())
786 if (!alan.autoCalculated || includingAutoCalculated)
788 deleteAnnotation(alan);
798 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
799 * AlignmentAnnotation)
802 public boolean deleteAnnotation(AlignmentAnnotation aa)
804 return deleteAnnotation(aa, true);
808 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
812 if (annotations != null)
814 aSize = annotations.length;
822 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
824 boolean swap = false;
827 for (int i = 0; i < aSize; i++)
829 if (annotations[i] == aa)
834 if (tIndex < temp.length)
836 temp[tIndex++] = annotations[i];
845 unhookAnnotation(aa);
852 * remove any object references associated with this annotation
856 private void unhookAnnotation(AlignmentAnnotation aa)
858 if (aa.sequenceRef != null)
860 aa.sequenceRef.removeAlignmentAnnotation(aa);
862 if (aa.groupRef != null)
864 // probably need to do more here in the future (post 2.5.0)
872 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
873 * AlignmentAnnotation)
876 public void addAnnotation(AlignmentAnnotation aa)
878 addAnnotation(aa, -1);
884 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
885 * AlignmentAnnotation, int)
888 public void addAnnotation(AlignmentAnnotation aa, int pos)
890 if (aa.getRNAStruc() != null)
892 hasRNAStructure = true;
896 if (annotations != null)
898 aSize = annotations.length + 1;
901 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
903 if (pos == -1 || pos >= aSize)
905 temp[aSize - 1] = aa;
914 for (i = 0; i < (aSize - 1); i++, p++)
922 temp[p] = annotations[i];
931 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
933 if (aa == null || annotations == null || annotations.length - 1 < index)
938 int aSize = annotations.length;
939 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
943 for (int i = 0; i < aSize; i++)
952 temp[i] = annotations[i];
956 temp[i] = annotations[i - 1];
965 * returns all annotation on the alignment
967 public AlignmentAnnotation[] getAlignmentAnnotation()
973 public boolean isNucleotide()
979 public boolean hasRNAStructure()
981 // TODO can it happen that structure is removed from alignment?
982 return hasRNAStructure;
986 public void setDataset(AlignmentI data)
988 if (dataset == null && data == null)
990 createDatasetAlignment();
992 else if (dataset == null && data != null)
994 if (!(data instanceof Alignment))
997 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
999 dataset = (Alignment) data;
1000 for (int i = 0; i < getHeight(); i++)
1002 SequenceI currentSeq = getSequenceAt(i);
1003 SequenceI dsq = currentSeq.getDatasetSequence();
1006 dsq = currentSeq.createDatasetSequence();
1007 dataset.addSequence(dsq);
1011 while (dsq.getDatasetSequence() != null)
1013 dsq = dsq.getDatasetSequence();
1015 if (dataset.findIndex(dsq) == -1)
1017 dataset.addSequence(dsq);
1022 dataset.addAlignmentRef();
1026 * add dataset sequences to seq for currentSeq and any sequences it references
1028 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1029 Set<SequenceI> seqs, boolean createDatasetSequence)
1031 SequenceI alignedSeq = currentSeq;
1032 if (currentSeq.getDatasetSequence() != null)
1034 currentSeq = currentSeq.getDatasetSequence();
1038 if (createDatasetSequence)
1040 currentSeq = currentSeq.createDatasetSequence();
1043 if (seqs.contains(currentSeq))
1047 List<SequenceI> toProcess = new ArrayList<SequenceI>();
1048 toProcess.add(currentSeq);
1049 while (toProcess.size() > 0)
1052 SequenceI curDs = toProcess.remove(0);
1053 if (seqs.contains(curDs))
1058 // iterate over database references, making sure we add forward referenced
1060 if (curDs.getDBRefs() != null)
1062 for (DBRefEntry dbr : curDs.getDBRefs())
1064 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1066 if (dbr.getMap().getTo() == alignedSeq)
1069 * update mapping to be to the newly created dataset sequence
1071 dbr.getMap().setTo(currentSeq);
1073 if (dbr.getMap().getTo().getDatasetSequence() != null)
1076 "Implementation error: Map.getTo() for dbref " + dbr
1077 + " from " + curDs.getName()
1078 + " is not a dataset sequence.");
1080 // we recurse to add all forward references to dataset sequences via
1082 toProcess.add(dbr.getMap().getTo());
1090 * Creates a new dataset for this alignment. Can only be done once - if
1091 * dataset is not null this will not be performed.
1093 public void createDatasetAlignment()
1095 if (dataset != null)
1099 // try to avoid using SequenceI.equals at this stage, it will be expensive
1100 Set<SequenceI> seqs = new LinkedIdentityHashSet<SequenceI>();
1102 for (int i = 0; i < getHeight(); i++)
1104 SequenceI currentSeq = getSequenceAt(i);
1105 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1108 // verify all mappings are in dataset
1109 for (AlignedCodonFrame cf : codonFrameList)
1111 for (SequenceToSequenceMapping ssm : cf.getMappings())
1113 if (!seqs.contains(ssm.getFromSeq()))
1115 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1117 if (!seqs.contains(ssm.getMapping().getTo()))
1119 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1123 // finally construct dataset
1124 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1125 // move mappings to the dataset alignment
1126 dataset.codonFrameList = this.codonFrameList;
1127 this.codonFrameList = null;
1131 * reference count for number of alignments referencing this one.
1133 int alignmentRefs = 0;
1136 * increase reference count to this alignment.
1138 private void addAlignmentRef()
1144 public Alignment getDataset()
1150 public boolean padGaps()
1152 boolean modified = false;
1154 // Remove excess gaps from the end of alignment
1158 for (int i = 0; i < sequences.size(); i++)
1160 current = getSequenceAt(i);
1161 for (int j = current.getLength(); j > maxLength; j--)
1164 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1175 for (int i = 0; i < sequences.size(); i++)
1177 current = getSequenceAt(i);
1178 cLength = current.getLength();
1180 if (cLength < maxLength)
1182 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1185 else if (current.getLength() > maxLength)
1187 current.deleteChars(maxLength, current.getLength());
1194 * Justify the sequences to the left or right by deleting and inserting gaps
1195 * before the initial residue or after the terminal residue
1198 * true if alignment padded to right, false to justify to left
1199 * @return true if alignment was changed
1202 public boolean justify(boolean right)
1204 boolean modified = false;
1206 // Remove excess gaps from the end of alignment
1208 int ends[] = new int[sequences.size() * 2];
1210 for (int i = 0; i < sequences.size(); i++)
1212 current = getSequenceAt(i);
1213 // This should really be a sequence method
1214 ends[i * 2] = current.findIndex(current.getStart());
1215 ends[i * 2 + 1] = current.findIndex(current.getStart()
1216 + current.getLength());
1217 boolean hitres = false;
1218 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1220 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1229 ends[i * 2 + 1] = j;
1230 if (j - ends[i * 2] > maxLength)
1232 maxLength = j - ends[i * 2];
1240 // now edit the flanking gaps to justify to either left or right
1241 int cLength, extent, diff;
1242 for (int i = 0; i < sequences.size(); i++)
1244 current = getSequenceAt(i);
1246 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1247 diff = maxLength - cLength; // number of gaps to indent
1248 extent = current.getLength();
1252 if (extent > ends[i * 2 + 1])
1254 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1257 if (ends[i * 2] > diff)
1259 current.deleteChars(0, ends[i * 2] - diff);
1264 if (ends[i * 2] < diff)
1266 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1274 if (ends[i * 2] > 0)
1276 current.deleteChars(0, ends[i * 2]);
1278 ends[i * 2 + 1] -= ends[i * 2];
1279 extent -= ends[i * 2];
1281 if (extent > maxLength)
1283 current.deleteChars(maxLength + 1, extent);
1288 if (extent < maxLength)
1290 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1300 public HiddenSequences getHiddenSequences()
1302 return hiddenSequences;
1306 public CigarArray getCompactAlignment()
1308 synchronized (sequences)
1310 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1312 for (SequenceI seq : sequences)
1314 alseqs[i++] = new SeqCigar(seq);
1316 CigarArray cal = new CigarArray(alseqs);
1317 cal.addOperation(CigarArray.M, getWidth());
1323 public void setProperty(Object key, Object value)
1325 if (alignmentProperties == null)
1327 alignmentProperties = new Hashtable();
1330 alignmentProperties.put(key, value);
1334 public Object getProperty(Object key)
1336 if (alignmentProperties != null)
1338 return alignmentProperties.get(key);
1347 public Hashtable getProperties()
1349 return alignmentProperties;
1353 * Adds the given mapping to the stored set. Note this may be held on the
1354 * dataset alignment.
1357 public void addCodonFrame(AlignedCodonFrame codons)
1359 List<AlignedCodonFrame> acfs = getCodonFrames();
1360 if (codons != null && acfs != null && !acfs.contains(codons))
1370 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1373 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1379 List<AlignedCodonFrame> cframes = new ArrayList<AlignedCodonFrame>();
1380 for (AlignedCodonFrame acf : getCodonFrames())
1382 if (acf.involvesSequence(seq))
1391 * Sets the codon frame mappings (replacing any existing mappings). Note the
1392 * mappings are set on the dataset alignment instead if there is one.
1394 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1397 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1399 if (dataset != null)
1401 dataset.setCodonFrames(acfs);
1405 this.codonFrameList = acfs;
1410 * Returns the set of codon frame mappings. Any changes to the returned set
1411 * will affect the alignment. The mappings are held on (and read from) the
1412 * dataset alignment if there is one.
1414 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1417 public List<AlignedCodonFrame> getCodonFrames()
1419 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1420 // this behaviour is currently incorrect. method should return codon frames
1421 // for just the alignment,
1422 // selected from dataset
1423 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1427 * Removes the given mapping from the stored set. Note that the mappings are
1428 * held on the dataset alignment if there is one.
1431 public boolean removeCodonFrame(AlignedCodonFrame codons)
1433 List<AlignedCodonFrame> acfs = getCodonFrames();
1434 if (codons == null || acfs == null)
1438 return acfs.remove(codons);
1442 public void append(AlignmentI toappend)
1444 // TODO JAL-1270 needs test coverage
1445 // currently tested for use in jalview.gui.SequenceFetcher
1446 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1447 char oldc = toappend.getGapCharacter();
1448 boolean hashidden = toappend.getHiddenSequences() != null
1449 && toappend.getHiddenSequences().hiddenSequences != null;
1450 // get all sequences including any hidden ones
1451 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1452 .getFullAlignment().getSequences() : toappend.getSequences();
1455 // avoid self append deadlock by
1456 List<SequenceI> toappendsq = new ArrayList<SequenceI>();
1459 for (SequenceI addedsq : sqs)
1463 char[] oldseq = addedsq.getSequence();
1464 for (int c = 0; c < oldseq.length; c++)
1466 if (oldseq[c] == oldc)
1468 oldseq[c] = gapCharacter;
1472 toappendsq.add(addedsq);
1475 for (SequenceI addedsq : toappendsq)
1477 addSequence(addedsq);
1480 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1481 for (int a = 0; alan != null && a < alan.length; a++)
1483 addAnnotation(alan[a]);
1487 getCodonFrames().addAll(toappend.getCodonFrames());
1489 List<SequenceGroup> sg = toappend.getGroups();
1492 for (SequenceGroup _sg : sg)
1497 if (toappend.getHiddenSequences() != null)
1499 HiddenSequences hs = toappend.getHiddenSequences();
1500 if (hiddenSequences == null)
1502 hiddenSequences = new HiddenSequences(this);
1504 if (hs.hiddenSequences != null)
1506 for (int s = 0; s < hs.hiddenSequences.length; s++)
1508 // hide the newly appended sequence in the alignment
1509 if (hs.hiddenSequences[s] != null)
1511 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1516 if (toappend.getProperties() != null)
1518 // we really can't do very much here - just try to concatenate strings
1519 // where property collisions occur.
1520 Enumeration key = toappend.getProperties().keys();
1521 while (key.hasMoreElements())
1523 Object k = key.nextElement();
1524 Object ourval = this.getProperty(k);
1525 Object toapprop = toappend.getProperty(k);
1528 if (ourval.getClass().equals(toapprop.getClass())
1529 && !ourval.equals(toapprop))
1531 if (ourval instanceof String)
1534 this.setProperty(k, ((String) ourval) + "; "
1535 + ((String) toapprop));
1539 if (ourval instanceof Vector)
1542 Enumeration theirv = ((Vector) toapprop).elements();
1543 while (theirv.hasMoreElements())
1545 ((Vector) ourval).addElement(theirv);
1553 // just add new property directly
1554 setProperty(k, toapprop);
1562 public AlignmentAnnotation findOrCreateAnnotation(String name,
1563 String calcId, boolean autoCalc, SequenceI seqRef,
1564 SequenceGroup groupRef)
1566 if (annotations != null)
1568 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1570 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1571 && (calcId == null || annot.getCalcId().equals(calcId))
1572 && annot.sequenceRef == seqRef
1573 && annot.groupRef == groupRef)
1579 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1580 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1581 annot.hasText = false;
1582 annot.setCalcId(new String(calcId));
1583 annot.autoCalculated = autoCalc;
1586 annot.setSequenceRef(seqRef);
1588 annot.groupRef = groupRef;
1589 addAnnotation(annot);
1595 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1597 List<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1598 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1599 if (alignmentAnnotation != null)
1601 for (AlignmentAnnotation a : alignmentAnnotation)
1603 if (a.getCalcId() == calcId
1604 || (a.getCalcId() != null && calcId != null && a
1605 .getCalcId().equals(calcId)))
1615 * Returns an iterable collection of any annotations that match on given
1616 * sequence ref, calcId and label (ignoring null values).
1619 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1620 String calcId, String label)
1622 ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1623 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1625 if (ann.getCalcId() != null && ann.getCalcId().equals(calcId)
1626 && ann.sequenceRef != null && ann.sequenceRef == seq
1627 && ann.label != null && ann.label.equals(label))
1636 public void moveSelectedSequencesByOne(SequenceGroup sg,
1637 Map<SequenceI, SequenceCollectionI> map, boolean up)
1639 synchronized (sequences)
1644 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1646 SequenceI seq = sequences.get(i);
1647 if (!sg.getSequences(map).contains(seq))
1652 SequenceI temp = sequences.get(i - 1);
1653 if (sg.getSequences(null).contains(temp))
1658 sequences.set(i, temp);
1659 sequences.set(i - 1, seq);
1664 for (int i = sequences.size() - 2; i > -1; i--)
1666 SequenceI seq = sequences.get(i);
1667 if (!sg.getSequences(map).contains(seq))
1672 SequenceI temp = sequences.get(i + 1);
1673 if (sg.getSequences(map).contains(temp))
1678 sequences.set(i, temp);
1679 sequences.set(i + 1, seq);
1687 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1689 alignmentAnnotation.validateRangeAndDisplay();
1690 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1692 hasRNAStructure = true;
1696 private SequenceI seqrep = null;
1700 * @return the representative sequence for this group
1703 public SequenceI getSeqrep()
1709 * set the representative sequence for this group. Note - this affects the
1710 * interpretation of the Hidereps attribute.
1713 * the seqrep to set (null means no sequence representative)
1716 public void setSeqrep(SequenceI seqrep)
1718 this.seqrep = seqrep;
1723 * @return true if group has a sequence representative
1726 public boolean hasSeqrep()
1728 return seqrep != null;
1732 public int getEndRes()
1734 return getWidth() - 1;
1738 public int getStartRes()
1744 * In the case of AlignmentI - returns the dataset for the alignment, if set
1747 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1750 public AnnotatedCollectionI getContext()
1756 * Align this alignment like the given (mapped) one.
1759 public int alignAs(AlignmentI al)
1762 * Currently retains unmapped gaps (in introns), regaps mapped regions
1765 return alignAs(al, false, true);
1769 * Align this alignment 'the same as' the given one. Mapped sequences only are
1770 * realigned. If both of the same type (nucleotide/protein) then align both
1771 * identically. If this is nucleotide and the other is protein, make 3 gaps
1772 * for each gap in the protein sequences. If this is protein and the other is
1773 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1774 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1775 * protein to match the relative ordering of codons in the nucleotide.
1777 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1778 * regions are preserved. Gaps that connect introns to exons are treated
1779 * conservatively, i.e. only preserved if both intron and exon gaps are
1780 * preserved. TODO: check caveats below where the implementation fails
1783 * - must have same dataset, and sequences in al must have equivalent
1784 * dataset sequence and start/end bounds under given mapping
1785 * @param preserveMappedGaps
1786 * if true, gaps within and between mapped codons are preserved
1787 * @param preserveUnmappedGaps
1788 * if true, gaps within and between unmapped codons are preserved
1791 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1792 boolean preserveUnmappedGaps)
1794 // TODO should this method signature be the one in the interface?
1795 // JBPComment - yes - neither flag is used, so should be deleted.
1796 boolean thisIsNucleotide = this.isNucleotide();
1797 boolean thatIsProtein = !al.isNucleotide();
1798 if (!thatIsProtein && !thisIsNucleotide)
1800 return AlignmentUtils.alignProteinAsDna(this, al);
1802 else if (thatIsProtein && thisIsNucleotide)
1804 return AlignmentUtils.alignCdsAsProtein(this, al);
1806 return AlignmentUtils.alignAs(this, al);
1810 * Returns the alignment in Fasta format. Behaviour of this method is not
1811 * guaranteed between versions.
1814 public String toString()
1816 return new FastaFile().print(getSequencesArray(), true);
1820 * Returns the set of distinct sequence names. No ordering is guaranteed.
1823 public Set<String> getSequenceNames()
1825 Set<String> names = new HashSet<String>();
1826 for (SequenceI seq : getSequences())
1828 names.add(seq.getName());
1834 public boolean hasValidSequence()
1836 boolean hasValidSeq = false;
1837 for (SequenceI seq : getSequences())
1839 if ((seq.getEnd() - seq.getStart()) > 0)
1849 * Update any mappings to 'virtual' sequences to compatible real ones, if
1850 * present in the added sequences. Returns a count of mappings updated.
1856 public int realiseMappings(List<SequenceI> seqs)
1859 for (SequenceI seq : seqs)
1861 for (AlignedCodonFrame mapping : getCodonFrames())
1863 count += mapping.realiseWith(seq);
1870 * Returns the first AlignedCodonFrame that has a mapping between the given
1878 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1880 for (AlignedCodonFrame acf : getCodonFrames())
1882 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1891 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1893 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1894 int startPos = alignmentStartEnd[0];
1895 int endPos = alignmentStartEnd[1];
1897 int[] lowestRange = new int[] { -1, -1 };
1898 int[] higestRange = new int[] { -1, -1 };
1900 for (int[] hiddenCol : hiddenCols)
1902 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1903 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1906 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1908 startPos = alignmentStartEnd[0];
1912 startPos = lowestRange[1] + 1;
1915 if (higestRange[0] == -1 && higestRange[1] == -1)
1917 endPos = alignmentStartEnd[1];
1921 endPos = higestRange[0] - 1;
1923 return new int[] { startPos, endPos };
1926 Map<Object, ContactMatrixI> contactmaps = new HashMap<Object, ContactMatrixI>();
1929 ContactListI getContactListFor(AlignmentAnnotation _aa, int column)
1931 ContactMatrixI cm = contactmaps.get(_aa.annotationId);
1936 return cm.getContactList(column);
1940 public AlignmentAnnotation addContactList(ContactMatrixI cm)
1942 Annotation _aa[] = new Annotation[getWidth()];
1943 Annotation dummy = new Annotation(0.0f);
1944 for (int i = 0; i < _aa.length; _aa[i++] = dummy)
1948 AlignmentAnnotation aa = new AlignmentAnnotation("Contact Matrix",
1949 "Contact Matrix", _aa);
1950 aa.graph = AlignmentAnnotation.CUSTOMRENDERER;
1951 aa.graphMin = cm.getMin();
1952 aa.graphMax = cm.getMax();
1953 aa.editable = false;
1954 // aa.autoCalculated = true;
1955 contactmaps.put(aa.annotationId, cm);