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 HiddenColumns hiddenCols;
68 public Hashtable alignmentProperties;
70 private List<AlignedCodonFrame> codonFrameList;
72 private void initAlignment(SequenceI[] seqs)
74 groups = Collections.synchronizedList(new ArrayList<SequenceGroup>());
75 hiddenSequences = new HiddenSequences(this);
76 hiddenCols = new HiddenColumns();
77 codonFrameList = new ArrayList<>();
79 nucleotide = Comparison.isNucleotide(seqs);
81 sequences = Collections.synchronizedList(new ArrayList<SequenceI>());
83 for (int i = 0; i < seqs.length; i++)
85 sequences.add(seqs[i]);
91 * Make a 'copy' alignment - sequences have new copies of features and
92 * annotations, but share the original dataset sequences.
94 public Alignment(AlignmentI al)
96 SequenceI[] seqs = al.getSequencesArray();
97 for (int i = 0; i < seqs.length; i++)
99 seqs[i] = new Sequence(seqs[i]);
105 * Share the same dataset sequence mappings (if any).
107 if (dataset == null && al.getDataset() == null)
109 this.setCodonFrames(al.getCodonFrames());
114 * Make an alignment from an array of Sequences.
118 public Alignment(SequenceI[] seqs)
124 * Make a new alignment from an array of SeqCigars
129 public Alignment(SeqCigar[] alseqs)
131 SequenceI[] seqs = SeqCigar.createAlignmentSequences(alseqs,
132 gapCharacter, new HiddenColumns(), null);
137 * Make a new alignment from an CigarArray JBPNote - can only do this when
138 * compactAlignment does not contain hidden regions. JBPNote - must also check
139 * that compactAlignment resolves to a set of SeqCigars - or construct them
142 * @param compactAlignment
145 public static AlignmentI createAlignment(CigarArray compactAlignment)
149 .getString("error.alignment_cigararray_not_implemented"));
150 // this(compactAlignment.refCigars);
154 public List<SequenceI> getSequences()
160 public List<SequenceI> getSequences(
161 Map<SequenceI, SequenceCollectionI> hiddenReps)
163 // TODO: in jalview 2.8 we don't do anything with hiddenreps - fix design to
169 public SequenceI[] getSequencesArray()
171 if (sequences == null)
175 synchronized (sequences)
177 return sequences.toArray(new SequenceI[sequences.size()]);
182 * Returns a map of lists of sequences keyed by sequence name.
187 public Map<String, List<SequenceI>> getSequencesByName()
189 return AlignmentUtils.getSequencesByName(this);
194 public SequenceI getSequenceAt(int i)
196 synchronized (sequences)
198 if (i > -1 && i < sequences.size())
200 return sequences.get(i);
207 public SequenceI getSequenceAtAbsoluteIndex(int i)
209 SequenceI seq = null;
210 if (getHiddenSequences().getSize() > 0)
212 seq = getHiddenSequences().getHiddenSequence(i);
215 // didn't find the sequence in the hidden sequences, get it from the
217 int index = getHiddenSequences().findIndexWithoutHiddenSeqs(i);
218 seq = getSequenceAt(index);
223 seq = getSequenceAt(i);
229 * Adds a sequence to the alignment. Recalculates maxLength and size. Note
230 * this currently does not recalculate whether or not the alignment is
231 * nucleotide, so mixed alignments may have undefined behaviour.
236 public void addSequence(SequenceI snew)
241 // maintain dataset integrity
242 SequenceI dsseq = snew.getDatasetSequence();
245 // derive new sequence
246 SequenceI adding = snew.deriveSequence();
248 dsseq = snew.getDatasetSequence();
250 if (getDataset().findIndex(dsseq) == -1)
252 getDataset().addSequence(dsseq);
256 if (sequences == null)
258 initAlignment(new SequenceI[] { snew });
262 synchronized (sequences)
267 if (hiddenSequences != null)
269 hiddenSequences.adjustHeightSequenceAdded();
274 public SequenceI replaceSequenceAt(int i, SequenceI snew)
276 synchronized (sequences)
278 if (sequences.size() > i)
280 return sequences.set(i, snew);
286 hiddenSequences.adjustHeightSequenceAdded();
295 * @return DOCUMENT ME!
298 public List<SequenceGroup> getGroups()
304 public void finalize() throws Throwable
306 if (getDataset() != null)
308 getDataset().removeAlignmentRef();
316 * Defensively nulls out references in case this object is not garbage
319 void nullReferences()
325 hiddenSequences = null;
329 * decrement the alignmentRefs counter by one and null references if it goes
334 private void removeAlignmentRef() throws Throwable
336 if (--alignmentRefs == 0)
343 public void deleteSequence(SequenceI s)
345 synchronized (sequences)
347 deleteSequence(findIndex(s));
352 public void deleteSequence(int i)
354 synchronized (sequences)
356 if (i > -1 && i < getHeight())
359 hiddenSequences.adjustHeightSequenceDeleted(i);
365 public void deleteHiddenSequence(int i)
367 synchronized (sequences)
369 if (i > -1 && i < getHeight())
379 * @see jalview.datamodel.AlignmentI#findGroup(jalview.datamodel.SequenceI)
382 public SequenceGroup findGroup(SequenceI seq, int position)
384 synchronized (groups)
386 for (SequenceGroup sg : groups)
388 if (sg.getSequences(null).contains(seq))
390 if (position >= sg.getStartRes() && position <= sg.getEndRes())
404 * jalview.datamodel.AlignmentI#findAllGroups(jalview.datamodel.SequenceI)
407 public SequenceGroup[] findAllGroups(SequenceI s)
409 ArrayList<SequenceGroup> temp = new ArrayList<>();
411 synchronized (groups)
413 int gSize = groups.size();
414 for (int i = 0; i < gSize; i++)
416 SequenceGroup sg = groups.get(i);
417 if (sg == null || sg.getSequences() == null)
419 this.deleteGroup(sg);
424 if (sg.getSequences().contains(s))
430 SequenceGroup[] ret = new SequenceGroup[temp.size()];
431 return temp.toArray(ret);
436 public void addGroup(SequenceGroup sg)
438 synchronized (groups)
440 if (!groups.contains(sg))
442 if (hiddenSequences.getSize() > 0)
444 int i, iSize = sg.getSize();
445 for (i = 0; i < iSize; i++)
447 if (!sequences.contains(sg.getSequenceAt(i)))
449 sg.deleteSequence(sg.getSequenceAt(i), false);
455 if (sg.getSize() < 1)
460 sg.setContext(this, true);
467 * remove any annotation that references gp
470 * (if null, removes all group associated annotation)
472 private void removeAnnotationForGroup(SequenceGroup gp)
474 if (annotations == null || annotations.length == 0)
478 // remove annotation very quickly
479 AlignmentAnnotation[] t, todelete = new AlignmentAnnotation[annotations.length], tokeep = new AlignmentAnnotation[annotations.length];
483 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
485 if (annotations[i].groupRef != null)
487 todelete[p++] = annotations[i];
491 tokeep[k++] = annotations[i];
497 for (i = 0, p = 0, k = 0; i < annotations.length; i++)
499 if (annotations[i].groupRef == gp)
501 todelete[p++] = annotations[i];
505 tokeep[k++] = annotations[i];
511 // clear out the group associated annotation.
512 for (i = 0; i < p; i++)
514 unhookAnnotation(todelete[i]);
517 t = new AlignmentAnnotation[k];
518 for (i = 0; i < k; i++)
527 public void deleteAllGroups()
529 synchronized (groups)
531 if (annotations != null)
533 removeAnnotationForGroup(null);
535 for (SequenceGroup sg : groups)
537 sg.setContext(null, false);
545 public void deleteGroup(SequenceGroup g)
547 synchronized (groups)
549 if (groups.contains(g))
551 removeAnnotationForGroup(g);
553 g.setContext(null, false);
560 public SequenceI findName(String name)
562 return findName(name, false);
568 * @see jalview.datamodel.AlignmentI#findName(java.lang.String, boolean)
571 public SequenceI findName(String token, boolean b)
573 return findName(null, token, b);
579 * @see jalview.datamodel.AlignmentI#findName(SequenceI, java.lang.String,
583 public SequenceI findName(SequenceI startAfter, String token, boolean b)
588 String sqname = null;
589 if (startAfter != null)
591 // try to find the sequence in the alignment
592 boolean matched = false;
593 while (i < sequences.size())
595 if (getSequenceAt(i++) == startAfter)
606 while (i < sequences.size())
608 sq = getSequenceAt(i);
609 sqname = sq.getName();
610 if (sqname.equals(token) // exact match
611 || (b && // allow imperfect matches - case varies
612 (sqname.equalsIgnoreCase(token))))
614 return getSequenceAt(i);
624 public SequenceI[] findSequenceMatch(String name)
626 Vector matches = new Vector();
629 while (i < sequences.size())
631 if (getSequenceAt(i).getName().equals(name))
633 matches.addElement(getSequenceAt(i));
638 SequenceI[] result = new SequenceI[matches.size()];
639 for (i = 0; i < result.length; i++)
641 result[i] = (SequenceI) matches.elementAt(i);
651 * @see jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SequenceI)
654 public int findIndex(SequenceI s)
658 while (i < sequences.size())
660 if (s == getSequenceAt(i))
675 * jalview.datamodel.AlignmentI#findIndex(jalview.datamodel.SearchResults)
678 public int findIndex(SearchResultsI results)
682 while (i < sequences.size())
684 if (results.involvesSequence(getSequenceAt(i)))
695 public int getHeight()
697 return sequences.size();
701 public int getAbsoluteHeight()
703 return sequences.size() + getHiddenSequences().getSize();
707 public int getWidth()
711 for (int i = 0; i < sequences.size(); i++)
713 if (getSequenceAt(i).getLength() > maxLength)
715 maxLength = getSequenceAt(i).getLength();
729 public void setGapCharacter(char gc)
732 synchronized (sequences)
734 for (SequenceI seq : sequences)
736 seq.setSequence(seq.getSequenceAsString().replace('.', gc)
737 .replace('-', gc).replace(' ', gc));
745 * @return DOCUMENT ME!
748 public char getGapCharacter()
756 * @see jalview.datamodel.AlignmentI#isAligned()
759 public boolean isAligned()
761 return isAligned(false);
767 * @see jalview.datamodel.AlignmentI#isAligned(boolean)
770 public boolean isAligned(boolean includeHidden)
772 int width = getWidth();
773 if (hiddenSequences == null || hiddenSequences.getSize() == 0)
775 includeHidden = true; // no hidden sequences to check against.
777 for (int i = 0; i < sequences.size(); i++)
779 if (includeHidden || !hiddenSequences.isHidden(getSequenceAt(i)))
781 if (getSequenceAt(i).getLength() != width)
792 public boolean isHidden(int alignmentIndex)
794 return (getHiddenSequences().getHiddenSequence(alignmentIndex) != null);
798 * Delete all annotations, including auto-calculated if the flag is set true.
799 * Returns true if at least one annotation was deleted, else false.
801 * @param includingAutoCalculated
805 public boolean deleteAllAnnotations(boolean includingAutoCalculated)
807 boolean result = false;
808 for (AlignmentAnnotation alan : getAlignmentAnnotation())
810 if (!alan.autoCalculated || includingAutoCalculated)
812 deleteAnnotation(alan);
822 * @seejalview.datamodel.AlignmentI#deleteAnnotation(jalview.datamodel.
823 * AlignmentAnnotation)
826 public boolean deleteAnnotation(AlignmentAnnotation aa)
828 return deleteAnnotation(aa, true);
832 public boolean deleteAnnotation(AlignmentAnnotation aa, boolean unhook)
836 if (annotations != null)
838 aSize = annotations.length;
846 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize - 1];
848 boolean swap = false;
851 for (int i = 0; i < aSize; i++)
853 if (annotations[i] == aa)
858 if (tIndex < temp.length)
860 temp[tIndex++] = annotations[i];
869 unhookAnnotation(aa);
876 * remove any object references associated with this annotation
880 private void unhookAnnotation(AlignmentAnnotation aa)
882 if (aa.sequenceRef != null)
884 aa.sequenceRef.removeAlignmentAnnotation(aa);
886 if (aa.groupRef != null)
888 // probably need to do more here in the future (post 2.5.0)
896 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
897 * AlignmentAnnotation)
900 public void addAnnotation(AlignmentAnnotation aa)
902 addAnnotation(aa, -1);
908 * @seejalview.datamodel.AlignmentI#addAnnotation(jalview.datamodel.
909 * AlignmentAnnotation, int)
912 public void addAnnotation(AlignmentAnnotation aa, int pos)
914 if (aa.getRNAStruc() != null)
916 hasRNAStructure = true;
920 if (annotations != null)
922 aSize = annotations.length + 1;
925 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
927 if (pos == -1 || pos >= aSize)
929 temp[aSize - 1] = aa;
938 for (i = 0; i < (aSize - 1); i++, p++)
946 temp[p] = annotations[i];
955 public void setAnnotationIndex(AlignmentAnnotation aa, int index)
957 if (aa == null || annotations == null || annotations.length - 1 < index)
962 int aSize = annotations.length;
963 AlignmentAnnotation[] temp = new AlignmentAnnotation[aSize];
967 for (int i = 0; i < aSize; i++)
976 temp[i] = annotations[i];
980 temp[i] = annotations[i - 1];
989 * returns all annotation on the alignment
991 public AlignmentAnnotation[] getAlignmentAnnotation()
997 public boolean isNucleotide()
1003 public boolean hasRNAStructure()
1005 // TODO can it happen that structure is removed from alignment?
1006 return hasRNAStructure;
1010 public void setDataset(AlignmentI data)
1012 if (dataset == null && data == null)
1014 createDatasetAlignment();
1016 else if (dataset == null && data != null)
1020 throw new IllegalArgumentException("Circular dataset reference");
1022 if (!(data instanceof Alignment))
1025 "Implementation Error: jalview.datamodel.Alignment does not yet support other implementations of AlignmentI as its dataset reference");
1027 dataset = (Alignment) data;
1028 for (int i = 0; i < getHeight(); i++)
1030 SequenceI currentSeq = getSequenceAt(i);
1031 SequenceI dsq = currentSeq.getDatasetSequence();
1034 dsq = currentSeq.createDatasetSequence();
1035 dataset.addSequence(dsq);
1039 while (dsq.getDatasetSequence() != null)
1041 dsq = dsq.getDatasetSequence();
1043 if (dataset.findIndex(dsq) == -1)
1045 dataset.addSequence(dsq);
1050 dataset.addAlignmentRef();
1054 * add dataset sequences to seq for currentSeq and any sequences it references
1056 private void resolveAndAddDatasetSeq(SequenceI currentSeq,
1057 Set<SequenceI> seqs, boolean createDatasetSequence)
1059 SequenceI alignedSeq = currentSeq;
1060 if (currentSeq.getDatasetSequence() != null)
1062 currentSeq = currentSeq.getDatasetSequence();
1066 if (createDatasetSequence)
1068 currentSeq = currentSeq.createDatasetSequence();
1071 if (seqs.contains(currentSeq))
1075 List<SequenceI> toProcess = new ArrayList<>();
1076 toProcess.add(currentSeq);
1077 while (toProcess.size() > 0)
1080 SequenceI curDs = toProcess.remove(0);
1081 if (seqs.contains(curDs))
1086 // iterate over database references, making sure we add forward referenced
1088 if (curDs.getDBRefs() != null)
1090 for (DBRefEntry dbr : curDs.getDBRefs())
1092 if (dbr.getMap() != null && dbr.getMap().getTo() != null)
1094 if (dbr.getMap().getTo() == alignedSeq)
1097 * update mapping to be to the newly created dataset sequence
1099 dbr.getMap().setTo(currentSeq);
1101 if (dbr.getMap().getTo().getDatasetSequence() != null)
1104 "Implementation error: Map.getTo() for dbref " + dbr
1105 + " from " + curDs.getName()
1106 + " is not a dataset sequence.");
1108 // we recurse to add all forward references to dataset sequences via
1110 toProcess.add(dbr.getMap().getTo());
1118 * Creates a new dataset for this alignment. Can only be done once - if
1119 * dataset is not null this will not be performed.
1121 public void createDatasetAlignment()
1123 if (dataset != null)
1127 // try to avoid using SequenceI.equals at this stage, it will be expensive
1128 Set<SequenceI> seqs = new LinkedIdentityHashSet<>();
1130 for (int i = 0; i < getHeight(); i++)
1132 SequenceI currentSeq = getSequenceAt(i);
1133 resolveAndAddDatasetSeq(currentSeq, seqs, true);
1136 // verify all mappings are in dataset
1137 for (AlignedCodonFrame cf : codonFrameList)
1139 for (SequenceToSequenceMapping ssm : cf.getMappings())
1141 if (!seqs.contains(ssm.getFromSeq()))
1143 resolveAndAddDatasetSeq(ssm.getFromSeq(), seqs, false);
1145 if (!seqs.contains(ssm.getMapping().getTo()))
1147 resolveAndAddDatasetSeq(ssm.getMapping().getTo(), seqs, false);
1151 // finally construct dataset
1152 dataset = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
1153 // move mappings to the dataset alignment
1154 dataset.codonFrameList = this.codonFrameList;
1155 this.codonFrameList = null;
1159 * reference count for number of alignments referencing this one.
1161 int alignmentRefs = 0;
1164 * increase reference count to this alignment.
1166 private void addAlignmentRef()
1172 public Alignment getDataset()
1178 public boolean padGaps()
1180 boolean modified = false;
1182 // Remove excess gaps from the end of alignment
1186 for (int i = 0; i < sequences.size(); i++)
1188 current = getSequenceAt(i);
1189 for (int j = current.getLength(); j > maxLength; j--)
1192 && !jalview.util.Comparison.isGap(current.getCharAt(j)))
1203 for (int i = 0; i < sequences.size(); i++)
1205 current = getSequenceAt(i);
1206 cLength = current.getLength();
1208 if (cLength < maxLength)
1210 current.insertCharAt(cLength, maxLength - cLength, gapCharacter);
1213 else if (current.getLength() > maxLength)
1215 current.deleteChars(maxLength, current.getLength());
1222 * Justify the sequences to the left or right by deleting and inserting gaps
1223 * before the initial residue or after the terminal residue
1226 * true if alignment padded to right, false to justify to left
1227 * @return true if alignment was changed
1230 public boolean justify(boolean right)
1232 boolean modified = false;
1234 // Remove excess gaps from the end of alignment
1236 int ends[] = new int[sequences.size() * 2];
1238 for (int i = 0; i < sequences.size(); i++)
1240 current = getSequenceAt(i);
1241 // This should really be a sequence method
1242 ends[i * 2] = current.findIndex(current.getStart());
1243 ends[i * 2 + 1] = current.findIndex(current.getStart()
1244 + current.getLength());
1245 boolean hitres = false;
1246 for (int j = 0, rs = 0, ssiz = current.getLength(); j < ssiz; j++)
1248 if (!jalview.util.Comparison.isGap(current.getCharAt(j)))
1257 ends[i * 2 + 1] = j;
1258 if (j - ends[i * 2] > maxLength)
1260 maxLength = j - ends[i * 2];
1268 // now edit the flanking gaps to justify to either left or right
1269 int cLength, extent, diff;
1270 for (int i = 0; i < sequences.size(); i++)
1272 current = getSequenceAt(i);
1274 cLength = 1 + ends[i * 2 + 1] - ends[i * 2];
1275 diff = maxLength - cLength; // number of gaps to indent
1276 extent = current.getLength();
1280 if (extent > ends[i * 2 + 1])
1282 current.deleteChars(ends[i * 2 + 1] + 1, extent);
1285 if (ends[i * 2] > diff)
1287 current.deleteChars(0, ends[i * 2] - diff);
1292 if (ends[i * 2] < diff)
1294 current.insertCharAt(0, diff - ends[i * 2], gapCharacter);
1302 if (ends[i * 2] > 0)
1304 current.deleteChars(0, ends[i * 2]);
1306 ends[i * 2 + 1] -= ends[i * 2];
1307 extent -= ends[i * 2];
1309 if (extent > maxLength)
1311 current.deleteChars(maxLength + 1, extent);
1316 if (extent < maxLength)
1318 current.insertCharAt(extent, maxLength - extent, gapCharacter);
1328 public HiddenSequences getHiddenSequences()
1330 return hiddenSequences;
1334 public HiddenColumns getHiddenColumns()
1340 public CigarArray getCompactAlignment()
1342 synchronized (sequences)
1344 SeqCigar alseqs[] = new SeqCigar[sequences.size()];
1346 for (SequenceI seq : sequences)
1348 alseqs[i++] = new SeqCigar(seq);
1350 CigarArray cal = new CigarArray(alseqs);
1351 cal.addOperation(CigarArray.M, getWidth());
1357 public void setProperty(Object key, Object value)
1359 if (alignmentProperties == null)
1361 alignmentProperties = new Hashtable();
1364 alignmentProperties.put(key, value);
1368 public Object getProperty(Object key)
1370 if (alignmentProperties != null)
1372 return alignmentProperties.get(key);
1381 public Hashtable getProperties()
1383 return alignmentProperties;
1387 * Adds the given mapping to the stored set. Note this may be held on the
1388 * dataset alignment.
1391 public void addCodonFrame(AlignedCodonFrame codons)
1393 List<AlignedCodonFrame> acfs = getCodonFrames();
1394 if (codons != null && acfs != null && !acfs.contains(codons))
1404 * jalview.datamodel.AlignmentI#getCodonFrame(jalview.datamodel.SequenceI)
1407 public List<AlignedCodonFrame> getCodonFrame(SequenceI seq)
1413 List<AlignedCodonFrame> cframes = new ArrayList<>();
1414 for (AlignedCodonFrame acf : getCodonFrames())
1416 if (acf.involvesSequence(seq))
1425 * Sets the codon frame mappings (replacing any existing mappings). Note the
1426 * mappings are set on the dataset alignment instead if there is one.
1428 * @see jalview.datamodel.AlignmentI#setCodonFrames()
1431 public void setCodonFrames(List<AlignedCodonFrame> acfs)
1433 if (dataset != null)
1435 dataset.setCodonFrames(acfs);
1439 this.codonFrameList = acfs;
1444 * Returns the set of codon frame mappings. Any changes to the returned set
1445 * will affect the alignment. The mappings are held on (and read from) the
1446 * dataset alignment if there is one.
1448 * @see jalview.datamodel.AlignmentI#getCodonFrames()
1451 public List<AlignedCodonFrame> getCodonFrames()
1453 // TODO: Fix this method to fix failing AlignedCodonFrame tests
1454 // this behaviour is currently incorrect. method should return codon frames
1455 // for just the alignment,
1456 // selected from dataset
1457 return dataset != null ? dataset.getCodonFrames() : codonFrameList;
1461 * Removes the given mapping from the stored set. Note that the mappings are
1462 * held on the dataset alignment if there is one.
1465 public boolean removeCodonFrame(AlignedCodonFrame codons)
1467 List<AlignedCodonFrame> acfs = getCodonFrames();
1468 if (codons == null || acfs == null)
1472 return acfs.remove(codons);
1476 public void append(AlignmentI toappend)
1478 // TODO JAL-1270 needs test coverage
1479 // currently tested for use in jalview.gui.SequenceFetcher
1480 boolean samegap = toappend.getGapCharacter() == getGapCharacter();
1481 char oldc = toappend.getGapCharacter();
1482 boolean hashidden = toappend.getHiddenSequences() != null
1483 && toappend.getHiddenSequences().hiddenSequences != null;
1484 // get all sequences including any hidden ones
1485 List<SequenceI> sqs = (hashidden) ? toappend.getHiddenSequences()
1486 .getFullAlignment().getSequences() : toappend.getSequences();
1489 // avoid self append deadlock by
1490 List<SequenceI> toappendsq = new ArrayList<>();
1493 for (SequenceI addedsq : sqs)
1497 char[] oldseq = addedsq.getSequence();
1498 for (int c = 0; c < oldseq.length; c++)
1500 if (oldseq[c] == oldc)
1502 oldseq[c] = gapCharacter;
1506 toappendsq.add(addedsq);
1509 for (SequenceI addedsq : toappendsq)
1511 addSequence(addedsq);
1514 AlignmentAnnotation[] alan = toappend.getAlignmentAnnotation();
1515 for (int a = 0; alan != null && a < alan.length; a++)
1517 addAnnotation(alan[a]);
1521 getCodonFrames().addAll(toappend.getCodonFrames());
1523 List<SequenceGroup> sg = toappend.getGroups();
1526 for (SequenceGroup _sg : sg)
1531 if (toappend.getHiddenSequences() != null)
1533 HiddenSequences hs = toappend.getHiddenSequences();
1534 if (hiddenSequences == null)
1536 hiddenSequences = new HiddenSequences(this);
1538 if (hs.hiddenSequences != null)
1540 for (int s = 0; s < hs.hiddenSequences.length; s++)
1542 // hide the newly appended sequence in the alignment
1543 if (hs.hiddenSequences[s] != null)
1545 hiddenSequences.hideSequence(hs.hiddenSequences[s]);
1550 if (toappend.getProperties() != null)
1552 // we really can't do very much here - just try to concatenate strings
1553 // where property collisions occur.
1554 Enumeration key = toappend.getProperties().keys();
1555 while (key.hasMoreElements())
1557 Object k = key.nextElement();
1558 Object ourval = this.getProperty(k);
1559 Object toapprop = toappend.getProperty(k);
1562 if (ourval.getClass().equals(toapprop.getClass())
1563 && !ourval.equals(toapprop))
1565 if (ourval instanceof String)
1568 this.setProperty(k, ((String) ourval) + "; "
1569 + ((String) toapprop));
1573 if (ourval instanceof Vector)
1576 Enumeration theirv = ((Vector) toapprop).elements();
1577 while (theirv.hasMoreElements())
1579 ((Vector) ourval).addElement(theirv);
1587 // just add new property directly
1588 setProperty(k, toapprop);
1596 public AlignmentAnnotation findOrCreateAnnotation(String name,
1597 String calcId, boolean autoCalc, SequenceI seqRef,
1598 SequenceGroup groupRef)
1600 if (annotations != null)
1602 for (AlignmentAnnotation annot : getAlignmentAnnotation())
1604 if (annot.autoCalculated == autoCalc && (name.equals(annot.label))
1605 && (calcId == null || annot.getCalcId().equals(calcId))
1606 && annot.sequenceRef == seqRef
1607 && annot.groupRef == groupRef)
1613 AlignmentAnnotation annot = new AlignmentAnnotation(name, name,
1614 new Annotation[1], 0f, 0f, AlignmentAnnotation.BAR_GRAPH);
1615 annot.hasText = false;
1616 annot.setCalcId(new String(calcId));
1617 annot.autoCalculated = autoCalc;
1620 annot.setSequenceRef(seqRef);
1622 annot.groupRef = groupRef;
1623 addAnnotation(annot);
1629 public Iterable<AlignmentAnnotation> findAnnotation(String calcId)
1631 List<AlignmentAnnotation> aa = new ArrayList<>();
1632 AlignmentAnnotation[] alignmentAnnotation = getAlignmentAnnotation();
1633 if (alignmentAnnotation != null)
1635 for (AlignmentAnnotation a : alignmentAnnotation)
1637 if (a.getCalcId() == calcId
1638 || (a.getCalcId() != null && calcId != null && a
1639 .getCalcId().equals(calcId)))
1649 public Iterable<AlignmentAnnotation> findAnnotations(SequenceI seq,
1650 String calcId, String label)
1652 ArrayList<AlignmentAnnotation> aa = new ArrayList<>();
1653 for (AlignmentAnnotation ann : getAlignmentAnnotation())
1655 if ((calcId == null || (ann.getCalcId() != null && ann.getCalcId()
1657 && (seq == null || (ann.sequenceRef != null && ann.sequenceRef == seq))
1658 && (label == null || (ann.label != null && ann.label
1668 public void moveSelectedSequencesByOne(SequenceGroup sg,
1669 Map<SequenceI, SequenceCollectionI> map, boolean up)
1671 synchronized (sequences)
1676 for (int i = 1, iSize = sequences.size(); i < iSize; i++)
1678 SequenceI seq = sequences.get(i);
1679 if (!sg.getSequences(map).contains(seq))
1684 SequenceI temp = sequences.get(i - 1);
1685 if (sg.getSequences(null).contains(temp))
1690 sequences.set(i, temp);
1691 sequences.set(i - 1, seq);
1696 for (int i = sequences.size() - 2; i > -1; i--)
1698 SequenceI seq = sequences.get(i);
1699 if (!sg.getSequences(map).contains(seq))
1704 SequenceI temp = sequences.get(i + 1);
1705 if (sg.getSequences(map).contains(temp))
1710 sequences.set(i, temp);
1711 sequences.set(i + 1, seq);
1719 public void validateAnnotation(AlignmentAnnotation alignmentAnnotation)
1721 alignmentAnnotation.validateRangeAndDisplay();
1722 if (isNucleotide() && alignmentAnnotation.isValidStruc())
1724 hasRNAStructure = true;
1728 private SequenceI seqrep = null;
1732 * @return the representative sequence for this group
1735 public SequenceI getSeqrep()
1741 * set the representative sequence for this group. Note - this affects the
1742 * interpretation of the Hidereps attribute.
1745 * the seqrep to set (null means no sequence representative)
1748 public void setSeqrep(SequenceI seqrep)
1750 this.seqrep = seqrep;
1755 * @return true if group has a sequence representative
1758 public boolean hasSeqrep()
1760 return seqrep != null;
1764 public int getEndRes()
1766 return getWidth() - 1;
1770 public int getStartRes()
1776 * In the case of AlignmentI - returns the dataset for the alignment, if set
1779 * @see jalview.datamodel.AnnotatedCollectionI#getContext()
1782 public AnnotatedCollectionI getContext()
1788 * Align this alignment like the given (mapped) one.
1791 public int alignAs(AlignmentI al)
1794 * Currently retains unmapped gaps (in introns), regaps mapped regions
1797 return alignAs(al, false, true);
1801 * Align this alignment 'the same as' the given one. Mapped sequences only are
1802 * realigned. If both of the same type (nucleotide/protein) then align both
1803 * identically. If this is nucleotide and the other is protein, make 3 gaps
1804 * for each gap in the protein sequences. If this is protein and the other is
1805 * nucleotide, insert a gap for each 3 gaps (or part thereof) between
1806 * nucleotide bases. If this is protein and the other is nucleotide, gaps
1807 * protein to match the relative ordering of codons in the nucleotide.
1809 * Parameters control whether gaps in exon (mapped) and intron (unmapped)
1810 * regions are preserved. Gaps that connect introns to exons are treated
1811 * conservatively, i.e. only preserved if both intron and exon gaps are
1812 * preserved. TODO: check caveats below where the implementation fails
1815 * - must have same dataset, and sequences in al must have equivalent
1816 * dataset sequence and start/end bounds under given mapping
1817 * @param preserveMappedGaps
1818 * if true, gaps within and between mapped codons are preserved
1819 * @param preserveUnmappedGaps
1820 * if true, gaps within and between unmapped codons are preserved
1823 public int alignAs(AlignmentI al, boolean preserveMappedGaps,
1824 boolean preserveUnmappedGaps)
1826 // TODO should this method signature be the one in the interface?
1827 // JBPComment - yes - neither flag is used, so should be deleted.
1828 boolean thisIsNucleotide = this.isNucleotide();
1829 boolean thatIsProtein = !al.isNucleotide();
1830 if (!thatIsProtein && !thisIsNucleotide)
1832 return AlignmentUtils.alignProteinAsDna(this, al);
1834 else if (thatIsProtein && thisIsNucleotide)
1836 return AlignmentUtils.alignCdsAsProtein(this, al);
1838 return AlignmentUtils.alignAs(this, al);
1842 * Returns the alignment in Fasta format. Behaviour of this method is not
1843 * guaranteed between versions.
1846 public String toString()
1848 return new FastaFile().print(getSequencesArray(), true);
1852 * Returns the set of distinct sequence names. No ordering is guaranteed.
1855 public Set<String> getSequenceNames()
1857 Set<String> names = new HashSet<>();
1858 for (SequenceI seq : getSequences())
1860 names.add(seq.getName());
1866 public boolean hasValidSequence()
1868 boolean hasValidSeq = false;
1869 for (SequenceI seq : getSequences())
1871 if ((seq.getEnd() - seq.getStart()) > 0)
1881 * Update any mappings to 'virtual' sequences to compatible real ones, if
1882 * present in the added sequences. Returns a count of mappings updated.
1888 public int realiseMappings(List<SequenceI> seqs)
1891 for (SequenceI seq : seqs)
1893 for (AlignedCodonFrame mapping : getCodonFrames())
1895 count += mapping.realiseWith(seq);
1902 * Returns the first AlignedCodonFrame that has a mapping between the given
1910 public AlignedCodonFrame getMapping(SequenceI mapFrom, SequenceI mapTo)
1912 for (AlignedCodonFrame acf : getCodonFrames())
1914 if (acf.getAaForDnaSeq(mapFrom) == mapTo)
1923 public int[] getVisibleStartAndEndIndex(List<int[]> hiddenCols)
1925 int[] alignmentStartEnd = new int[] { 0, getWidth() - 1 };
1926 int startPos = alignmentStartEnd[0];
1927 int endPos = alignmentStartEnd[1];
1929 int[] lowestRange = new int[] { -1, -1 };
1930 int[] higestRange = new int[] { -1, -1 };
1932 for (int[] hiddenCol : hiddenCols)
1934 lowestRange = (hiddenCol[0] <= startPos) ? hiddenCol : lowestRange;
1935 higestRange = (hiddenCol[1] >= endPos) ? hiddenCol : higestRange;
1938 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1940 startPos = alignmentStartEnd[0];
1944 startPos = lowestRange[1] + 1;
1947 if (higestRange[0] == -1 && higestRange[1] == -1)
1949 endPos = alignmentStartEnd[1];
1953 endPos = higestRange[0] - 1;
1955 return new int[] { startPos, endPos };
1959 public void setHiddenColumns(HiddenColumns cols)
1965 public Map<Integer, SequenceI> getHMMConsensusSequences(boolean remove)
1967 Map<Integer, SequenceI> seqs = new HashMap<>();
1969 for (SequenceI seq : sequences)
1971 if (seq.isHMMConsensusSequence())
1973 seqs.put(position, seq);
1976 sequences.set(position, null);
1982 boolean endReached = false;
1986 if (sequences.get(pos) == null)
1988 sequences.remove(pos);
1994 if (pos >= sequences.size())
2004 public List<SequenceI> getHMMConsensusSequences()
2006 List<SequenceI> seqs = new ArrayList<>();
2007 for (SequenceI seq : sequences)
2009 if (seq.isHMMConsensusSequence())