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)
339 public void deleteSequence(SequenceI s)
341 synchronized (sequences)
343 deleteSequence(findIndex(s));
348 public void deleteSequence(int i)
350 synchronized (sequences)
352 if (i > -1 && i < getHeight())
355 hiddenSequences.adjustHeightSequenceDeleted(i);
361 public void deleteHiddenSequence(int i)
363 synchronized (sequences)
365 if (i > -1 && i < getHeight())
375 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
378 public SequenceGroup findGroup(SequenceI seq, int position)
380 synchronized (groups)
382 for (SequenceGroup sg : groups)
384 if (sg.getSequences(null).contains(seq))
386 if (position >= sg.getStartRes() && position <= sg.getEndRes())
400 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
403 public SequenceGroup[] findAllGroups(SequenceI s)
405 ArrayList<SequenceGroup> temp = new ArrayList<SequenceGroup>();
407 synchronized (groups)
409 int gSize = groups.size();
410 for (int i = 0; i < gSize; i++)
412 SequenceGroup sg = groups.get(i);
413 if (sg == null || sg.getSequences() == null)
415 this.deleteGroup(sg);
420 if (sg.getSequences().contains(s))
426 SequenceGroup[] ret = new SequenceGroup[temp.size()];
427 return temp.toArray(ret);
432 public void addGroup(SequenceGroup sg)
434 synchronized (groups)
436 if (!groups.contains(sg))
438 if (hiddenSequences.getSize() > 0)
440 int i, iSize = sg.getSize();
441 for (i = 0; i < iSize; i++)
443 if (!sequences.contains(sg.getSequenceAt(i)))
445 sg.deleteSequence(sg.getSequenceAt(i), false);
451 if (sg.getSize() < 1)
463 * remove any annotation that references gp
466 * (if null, removes all group associated annotation)
468 private void removeAnnotationForGroup(SequenceGroup gp)
470 if (annotations == null || annotations.length == 0)
474 // remove annotation very quickly
475 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
479 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
481 if (annotations[i].groupRef != null)
483 todelete[p++] = annotations[i];
487 tokeep[k++] = annotations[i];
493 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
495 if (annotations[i].groupRef == gp)
497 todelete[p++] = annotations[i];
501 tokeep[k++] = annotations[i];
507 // clear out the group associated annotation.
508 for (i = 0; i < p; i++)
510 unhookAnnotation(todelete[i]);
513 t = new AlignmentAnnotation[k];
514 for (i = 0; i < k; i++)
523 public void deleteAllGroups()
525 synchronized (groups)
527 if (annotations != null)
529 removeAnnotationForGroup(null);
531 for (SequenceGroup sg : groups)
541 public void deleteGroup(SequenceGroup g)
543 synchronized (groups)
545 if (groups.contains(g))
547 removeAnnotationForGroup(g);
556 public SequenceI findName(String name)
558 return findName(name, false);
564 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
567 public SequenceI findName(String token, boolean b)
569 return findName(null, token, b);
575 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
579 public SequenceI findName(SequenceI startAfter, String token, boolean b)
584 String sqname = null;
585 if (startAfter != null)
587 // try to find the sequence in the alignment
588 boolean matched = false;
589 while (i < sequences.size())
591 if (getSequenceAt(i++) == startAfter)
602 while (i < sequences.size())
604 sq = getSequenceAt(i);
605 sqname = sq.getName();
606 if (sqname.equals(token) // exact match
607 || (b && // allow imperfect matches - case varies
608 (sqname.equalsIgnoreCase(token))))
610 return getSequenceAt(i);
620 public SequenceI[] findSequenceMatch(String name)
622 Vector matches = new Vector();
625 while (i < sequences.size())
627 if (getSequenceAt(i).getName().equals(name))
629 matches.addElement(getSequenceAt(i));
634 SequenceI[] result = new SequenceI[matches.size()];
635 for (i = 0; i < result.length; i++)
637 result[i] = (SequenceI) matches.elementAt(i);
647 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
650 public int findIndex(SequenceI s)
654 while (i < sequences.size())
656 if (s == getSequenceAt(i))
671 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
674 public int findIndex(SearchResultsI results)
678 while (i < sequences.size())
680 if (results.involvesSequence(getSequenceAt(i)))
691 public int getHeight()
693 return sequences.size();
697 public int getAbsoluteHeight()
699 return sequences.size() + getHiddenSequences().getSize();
703 public int getWidth()
707 for (int i = 0; i < sequences.size(); i++)
709 if (getSequenceAt(i).getLength() > maxLength)
711 maxLength = getSequenceAt(i).getLength();
725 public void setGapCharacter(char gc)
728 synchronized (sequences)
730 for (SequenceI seq : sequences)
732 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
733 .replace('-', gc).replace(' ', gc));
741 * @return DOCUMENT ME!
744 public char getGapCharacter()
752 * @see jalview.datamodel.AlignmentI#isAligned()
755 public boolean isAligned()
757 return isAligned(false);
763 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
766 public boolean isAligned(boolean includeHidden)
768 int width = getWidth();
769 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
771 includeHidden = true; // no hidden sequences to check against.
773 for (int i = 0; i < sequences.size(); i++)
775 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
777 if (getSequenceAt(i).getLength() != width)
788 public boolean isHidden(int alignmentIndex)
790 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
794 * Delete all annotations, including auto-calculated if the flag is set true.
795 * Returns true if at least one annotation was deleted, else false.
797 * @param includingAutoCalculated
801 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
803 boolean result = false;
804 for (AlignmentAnnotation alan : getAlignmentAnnotation())
806 if (!alan.autoCalculated || includingAutoCalculated)
808 deleteAnnotation(alan);
818 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
819 * AlignmentAnnotation)
822 public boolean deleteAnnotation(AlignmentAnnotation aa)
824 return deleteAnnotation(aa, true);
828 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
832 if (annotations != null)
834 aSize = annotations.length;
842 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
844 boolean swap = false;
847 for (int i = 0; i < aSize; i++)
849 if (annotations[i] == aa)
854 if (tIndex < temp.length)
856 temp[tIndex++] = annotations[i];
865 unhookAnnotation(aa);
872 * remove any object references associated with this annotation
876 private void unhookAnnotation(AlignmentAnnotation aa)
878 if (aa.sequenceRef != null)
880 aa.sequenceRef.removeAlignmentAnnotation(aa);
882 if (aa.groupRef != null)
884 // probably need to do more here in the future (post 2.5.0)
892 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
893 * AlignmentAnnotation)
896 public void addAnnotation(AlignmentAnnotation aa)
898 addAnnotation(aa, -1);
904 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
905 * AlignmentAnnotation, int)
908 public void addAnnotation(AlignmentAnnotation aa, int pos)
910 if (aa.getRNAStruc() != null)
912 hasRNAStructure = true;
916 if (annotations != null)
918 aSize = annotations.length + 1;
921 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
923 if (pos == -1 || pos >= aSize)
925 temp[aSize - 1] = aa;
934 for (i = 0; i < (aSize - 1); i++, p++)
942 temp[p] = annotations[i];
951 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
953 if (aa == null || annotations == null || annotations.length - 1 < index)
958 int aSize = annotations.length;
959 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
963 for (int i = 0; i < aSize; i++)
972 temp[i] = annotations[i];
976 temp[i] = annotations[i - 1];
985 * returns all annotation on the alignment
987 public AlignmentAnnotation[] getAlignmentAnnotation()
993 public boolean isNucleotide()
999 public boolean hasRNAStructure()
1001 // TODO can it happen that structure is removed from alignment?
1002 return hasRNAStructure;
1006 public void setDataset(AlignmentI data)
1008 if (dataset == null && data == null)
1010 createDatasetAlignment();
1012 else if (dataset == null && data != null)
1016 throw new IllegalArgumentException("Circular dataset reference");
1018 if (!(data instanceof Alignment))
1021 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1023 dataset = (Alignment) data;
1024 for (int i = 0; i < getHeight(); i++)
1026 SequenceI currentSeq = getSequenceAt(i);
1027 SequenceI dsq = currentSeq.getDatasetSequence();
1030 dsq = currentSeq.createDatasetSequence();
1031 dataset.addSequence(dsq);
1035 while (dsq.getDatasetSequence() != null)
1037 dsq = dsq.getDatasetSequence();
1039 if (dataset.findIndex(dsq) == -1)
1041 dataset.addSequence(dsq);
1046 dataset.addAlignmentRef();
1050 * add dataset sequences to seq for currentSeq and any sequences it references
1052 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1053 Set<SequenceI> seqs, boolean createDatasetSequence)
1055 SequenceI alignedSeq = currentSeq;
1056 if (currentSeq.getDatasetSequence() != null)
1058 currentSeq = currentSeq.getDatasetSequence();
1062 if (createDatasetSequence)
1064 currentSeq = currentSeq.createDatasetSequence();
1067 if (seqs.contains(currentSeq))
1071 List<SequenceI> toProcess = new ArrayList<SequenceI>();
1072 toProcess.add(currentSeq);
1073 while (toProcess.size() > 0)
1076 SequenceI curDs = toProcess.remove(0);
1077 if (seqs.contains(curDs))
1082 // iterate over database references, making sure we add forward referenced
1084 if (curDs.getDBRefs() != null)
1086 for (DBRefEntry dbr : curDs.getDBRefs())
1088 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1090 if (dbr.getMap().getTo() == alignedSeq)
1093 * update mapping to be to the newly created dataset sequence
1095 dbr.getMap().setTo(currentSeq);
1097 if (dbr.getMap().getTo().getDatasetSequence() != null)
1100 "Implementation error: Map.getTo() for dbref " + dbr
1101 + " from " + curDs.getName()
1102 + " is not a dataset sequence.");
1104 // we recurse to add all forward references to dataset sequences via
1106 toProcess.add(dbr.getMap().getTo());
1114 * Creates a new dataset for this alignment. Can only be done once - if
1115 * dataset is not null this will not be performed.
1117 public void createDatasetAlignment()
1119 if (dataset != null)
1123 // try to avoid using SequenceI.equals at this stage, it will be expensive
1124 Set<SequenceI> seqs = new LinkedIdentityHashSet<SequenceI>();
1126 for (int i = 0; i < getHeight(); i++)
1128 SequenceI currentSeq = getSequenceAt(i);
1129 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1132 // verify all mappings are in dataset
1133 for (AlignedCodonFrame cf : codonFrameList)
1135 for (SequenceToSequenceMapping ssm : cf.getMappings())
1137 if (!seqs.contains(ssm.getFromSeq()))
1139 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1141 if (!seqs.contains(ssm.getMapping().getTo()))
1143 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1147 // finally construct dataset
1148 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1149 // move mappings to the dataset alignment
1150 dataset.codonFrameList = this.codonFrameList;
1151 this.codonFrameList = null;
1155 * reference count for number of alignments referencing this one.
1157 int alignmentRefs = 0;
1160 * increase reference count to this alignment.
1162 private void addAlignmentRef()
1168 public Alignment getDataset()
1174 public boolean padGaps()
1176 boolean modified = false;
1178 // Remove excess gaps from the end of alignment
1182 for (int i = 0; i < sequences.size(); i++)
1184 current = getSequenceAt(i);
1185 for (int j = current.getLength(); j > maxLength; j--)
1188 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1199 for (int i = 0; i < sequences.size(); i++)
1201 current = getSequenceAt(i);
1202 cLength = current.getLength();
1204 if (cLength < maxLength)
1206 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1209 else if (current.getLength() > maxLength)
1211 current.deleteChars(maxLength, current.getLength());
1218 * Justify the sequences to the left or right by deleting and inserting gaps
1219 * before the initial residue or after the terminal residue
1222 * true if alignment padded to right, false to justify to left
1223 * @return true if alignment was changed
1226 public boolean justify(boolean right)
1228 boolean modified = false;
1230 // Remove excess gaps from the end of alignment
1232 int ends[] = new int[sequences.size() * 2];
1234 for (int i = 0; i < sequences.size(); i++)
1236 current = getSequenceAt(i);
1237 // This should really be a sequence method
1238 ends[i * 2] = current.findIndex(current.getStart());
1239 ends[i * 2 + 1] = current.findIndex(current.getStart()
1240 + current.getLength());
1241 boolean hitres = false;
1242 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1244 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1253 ends[i * 2 + 1] = j;
1254 if (j - ends[i * 2] > maxLength)
1256 maxLength = j - ends[i * 2];
1264 // now edit the flanking gaps to justify to either left or right
1265 int cLength, extent, diff;
1266 for (int i = 0; i < sequences.size(); i++)
1268 current = getSequenceAt(i);
1270 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1271 diff = maxLength - cLength; // number of gaps to indent
1272 extent = current.getLength();
1276 if (extent > ends[i * 2 + 1])
1278 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1281 if (ends[i * 2] > diff)
1283 current.deleteChars(0, ends[i * 2] - diff);
1288 if (ends[i * 2] < diff)
1290 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1298 if (ends[i * 2] > 0)
1300 current.deleteChars(0, ends[i * 2]);
1302 ends[i * 2 + 1] -= ends[i * 2];
1303 extent -= ends[i * 2];
1305 if (extent > maxLength)
1307 current.deleteChars(maxLength + 1, extent);
1312 if (extent < maxLength)
1314 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1324 public HiddenSequences getHiddenSequences()
1326 return hiddenSequences;
1330 public CigarArray getCompactAlignment()
1332 synchronized (sequences)
1334 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1336 for (SequenceI seq : sequences)
1338 alseqs[i++] = new SeqCigar(seq);
1340 CigarArray cal = new CigarArray(alseqs);
1341 cal.addOperation(CigarArray.M, getWidth());
1347 public void setProperty(Object key, Object value)
1349 if (alignmentProperties == null)
1351 alignmentProperties = new Hashtable();
1354 alignmentProperties.put(key, value);
1358 public Object getProperty(Object key)
1360 if (alignmentProperties != null)
1362 return alignmentProperties.get(key);
1371 public Hashtable getProperties()
1373 return alignmentProperties;
1377 * Adds the given mapping to the stored set. Note this may be held on the
1378 * dataset alignment.
1381 public void addCodonFrame(AlignedCodonFrame codons)
1383 List<AlignedCodonFrame> acfs = getCodonFrames();
1384 if (codons != null && acfs != null && !acfs.contains(codons))
1394 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1397 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1403 List<AlignedCodonFrame> cframes = new ArrayList<AlignedCodonFrame>();
1404 for (AlignedCodonFrame acf : getCodonFrames())
1406 if (acf.involvesSequence(seq))
1415 * Sets the codon frame mappings (replacing any existing mappings). Note the
1416 * mappings are set on the dataset alignment instead if there is one.
1418 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1421 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1423 if (dataset != null)
1425 dataset.setCodonFrames(acfs);
1429 this.codonFrameList = acfs;
1434 * Returns the set of codon frame mappings. Any changes to the returned set
1435 * will affect the alignment. The mappings are held on (and read from) the
1436 * dataset alignment if there is one.
1438 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1441 public List<AlignedCodonFrame> getCodonFrames()
1443 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1444 // this behaviour is currently incorrect. method should return codon frames
1445 // for just the alignment,
1446 // selected from dataset
1447 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1451 * Removes the given mapping from the stored set. Note that the mappings are
1452 * held on the dataset alignment if there is one.
1455 public boolean removeCodonFrame(AlignedCodonFrame codons)
1457 List<AlignedCodonFrame> acfs = getCodonFrames();
1458 if (codons == null || acfs == null)
1462 return acfs.remove(codons);
1466 public void append(AlignmentI toappend)
1468 // TODO JAL-1270 needs test coverage
1469 // currently tested for use in jalview.gui.SequenceFetcher
1470 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1471 char oldc = toappend.getGapCharacter();
1472 boolean hashidden = toappend.getHiddenSequences() != null
1473 && toappend.getHiddenSequences().hiddenSequences != null;
1474 // get all sequences including any hidden ones
1475 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1476 .getFullAlignment().getSequences() : toappend.getSequences();
1479 // avoid self append deadlock by
1480 List<SequenceI> toappendsq = new ArrayList<SequenceI>();
1483 for (SequenceI addedsq : sqs)
1487 char[] oldseq = addedsq.getSequence();
1488 for (int c = 0; c < oldseq.length; c++)
1490 if (oldseq[c] == oldc)
1492 oldseq[c] = gapCharacter;
1496 toappendsq.add(addedsq);
1499 for (SequenceI addedsq : toappendsq)
1501 addSequence(addedsq);
1504 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1505 for (int a = 0; alan != null && a < alan.length; a++)
1507 addAnnotation(alan[a]);
1511 getCodonFrames().addAll(toappend.getCodonFrames());
1513 List<SequenceGroup> sg = toappend.getGroups();
1516 for (SequenceGroup _sg : sg)
1521 if (toappend.getHiddenSequences() != null)
1523 HiddenSequences hs = toappend.getHiddenSequences();
1524 if (hiddenSequences == null)
1526 hiddenSequences = new HiddenSequences(this);
1528 if (hs.hiddenSequences != null)
1530 for (int s = 0; s < hs.hiddenSequences.length; s++)
1532 // hide the newly appended sequence in the alignment
1533 if (hs.hiddenSequences[s] != null)
1535 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1540 if (toappend.getProperties() != null)
1542 // we really can't do very much here - just try to concatenate strings
1543 // where property collisions occur.
1544 Enumeration key = toappend.getProperties().keys();
1545 while (key.hasMoreElements())
1547 Object k = key.nextElement();
1548 Object ourval = this.getProperty(k);
1549 Object toapprop = toappend.getProperty(k);
1552 if (ourval.getClass().equals(toapprop.getClass())
1553 && !ourval.equals(toapprop))
1555 if (ourval instanceof String)
1558 this.setProperty(k, ((String) ourval) + "; "
1559 + ((String) toapprop));
1563 if (ourval instanceof Vector)
1566 Enumeration theirv = ((Vector) toapprop).elements();
1567 while (theirv.hasMoreElements())
1569 ((Vector) ourval).addElement(theirv);
1577 // just add new property directly
1578 setProperty(k, toapprop);
1586 public AlignmentAnnotation findOrCreateAnnotation(String name,
1587 String calcId, boolean autoCalc, SequenceI seqRef,
1588 SequenceGroup groupRef)
1590 if (annotations != null)
1592 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1594 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1595 && (calcId == null || annot.getCalcId().equals(calcId))
1596 && annot.sequenceRef == seqRef
1597 && annot.groupRef == groupRef)
1603 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1604 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1605 annot.hasText = false;
1606 annot.setCalcId(new String(calcId));
1607 annot.autoCalculated = autoCalc;
1610 annot.setSequenceRef(seqRef);
1612 annot.groupRef = groupRef;
1613 addAnnotation(annot);
1619 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1621 List<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1622 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1623 if (alignmentAnnotation != null)
1625 for (AlignmentAnnotation a : alignmentAnnotation)
1627 if (a.getCalcId() == calcId
1628 || (a.getCalcId() != null && calcId != null && a
1629 .getCalcId().equals(calcId)))
1639 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1640 String calcId, String label)
1642 ArrayList<AlignmentAnnotation> aa = new ArrayList<AlignmentAnnotation>();
1643 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1645 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1647 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1648 && (label == null || (ann.label != null && ann.label
1658 public void moveSelectedSequencesByOne(SequenceGroup sg,
1659 Map<SequenceI, SequenceCollectionI> map, boolean up)
1661 synchronized (sequences)
1666 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1668 SequenceI seq = sequences.get(i);
1669 if (!sg.getSequences(map).contains(seq))
1674 SequenceI temp = sequences.get(i - 1);
1675 if (sg.getSequences(null).contains(temp))
1680 sequences.set(i, temp);
1681 sequences.set(i - 1, seq);
1686 for (int i = sequences.size() - 2; i > -1; i--)
1688 SequenceI seq = sequences.get(i);
1689 if (!sg.getSequences(map).contains(seq))
1694 SequenceI temp = sequences.get(i + 1);
1695 if (sg.getSequences(map).contains(temp))
1700 sequences.set(i, temp);
1701 sequences.set(i + 1, seq);
1709 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1711 alignmentAnnotation.validateRangeAndDisplay();
1712 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1714 hasRNAStructure = true;
1718 private SequenceI seqrep = null;
1722 * @return the representative sequence for this group
1725 public SequenceI getSeqrep()
1731 * set the representative sequence for this group. Note - this affects the
1732 * interpretation of the Hidereps attribute.
1735 * the seqrep to set (null means no sequence representative)
1738 public void setSeqrep(SequenceI seqrep)
1740 this.seqrep = seqrep;
1745 * @return true if group has a sequence representative
1748 public boolean hasSeqrep()
1750 return seqrep != null;
1754 public int getEndRes()
1756 return getWidth() - 1;
1760 public int getStartRes()
1766 * In the case of AlignmentI - returns the dataset for the alignment, if set
1769 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1772 public AnnotatedCollectionI getContext()
1778 * Align this alignment like the given (mapped) one.
1781 public int alignAs(AlignmentI al)
1784 * Currently retains unmapped gaps (in introns), regaps mapped regions
1787 return alignAs(al, false, true);
1791 * Align this alignment 'the same as' the given one. Mapped sequences only are
1792 * realigned. If both of the same type (nucleotide/protein) then align both
1793 * identically. If this is nucleotide and the other is protein, make 3 gaps
1794 * for each gap in the protein sequences. If this is protein and the other is
1795 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1796 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1797 * protein to match the relative ordering of codons in the nucleotide.
1799 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1800 * regions are preserved. Gaps that connect introns to exons are treated
1801 * conservatively, i.e. only preserved if both intron and exon gaps are
1802 * preserved. TODO: check caveats below where the implementation fails
1805 * - must have same dataset, and sequences in al must have equivalent
1806 * dataset sequence and start/end bounds under given mapping
1807 * @param preserveMappedGaps
1808 * if true, gaps within and between mapped codons are preserved
1809 * @param preserveUnmappedGaps
1810 * if true, gaps within and between unmapped codons are preserved
1813 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1814 boolean preserveUnmappedGaps)
1816 // TODO should this method signature be the one in the interface?
1817 // JBPComment - yes - neither flag is used, so should be deleted.
1818 boolean thisIsNucleotide = this.isNucleotide();
1819 boolean thatIsProtein = !al.isNucleotide();
1820 if (!thatIsProtein && !thisIsNucleotide)
1822 return AlignmentUtils.alignProteinAsDna(this, al);
1824 else if (thatIsProtein && thisIsNucleotide)
1826 return AlignmentUtils.alignCdsAsProtein(this, al);
1828 return AlignmentUtils.alignAs(this, al);
1832 * Returns the alignment in Fasta format. Behaviour of this method is not
1833 * guaranteed between versions.
1836 public String toString()
1838 return new FastaFile().print(getSequencesArray(), true);
1842 * Returns the set of distinct sequence names. No ordering is guaranteed.
1845 public Set<String> getSequenceNames()
1847 Set<String> names = new HashSet<String>();
1848 for (SequenceI seq : getSequences())
1850 names.add(seq.getName());
1856 public boolean hasValidSequence()
1858 boolean hasValidSeq = false;
1859 for (SequenceI seq : getSequences())
1861 if ((seq.getEnd() - seq.getStart()) > 0)
1871 * Update any mappings to 'virtual' sequences to compatible real ones, if
1872 * present in the added sequences. Returns a count of mappings updated.
1878 public int realiseMappings(List<SequenceI> seqs)
1881 for (SequenceI seq : seqs)
1883 for (AlignedCodonFrame mapping : getCodonFrames())
1885 count += mapping.realiseWith(seq);
1892 * Returns the first AlignedCodonFrame that has a mapping between the given
1900 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1902 for (AlignedCodonFrame acf : getCodonFrames())
1904 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1913 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1915 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1916 int startPos = alignmentStartEnd[0];
1917 int endPos = alignmentStartEnd[1];
1919 int[] lowestRange = new int[] { -1, -1 };
1920 int[] higestRange = new int[] { -1, -1 };
1922 for (int[] hiddenCol : hiddenCols)
1924 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1925 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1928 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1930 startPos = alignmentStartEnd[0];
1934 startPos = lowestRange[1] + 1;
1937 if (higestRange[0] == -1 && higestRange[1] == -1)
1939 endPos = alignmentStartEnd[1];
1943 endPos = higestRange[0] - 1;
1945 return new int[] { startPos, endPos };