2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.analysis;
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceI;
27 import jalview.schemes.ResidueProperties;
28 import jalview.util.MapList;
30 import java.util.ArrayList;
31 import java.util.LinkedHashMap;
32 import java.util.List;
37 * grab bag of useful alignment manipulation operations Expect these to be
38 * refactored elsewhere at some point.
43 public class AlignmentUtils
47 * Represents the 3 possible results of trying to map one alignment to
50 public enum MappingResult
52 Mapped, NotMapped, AlreadyMapped
56 * given an existing alignment, create a new alignment including all, or up to
57 * flankSize additional symbols from each sequence's dataset sequence
63 public static AlignmentI expandContext(AlignmentI core, int flankSize)
65 List<SequenceI> sq = new ArrayList<SequenceI>();
67 for (SequenceI s : core.getSequences())
69 SequenceI newSeq = s.deriveSequence();
70 if (newSeq.getStart() > maxoffset
71 && newSeq.getDatasetSequence().getStart() < s.getStart())
73 maxoffset = newSeq.getStart();
79 maxoffset = flankSize;
81 // now add offset to create a new expanded alignment
82 for (SequenceI s : sq)
85 while (ds.getDatasetSequence() != null)
87 ds = ds.getDatasetSequence();
89 int s_end = s.findPosition(s.getStart() + s.getLength());
90 // find available flanking residues for sequence
91 int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
94 // build new flanked sequence
96 // compute gap padding to start of flanking sequence
97 int offset = maxoffset - ustream_ds;
99 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
102 if (flankSize < ustream_ds)
104 // take up to flankSize residues
105 offset = maxoffset - flankSize;
106 ustream_ds = flankSize;
108 if (flankSize < dstream_ds)
110 dstream_ds = flankSize;
113 char[] upstream = new String(ds.getSequence(s.getStart() - 1
114 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
115 char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
116 + dstream_ds)).toLowerCase().toCharArray();
117 char[] coreseq = s.getSequence();
118 char[] nseq = new char[offset + upstream.length + downstream.length
120 char c = core.getGapCharacter();
121 // TODO could lowercase the flanking regions
123 for (; p < offset; p++)
127 // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
128 // new String(downstream).toLowerCase());
129 System.arraycopy(upstream, 0, nseq, p, upstream.length);
130 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
132 System.arraycopy(downstream, 0, nseq, p + coreseq.length
133 + upstream.length, downstream.length);
134 s.setSequence(new String(nseq));
135 s.setStart(s.getStart() - ustream_ds);
136 s.setEnd(s_end + downstream.length);
138 AlignmentI newAl = new jalview.datamodel.Alignment(
139 sq.toArray(new SequenceI[0]));
140 for (SequenceI s : sq)
142 if (s.getAnnotation() != null)
144 for (AlignmentAnnotation aa : s.getAnnotation())
146 newAl.addAnnotation(aa);
150 newAl.setDataset(core.getDataset());
155 * Returns the index (zero-based position) of a sequence in an alignment, or
162 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
166 for (SequenceI alSeq : al.getSequences())
179 * Returns a map of lists of sequences in the alignment, keyed by sequence
180 * name. For use in mapping between different alignment views of the same
183 * @see jalview.datamodel.AlignmentI#getSequencesByName()
185 public static Map<String, List<SequenceI>> getSequencesByName(
188 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
189 for (SequenceI seq : al.getSequences())
191 String name = seq.getName();
194 List<SequenceI> seqs = theMap.get(name);
197 seqs = new ArrayList<SequenceI>();
198 theMap.put(name, seqs);
207 * Build mapping of protein to cDNA alignment. Mappings are made between
208 * sequences which have the same name and compatible lengths. Has a 3-valued
209 * result: either Mapped (at least one sequence mapping was created),
210 * AlreadyMapped (all possible sequence mappings already exist), or NotMapped
211 * (no possible sequence mappings exist).
213 * @param proteinAlignment
214 * @param cdnaAlignment
217 public static MappingResult mapProteinToCdna(
218 final AlignmentI proteinAlignment,
219 final AlignmentI cdnaAlignment)
221 boolean mappingPossible = false;
222 boolean mappingPerformed = false;
224 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
227 * Build a look-up of cDNA sequences by name, for matching purposes.
229 Map<String, List<SequenceI>> cdnaSeqs = cdnaAlignment
230 .getSequencesByName();
232 for (SequenceI aaSeq : thisSeqs)
234 AlignedCodonFrame acf = new AlignedCodonFrame();
235 List<SequenceI> candidates = cdnaSeqs.get(aaSeq.getName());
236 if (candidates == null)
239 * No cDNA sequence with matching name, so no mapping possible for this
244 mappingPossible = true;
245 for (SequenceI cdnaSeq : candidates)
247 if (!mappingExists(proteinAlignment.getCodonFrames(),
248 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
250 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
253 acf.addMap(cdnaSeq, aaSeq, map);
254 mappingPerformed = true;
258 proteinAlignment.addCodonFrame(acf);
262 * If at least one mapping was possible but none was done, then the
263 * alignments are already as mapped as they can be.
265 if (mappingPossible && !mappingPerformed)
267 return MappingResult.AlreadyMapped;
271 return mappingPerformed ? MappingResult.Mapped
272 : MappingResult.NotMapped;
277 * Answers true if the mappings include one between the given (dataset)
280 public static boolean mappingExists(Set<AlignedCodonFrame> set,
281 SequenceI aaSeq, SequenceI cdnaSeq)
285 for (AlignedCodonFrame acf : set)
287 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
297 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
298 * must be three times the length of the protein, possibly after ignoring
299 * start and/or stop codons. Returns null if no mapping is determined.
305 public static MapList mapProteinToCdna(SequenceI proteinSeq,
308 String aaSeqString = proteinSeq.getDatasetSequence()
309 .getSequenceAsString();
310 String cdnaSeqString = cdnaSeq.getDatasetSequence()
311 .getSequenceAsString();
312 if (aaSeqString == null || cdnaSeqString == null)
317 final int mappedLength = 3 * aaSeqString.length();
318 int cdnaLength = cdnaSeqString.length();
320 int cdnaEnd = cdnaLength;
321 final int proteinStart = 1;
322 final int proteinEnd = aaSeqString.length();
325 * If lengths don't match, try ignoring stop codon.
327 if (cdnaLength != mappedLength)
329 for (Object stop : ResidueProperties.STOP)
331 if (cdnaSeqString.toUpperCase().endsWith((String) stop))
341 * If lengths still don't match, try ignoring start codon.
343 if (cdnaLength != mappedLength
344 && cdnaSeqString.toUpperCase().startsWith(
345 ResidueProperties.START))
351 if (cdnaLength == mappedLength)
353 MapList map = new MapList(new int[]
354 { cdnaStart, cdnaEnd }, new int[]
355 { proteinStart, proteinEnd }, 3, 1);
365 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
366 * currently assumes that we are aligning cDNA to match protein.
369 * the sequence to be realigned
371 * the alignment whose sequence alignment is to be 'copied'
373 * character string represent a gap in the realigned sequence
374 * @param preserveUnmappedGaps
375 * @param preserveMappedGaps
376 * @return true if the sequence was realigned, false if it could not be
378 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
379 String gap, boolean preserveMappedGaps,
380 boolean preserveUnmappedGaps)
383 * Get any mappings from the source alignment to the target (dataset) sequence.
385 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
386 // all mappings. Would it help to constrain this?
387 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
388 if (mappings == null)
394 * Locate the aligned source sequence whose dataset sequence is mapped. We
395 * just take the first match here (as we can't align cDNA like more than one
398 SequenceI alignFrom = null;
399 AlignedCodonFrame mapping = null;
400 for (AlignedCodonFrame mp : mappings)
402 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
403 if (alignFrom != null)
410 if (alignFrom == null)
414 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
415 preserveMappedGaps, preserveUnmappedGaps);
420 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
421 * match residues and codons. Flags control whether existing gaps in unmapped
422 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
423 * and exon are only retained if both flags are set.
430 * @param preserveUnmappedGaps
431 * @param preserveMappedGaps
433 public static void alignSequenceAs(SequenceI alignTo,
435 AlignedCodonFrame mapping, String myGap, char sourceGap,
436 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
438 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
439 final char[] thisSeq = alignTo.getSequence();
440 final char[] thatAligned = alignFrom.getSequence();
441 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
443 // aligned and dataset sequence positions, all base zero
447 int basesWritten = 0;
448 char myGapChar = myGap.charAt(0);
449 int ratio = myGap.length();
452 * Traverse the aligned protein sequence.
454 int sourceGapMappedLength = 0;
455 boolean inExon = false;
456 for (char sourceChar : thatAligned)
458 if (sourceChar == sourceGap)
460 sourceGapMappedLength += ratio;
465 * Found a residue. Locate its mapped codon (start) position.
468 // Note mapping positions are base 1, our sequence positions base 0
469 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
471 if (mappedPos == null)
474 * Abort realignment if unmapped protein. Or could ignore it??
476 System.err.println("Can't align: no codon mapping to residue "
477 + sourceDsPos + "(" + sourceChar + ")");
481 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
482 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
483 StringBuilder trailingCopiedGap = new StringBuilder();
486 * Copy dna sequence up to and including this codon. Optionally, include
487 * gaps before the codon starts (in introns) and/or after the codon starts
490 * Note this only works for 'linear' splicing, not reverse or interleaved.
491 * But then 'align dna as protein' doesn't make much sense otherwise.
493 int intronLength = 0;
494 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
496 final char c = thisSeq[thisSeqPos++];
501 if (basesWritten < mappedCodonStart)
504 * Found an unmapped (intron) base. First add in any preceding gaps
507 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
509 thisAligned.append(trailingCopiedGap.toString());
510 intronLength += trailingCopiedGap.length();
511 trailingCopiedGap = new StringBuilder();
518 final boolean startOfCodon = basesWritten == mappedCodonStart;
519 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
520 preserveUnmappedGaps, sourceGapMappedLength, inExon,
521 trailingCopiedGap.length(), intronLength, startOfCodon);
522 for (int i = 0; i < gapsToAdd; i++)
524 thisAligned.append(myGapChar);
526 sourceGapMappedLength = 0;
529 thisAligned.append(c);
530 trailingCopiedGap = new StringBuilder();
534 if (inExon && preserveMappedGaps)
536 trailingCopiedGap.append(myGapChar);
538 else if (!inExon && preserveUnmappedGaps)
540 trailingCopiedGap.append(myGapChar);
547 * At end of protein sequence. Copy any remaining dna sequence, optionally
548 * including (intron) gaps. We do not copy trailing gaps in protein.
550 while (thisSeqPos < thisSeq.length)
552 final char c = thisSeq[thisSeqPos++];
553 if (c != myGapChar || preserveUnmappedGaps)
555 thisAligned.append(c);
560 * All done aligning, set the aligned sequence.
562 alignTo.setSequence(new String(thisAligned));
566 * Helper method to work out how many gaps to insert when realigning.
568 * @param preserveMappedGaps
569 * @param preserveUnmappedGaps
570 * @param sourceGapMappedLength
572 * @param trailingCopiedGap
573 * @param intronLength
574 * @param startOfCodon
577 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
578 boolean preserveUnmappedGaps, int sourceGapMappedLength,
579 boolean inExon, int trailingGapLength,
580 int intronLength, final boolean startOfCodon)
586 * Reached start of codon. Ignore trailing gaps in intron unless we are
587 * preserving gaps in both exon and intron. Ignore them anyway if the
588 * protein alignment introduces a gap at least as large as the intronic
591 if (inExon && !preserveMappedGaps)
593 trailingGapLength = 0;
595 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
597 trailingGapLength = 0;
601 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
605 if (intronLength + trailingGapLength <= sourceGapMappedLength)
607 gapsToAdd = sourceGapMappedLength - intronLength;
611 gapsToAdd = Math.min(intronLength + trailingGapLength
612 - sourceGapMappedLength, trailingGapLength);
619 * second or third base of codon; check for any gaps in dna
621 if (!preserveMappedGaps)
623 trailingGapLength = 0;
625 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);