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 HiddenColumns hiddenCols;
67 public Hashtable alignmentProperties;
69 private List<AlignedCodonFrame> codonFrameList;
71 private void initAlignment(SequenceI[] seqs)
73 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
74 hiddenSequences = new HiddenSequences(this);
75 hiddenCols = new HiddenColumns();
76 codonFrameList = new ArrayList<>();
78 nucleotide = Comparison.isNucleotide(seqs);
80 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
82 for (int i = 0; i < seqs.length; i++)
84 sequences.add(seqs[i]);
90 * Make a 'copy' alignment - sequences have new copies of features and
91 * annotations, but share the original dataset sequences.
93 public Alignment(AlignmentI al)
95 SequenceI[] seqs = al.getSequencesArray();
96 for (int i = 0; i < seqs.length; i++)
98 seqs[i] = new Sequence(seqs[i]);
104 * Share the same dataset sequence mappings (if any).
106 if (dataset == null && al.getDataset() == null)
108 this.setCodonFrames(al.getCodonFrames());
113 * Make an alignment from an array of Sequences.
117 public Alignment(SequenceI[] seqs)
123 * Make a new alignment from an array of SeqCigars
128 public Alignment(SeqCigar[] alseqs)
130 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
131 gapCharacter, new HiddenColumns(), null);
136 * Make a new alignment from an CigarArray JBPNote - can only do this when
137 * compactAlignment does not contain hidden regions. JBPNote - must also check
138 * that compactAlignment resolves to a set of SeqCigars - or construct them
141 * @param compactAlignment
144 public static AlignmentI createAlignment(CigarArray compactAlignment)
148 .getString("error.alignment_cigararray_not_implemented"));
149 // this(compactAlignment.refCigars);
153 public List<SequenceI> getSequences()
159 public List<SequenceI> getSequences(
160 Map<SequenceI, SequenceCollectionI> hiddenReps)
162 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
168 public SequenceI[] getSequencesArray()
170 if (sequences == null)
174 synchronized (sequences)
176 return sequences.toArray(new SequenceI[sequences.size()]);
181 * Returns a map of lists of sequences keyed by sequence name.
186 public Map<String, List<SequenceI>> getSequencesByName()
188 return AlignmentUtils.getSequencesByName(this);
193 public SequenceI getSequenceAt(int i)
195 synchronized (sequences)
197 if (i > -1 && i < sequences.size())
199 return sequences.get(i);
206 public SequenceI getSequenceAtAbsoluteIndex(int i)
208 SequenceI seq = null;
209 if (getHiddenSequences().getSize() > 0)
211 seq = getHiddenSequences().getHiddenSequence(i);
214 // didn't find the sequence in the hidden sequences, get it from the
216 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
217 seq = getSequenceAt(index);
222 seq = getSequenceAt(i);
228 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
229 * this currently does not recalculate whether or not the alignment is
230 * nucleotide, so mixed alignments may have undefined behaviour.
235 public void addSequence(SequenceI snew)
240 // maintain dataset integrity
241 SequenceI dsseq = snew.getDatasetSequence();
244 // derive new sequence
245 SequenceI adding = snew.deriveSequence();
247 dsseq = snew.getDatasetSequence();
249 if (getDataset().findIndex(dsseq) == -1)
251 getDataset().addSequence(dsseq);
255 if (sequences == null)
257 initAlignment(new SequenceI[] { snew });
261 synchronized (sequences)
266 if (hiddenSequences != null)
268 hiddenSequences.adjustHeightSequenceAdded();
273 public SequenceI replaceSequenceAt(int i, SequenceI snew)
275 synchronized (sequences)
277 if (sequences.size() > i)
279 return sequences.set(i, snew);
285 hiddenSequences.adjustHeightSequenceAdded();
294 * @return DOCUMENT ME!
297 public List<SequenceGroup> getGroups()
303 public void finalize() throws Throwable
305 if (getDataset() != null)
307 getDataset().removeAlignmentRef();
315 * Defensively nulls out references in case this object is not garbage
318 void nullReferences()
324 hiddenSequences = null;
328 * decrement the alignmentRefs counter by one and null references if it goes
333 private void removeAlignmentRef() throws Throwable
335 if (--alignmentRefs == 0)
342 public void deleteSequence(SequenceI s)
344 synchronized (sequences)
346 deleteSequence(findIndex(s));
351 public void deleteSequence(int i)
353 synchronized (sequences)
355 if (i > -1 && i < getHeight())
358 hiddenSequences.adjustHeightSequenceDeleted(i);
364 public void deleteHiddenSequence(int i)
366 synchronized (sequences)
368 if (i > -1 && i < getHeight())
378 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
381 public SequenceGroup findGroup(SequenceI seq, int position)
383 synchronized (groups)
385 for (SequenceGroup sg : groups)
387 if (sg.getSequences(null).contains(seq))
389 if (position >= sg.getStartRes() && position <= sg.getEndRes())
403 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
406 public SequenceGroup[] findAllGroups(SequenceI s)
408 ArrayList<SequenceGroup> temp = new ArrayList<>();
410 synchronized (groups)
412 int gSize = groups.size();
413 for (int i = 0; i < gSize; i++)
415 SequenceGroup sg = groups.get(i);
416 if (sg == null || sg.getSequences() == null)
418 this.deleteGroup(sg);
423 if (sg.getSequences().contains(s))
429 SequenceGroup[] ret = new SequenceGroup[temp.size()];
430 return temp.toArray(ret);
435 public void addGroup(SequenceGroup sg)
437 synchronized (groups)
439 if (!groups.contains(sg))
441 if (hiddenSequences.getSize() > 0)
443 int i, iSize = sg.getSize();
444 for (i = 0; i < iSize; i++)
446 if (!sequences.contains(sg.getSequenceAt(i)))
448 sg.deleteSequence(sg.getSequenceAt(i), false);
454 if (sg.getSize() < 1)
459 sg.setContext(this, true);
466 * remove any annotation that references gp
469 * (if null, removes all group associated annotation)
471 private void removeAnnotationForGroup(SequenceGroup gp)
473 if (annotations == null || annotations.length == 0)
477 // remove annotation very quickly
478 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
482 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
484 if (annotations[i].groupRef != null)
486 todelete[p++] = annotations[i];
490 tokeep[k++] = annotations[i];
496 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
498 if (annotations[i].groupRef == gp)
500 todelete[p++] = annotations[i];
504 tokeep[k++] = annotations[i];
510 // clear out the group associated annotation.
511 for (i = 0; i < p; i++)
513 unhookAnnotation(todelete[i]);
516 t = new AlignmentAnnotation[k];
517 for (i = 0; i < k; i++)
526 public void deleteAllGroups()
528 synchronized (groups)
530 if (annotations != null)
532 removeAnnotationForGroup(null);
534 for (SequenceGroup sg : groups)
536 sg.setContext(null, false);
544 public void deleteGroup(SequenceGroup g)
546 synchronized (groups)
548 if (groups.contains(g))
550 removeAnnotationForGroup(g);
552 g.setContext(null, false);
559 public SequenceI findName(String name)
561 return findName(name, false);
567 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
570 public SequenceI findName(String token, boolean b)
572 return findName(null, token, b);
578 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
582 public SequenceI findName(SequenceI startAfter, String token, boolean b)
587 String sqname = null;
588 if (startAfter != null)
590 // try to find the sequence in the alignment
591 boolean matched = false;
592 while (i < sequences.size())
594 if (getSequenceAt(i++) == startAfter)
605 while (i < sequences.size())
607 sq = getSequenceAt(i);
608 sqname = sq.getName();
609 if (sqname.equals(token) // exact match
610 || (b && // allow imperfect matches - case varies
611 (sqname.equalsIgnoreCase(token))))
613 return getSequenceAt(i);
623 public SequenceI[] findSequenceMatch(String name)
625 Vector matches = new Vector();
628 while (i < sequences.size())
630 if (getSequenceAt(i).getName().equals(name))
632 matches.addElement(getSequenceAt(i));
637 SequenceI[] result = new SequenceI[matches.size()];
638 for (i = 0; i < result.length; i++)
640 result[i] = (SequenceI) matches.elementAt(i);
650 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
653 public int findIndex(SequenceI s)
657 while (i < sequences.size())
659 if (s == getSequenceAt(i))
674 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
677 public int findIndex(SearchResultsI results)
681 while (i < sequences.size())
683 if (results.involvesSequence(getSequenceAt(i)))
694 public int getHeight()
696 return sequences.size();
700 public int getAbsoluteHeight()
702 return sequences.size() + getHiddenSequences().getSize();
706 public int getWidth()
710 for (int i = 0; i < sequences.size(); i++)
712 if (getSequenceAt(i).getLength() > maxLength)
714 maxLength = getSequenceAt(i).getLength();
728 public void setGapCharacter(char gc)
731 synchronized (sequences)
733 for (SequenceI seq : sequences)
735 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
736 .replace('-', gc).replace(' ', gc));
744 * @return DOCUMENT ME!
747 public char getGapCharacter()
755 * @see jalview.datamodel.AlignmentI#isAligned()
758 public boolean isAligned()
760 return isAligned(false);
766 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
769 public boolean isAligned(boolean includeHidden)
771 int width = getWidth();
772 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
774 includeHidden = true; // no hidden sequences to check against.
776 for (int i = 0; i < sequences.size(); i++)
778 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
780 if (getSequenceAt(i).getLength() != width)
791 public boolean isHidden(int alignmentIndex)
793 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
797 * Delete all annotations, including auto-calculated if the flag is set true.
798 * Returns true if at least one annotation was deleted, else false.
800 * @param includingAutoCalculated
804 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
806 boolean result = false;
807 for (AlignmentAnnotation alan : getAlignmentAnnotation())
809 if (!alan.autoCalculated || includingAutoCalculated)
811 deleteAnnotation(alan);
821 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
822 * AlignmentAnnotation)
825 public boolean deleteAnnotation(AlignmentAnnotation aa)
827 return deleteAnnotation(aa, true);
831 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
835 if (annotations != null)
837 aSize = annotations.length;
845 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
847 boolean swap = false;
850 for (int i = 0; i < aSize; i++)
852 if (annotations[i] == aa)
857 if (tIndex < temp.length)
859 temp[tIndex++] = annotations[i];
868 unhookAnnotation(aa);
875 * remove any object references associated with this annotation
879 private void unhookAnnotation(AlignmentAnnotation aa)
881 if (aa.sequenceRef != null)
883 aa.sequenceRef.removeAlignmentAnnotation(aa);
885 if (aa.groupRef != null)
887 // probably need to do more here in the future (post 2.5.0)
895 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
896 * AlignmentAnnotation)
899 public void addAnnotation(AlignmentAnnotation aa)
901 addAnnotation(aa, -1);
907 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
908 * AlignmentAnnotation, int)
911 public void addAnnotation(AlignmentAnnotation aa, int pos)
913 if (aa.getRNAStruc() != null)
915 hasRNAStructure = true;
919 if (annotations != null)
921 aSize = annotations.length + 1;
924 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
926 if (pos == -1 || pos >= aSize)
928 temp[aSize - 1] = aa;
937 for (i = 0; i < (aSize - 1); i++, p++)
945 temp[p] = annotations[i];
954 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
956 if (aa == null || annotations == null || annotations.length - 1 < index)
961 int aSize = annotations.length;
962 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
966 for (int i = 0; i < aSize; i++)
975 temp[i] = annotations[i];
979 temp[i] = annotations[i - 1];
988 * returns all annotation on the alignment
990 public AlignmentAnnotation[] getAlignmentAnnotation()
996 public boolean isNucleotide()
1002 public boolean hasRNAStructure()
1004 // TODO can it happen that structure is removed from alignment?
1005 return hasRNAStructure;
1009 public void setDataset(AlignmentI data)
1011 if (dataset == null && data == null)
1013 createDatasetAlignment();
1015 else if (dataset == null && data != null)
1019 throw new IllegalArgumentException("Circular dataset reference");
1021 if (!(data instanceof Alignment))
1024 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1026 dataset = (Alignment) data;
1027 for (int i = 0; i < getHeight(); i++)
1029 SequenceI currentSeq = getSequenceAt(i);
1030 SequenceI dsq = currentSeq.getDatasetSequence();
1033 dsq = currentSeq.createDatasetSequence();
1034 dataset.addSequence(dsq);
1038 while (dsq.getDatasetSequence() != null)
1040 dsq = dsq.getDatasetSequence();
1042 if (dataset.findIndex(dsq) == -1)
1044 dataset.addSequence(dsq);
1049 dataset.addAlignmentRef();
1053 * add dataset sequences to seq for currentSeq and any sequences it references
1055 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1056 Set<SequenceI> seqs, boolean createDatasetSequence)
1058 SequenceI alignedSeq = currentSeq;
1059 if (currentSeq.getDatasetSequence() != null)
1061 currentSeq = currentSeq.getDatasetSequence();
1065 if (createDatasetSequence)
1067 currentSeq = currentSeq.createDatasetSequence();
1071 List<SequenceI> toProcess = new ArrayList<>();
1072 toProcess.add(currentSeq);
1073 while (toProcess.size() > 0)
1076 SequenceI curDs = toProcess.remove(0);
1078 if (!seqs.add(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<>();
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 HiddenColumns getHiddenColumns()
1336 public CigarArray getCompactAlignment()
1338 synchronized (sequences)
1340 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1342 for (SequenceI seq : sequences)
1344 alseqs[i++] = new SeqCigar(seq);
1346 CigarArray cal = new CigarArray(alseqs);
1347 cal.addOperation(CigarArray.M, getWidth());
1353 public void setProperty(Object key, Object value)
1355 if (alignmentProperties == null)
1357 alignmentProperties = new Hashtable();
1360 alignmentProperties.put(key, value);
1364 public Object getProperty(Object key)
1366 if (alignmentProperties != null)
1368 return alignmentProperties.get(key);
1377 public Hashtable getProperties()
1379 return alignmentProperties;
1383 * Adds the given mapping to the stored set. Note this may be held on the
1384 * dataset alignment.
1387 public void addCodonFrame(AlignedCodonFrame codons)
1389 List<AlignedCodonFrame> acfs = getCodonFrames();
1390 if (codons != null && acfs != null && !acfs.contains(codons))
1400 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1403 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1409 List<AlignedCodonFrame> cframes = new ArrayList<>();
1410 for (AlignedCodonFrame acf : getCodonFrames())
1412 if (acf.involvesSequence(seq))
1421 * Sets the codon frame mappings (replacing any existing mappings). Note the
1422 * mappings are set on the dataset alignment instead if there is one.
1424 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1427 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1429 if (dataset != null)
1431 dataset.setCodonFrames(acfs);
1435 this.codonFrameList = acfs;
1440 * Returns the set of codon frame mappings. Any changes to the returned set
1441 * will affect the alignment. The mappings are held on (and read from) the
1442 * dataset alignment if there is one.
1444 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1447 public List<AlignedCodonFrame> getCodonFrames()
1449 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1450 // this behaviour is currently incorrect. method should return codon frames
1451 // for just the alignment,
1452 // selected from dataset
1453 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1457 * Removes the given mapping from the stored set. Note that the mappings are
1458 * held on the dataset alignment if there is one.
1461 public boolean removeCodonFrame(AlignedCodonFrame codons)
1463 List<AlignedCodonFrame> acfs = getCodonFrames();
1464 if (codons == null || acfs == null)
1468 return acfs.remove(codons);
1472 public void append(AlignmentI toappend)
1474 // TODO JAL-1270 needs test coverage
1475 // currently tested for use in jalview.gui.SequenceFetcher
1476 char oldc = toappend.getGapCharacter();
1477 boolean samegap = oldc == getGapCharacter();
1478 boolean hashidden = toappend.getHiddenSequences() != null
1479 && toappend.getHiddenSequences().hiddenSequences != null;
1480 // get all sequences including any hidden ones
1481 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1482 .getFullAlignment().getSequences() : toappend.getSequences();
1485 // avoid self append deadlock by
1486 List<SequenceI> toappendsq = new ArrayList<>();
1489 for (SequenceI addedsq : sqs)
1493 addedsq.replace(oldc, gapCharacter);
1495 toappendsq.add(addedsq);
1498 for (SequenceI addedsq : toappendsq)
1500 addSequence(addedsq);
1503 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1504 for (int a = 0; alan != null && a < alan.length; a++)
1506 addAnnotation(alan[a]);
1510 getCodonFrames().addAll(toappend.getCodonFrames());
1512 List<SequenceGroup> sg = toappend.getGroups();
1515 for (SequenceGroup _sg : sg)
1520 if (toappend.getHiddenSequences() != null)
1522 HiddenSequences hs = toappend.getHiddenSequences();
1523 if (hiddenSequences == null)
1525 hiddenSequences = new HiddenSequences(this);
1527 if (hs.hiddenSequences != null)
1529 for (int s = 0; s < hs.hiddenSequences.length; s++)
1531 // hide the newly appended sequence in the alignment
1532 if (hs.hiddenSequences[s] != null)
1534 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1539 if (toappend.getProperties() != null)
1541 // we really can't do very much here - just try to concatenate strings
1542 // where property collisions occur.
1543 Enumeration key = toappend.getProperties().keys();
1544 while (key.hasMoreElements())
1546 Object k = key.nextElement();
1547 Object ourval = this.getProperty(k);
1548 Object toapprop = toappend.getProperty(k);
1551 if (ourval.getClass().equals(toapprop.getClass())
1552 && !ourval.equals(toapprop))
1554 if (ourval instanceof String)
1557 this.setProperty(k, ((String) ourval) + "; "
1558 + ((String) toapprop));
1562 if (ourval instanceof Vector)
1565 Enumeration theirv = ((Vector) toapprop).elements();
1566 while (theirv.hasMoreElements())
1568 ((Vector) ourval).addElement(theirv);
1576 // just add new property directly
1577 setProperty(k, toapprop);
1585 public AlignmentAnnotation findOrCreateAnnotation(String name,
1586 String calcId, boolean autoCalc, SequenceI seqRef,
1587 SequenceGroup groupRef)
1589 if (annotations != null)
1591 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1593 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1594 && (calcId == null || annot.getCalcId().equals(calcId))
1595 && annot.sequenceRef == seqRef
1596 && annot.groupRef == groupRef)
1602 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1603 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1604 annot.hasText = false;
1605 annot.setCalcId(new String(calcId));
1606 annot.autoCalculated = autoCalc;
1609 annot.setSequenceRef(seqRef);
1611 annot.groupRef = groupRef;
1612 addAnnotation(annot);
1618 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1620 List<AlignmentAnnotation> aa = new ArrayList<>();
1621 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1622 if (alignmentAnnotation != null)
1624 for (AlignmentAnnotation a : alignmentAnnotation)
1626 if (a.getCalcId() == calcId
1627 || (a.getCalcId() != null && calcId != null && a
1628 .getCalcId().equals(calcId)))
1638 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1639 String calcId, String label)
1641 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1642 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1644 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1646 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1647 && (label == null || (ann.label != null && ann.label
1657 public void moveSelectedSequencesByOne(SequenceGroup sg,
1658 Map<SequenceI, SequenceCollectionI> map, boolean up)
1660 synchronized (sequences)
1665 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1667 SequenceI seq = sequences.get(i);
1668 if (!sg.getSequences(map).contains(seq))
1673 SequenceI temp = sequences.get(i - 1);
1674 if (sg.getSequences(null).contains(temp))
1679 sequences.set(i, temp);
1680 sequences.set(i - 1, seq);
1685 for (int i = sequences.size() - 2; i > -1; i--)
1687 SequenceI seq = sequences.get(i);
1688 if (!sg.getSequences(map).contains(seq))
1693 SequenceI temp = sequences.get(i + 1);
1694 if (sg.getSequences(map).contains(temp))
1699 sequences.set(i, temp);
1700 sequences.set(i + 1, seq);
1708 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1710 alignmentAnnotation.validateRangeAndDisplay();
1711 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1713 hasRNAStructure = true;
1717 private SequenceI seqrep = null;
1721 * @return the representative sequence for this group
1724 public SequenceI getSeqrep()
1730 * set the representative sequence for this group. Note - this affects the
1731 * interpretation of the Hidereps attribute.
1734 * the seqrep to set (null means no sequence representative)
1737 public void setSeqrep(SequenceI seqrep)
1739 this.seqrep = seqrep;
1744 * @return true if group has a sequence representative
1747 public boolean hasSeqrep()
1749 return seqrep != null;
1753 public int getEndRes()
1755 return getWidth() - 1;
1759 public int getStartRes()
1765 * In the case of AlignmentI - returns the dataset for the alignment, if set
1768 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1771 public AnnotatedCollectionI getContext()
1777 * Align this alignment like the given (mapped) one.
1780 public int alignAs(AlignmentI al)
1783 * Currently retains unmapped gaps (in introns), regaps mapped regions
1786 return alignAs(al, false, true);
1790 * Align this alignment 'the same as' the given one. Mapped sequences only are
1791 * realigned. If both of the same type (nucleotide/protein) then align both
1792 * identically. If this is nucleotide and the other is protein, make 3 gaps
1793 * for each gap in the protein sequences. If this is protein and the other is
1794 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1795 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1796 * protein to match the relative ordering of codons in the nucleotide.
1798 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1799 * regions are preserved. Gaps that connect introns to exons are treated
1800 * conservatively, i.e. only preserved if both intron and exon gaps are
1801 * preserved. TODO: check caveats below where the implementation fails
1804 * - must have same dataset, and sequences in al must have equivalent
1805 * dataset sequence and start/end bounds under given mapping
1806 * @param preserveMappedGaps
1807 * if true, gaps within and between mapped codons are preserved
1808 * @param preserveUnmappedGaps
1809 * if true, gaps within and between unmapped codons are preserved
1812 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1813 boolean preserveUnmappedGaps)
1815 // TODO should this method signature be the one in the interface?
1816 // JBPComment - yes - neither flag is used, so should be deleted.
1817 boolean thisIsNucleotide = this.isNucleotide();
1818 boolean thatIsProtein = !al.isNucleotide();
1819 if (!thatIsProtein && !thisIsNucleotide)
1821 return AlignmentUtils.alignProteinAsDna(this, al);
1823 else if (thatIsProtein && thisIsNucleotide)
1825 return AlignmentUtils.alignCdsAsProtein(this, al);
1827 return AlignmentUtils.alignAs(this, al);
1831 * Returns the alignment in Fasta format. Behaviour of this method is not
1832 * guaranteed between versions.
1835 public String toString()
1837 return new FastaFile().print(getSequencesArray(), true);
1841 * Returns the set of distinct sequence names. No ordering is guaranteed.
1844 public Set<String> getSequenceNames()
1846 Set<String> names = new HashSet<>();
1847 for (SequenceI seq : getSequences())
1849 names.add(seq.getName());
1855 public boolean hasValidSequence()
1857 boolean hasValidSeq = false;
1858 for (SequenceI seq : getSequences())
1860 if ((seq.getEnd() - seq.getStart()) > 0)
1870 * Update any mappings to 'virtual' sequences to compatible real ones, if
1871 * present in the added sequences. Returns a count of mappings updated.
1877 public int realiseMappings(List<SequenceI> seqs)
1880 for (SequenceI seq : seqs)
1882 for (AlignedCodonFrame mapping : getCodonFrames())
1884 count += mapping.realiseWith(seq);
1891 * Returns the first AlignedCodonFrame that has a mapping between the given
1899 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1901 for (AlignedCodonFrame acf : getCodonFrames())
1903 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1912 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1914 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1915 int startPos = alignmentStartEnd[0];
1916 int endPos = alignmentStartEnd[1];
1918 int[] lowestRange = new int[] { -1, -1 };
1919 int[] higestRange = new int[] { -1, -1 };
1921 for (int[] hiddenCol : hiddenCols)
1923 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1924 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1927 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1929 startPos = alignmentStartEnd[0];
1933 startPos = lowestRange[1] + 1;
1936 if (higestRange[0] == -1 && higestRange[1] == -1)
1938 endPos = alignmentStartEnd[1];
1942 endPos = higestRange[0] - 1;
1944 return new int[] { startPos, endPos };
1948 public void setHiddenColumns(HiddenColumns cols)