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;
36 * grab bag of useful alignment manipulation operations Expect these to be
37 * refactored elsewhere at some point.
42 public class AlignmentUtils
46 * Represents the 3 possible results of trying to map one alignment to
49 public enum MappingResult
51 Mapped, NotMapped, AlreadyMapped
55 * given an existing alignment, create a new alignment including all, or up to
56 * flankSize additional symbols from each sequence's dataset sequence
62 public static AlignmentI expandContext(AlignmentI core, int flankSize)
64 List<SequenceI> sq = new ArrayList<SequenceI>();
66 for (SequenceI s : core.getSequences())
68 SequenceI newSeq = s.deriveSequence();
69 if (newSeq.getStart() > maxoffset
70 && newSeq.getDatasetSequence().getStart() < s.getStart())
72 maxoffset = newSeq.getStart();
78 maxoffset = flankSize;
80 // now add offset to create a new expanded alignment
81 for (SequenceI s : sq)
84 while (ds.getDatasetSequence() != null)
86 ds = ds.getDatasetSequence();
88 int s_end = s.findPosition(s.getStart() + s.getLength());
89 // find available flanking residues for sequence
90 int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
93 // build new flanked sequence
95 // compute gap padding to start of flanking sequence
96 int offset = maxoffset - ustream_ds;
98 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
101 if (flankSize < ustream_ds)
103 // take up to flankSize residues
104 offset = maxoffset - flankSize;
105 ustream_ds = flankSize;
107 if (flankSize < dstream_ds)
109 dstream_ds = flankSize;
112 char[] upstream = new String(ds.getSequence(s.getStart() - 1
113 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
114 char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
115 + dstream_ds)).toLowerCase().toCharArray();
116 char[] coreseq = s.getSequence();
117 char[] nseq = new char[offset + upstream.length + downstream.length
119 char c = core.getGapCharacter();
120 // TODO could lowercase the flanking regions
122 for (; p < offset; p++)
126 // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
127 // new String(downstream).toLowerCase());
128 System.arraycopy(upstream, 0, nseq, p, upstream.length);
129 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
131 System.arraycopy(downstream, 0, nseq, p + coreseq.length
132 + upstream.length, downstream.length);
133 s.setSequence(new String(nseq));
134 s.setStart(s.getStart() - ustream_ds);
135 s.setEnd(s_end + downstream.length);
137 AlignmentI newAl = new jalview.datamodel.Alignment(
138 sq.toArray(new SequenceI[0]));
139 for (SequenceI s : sq)
141 if (s.getAnnotation() != null)
143 for (AlignmentAnnotation aa : s.getAnnotation())
145 newAl.addAnnotation(aa);
149 newAl.setDataset(core.getDataset());
154 * Returns the index (zero-based position) of a sequence in an alignment, or
161 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
165 for (SequenceI alSeq : al.getSequences())
178 * Returns a map of lists of sequences in the alignment, keyed by sequence
179 * name. For use in mapping between different alignment views of the same
182 * @see jalview.datamodel.AlignmentI#getSequencesByName()
184 public static Map<String, List<SequenceI>> getSequencesByName(
187 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
188 for (SequenceI seq : al.getSequences())
190 String name = seq.getName();
193 List<SequenceI> seqs = theMap.get(name);
196 seqs = new ArrayList<SequenceI>();
197 theMap.put(name, seqs);
206 * Build mapping of protein to cDNA alignment. Mappings are made between
207 * sequences which have the same name and compatible lengths. Has a 3-valued
208 * result: either Mapped (at least one sequence mapping was created),
209 * AlreadyMapped (all possible sequence mappings already exist), or NotMapped
210 * (no possible sequence mappings exist).
212 * @param proteinAlignment
213 * @param cdnaAlignment
216 public static MappingResult mapProteinToCdna(
217 final AlignmentI proteinAlignment,
218 final AlignmentI cdnaAlignment)
220 boolean mappingPossible = false;
221 boolean mappingPerformed = false;
223 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
226 * Build a look-up of cDNA sequences by name, for matching purposes.
228 Map<String, List<SequenceI>> cdnaSeqs = cdnaAlignment
229 .getSequencesByName();
231 for (SequenceI aaSeq : thisSeqs)
233 AlignedCodonFrame acf = new AlignedCodonFrame();
234 List<SequenceI> candidates = cdnaSeqs.get(aaSeq.getName());
235 if (candidates == null)
238 * No cDNA sequence with matching name, so no mapping possible for this
243 mappingPossible = true;
244 for (SequenceI cdnaSeq : candidates)
246 if (!mappingExists(proteinAlignment.getCodonFrames(),
247 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
249 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
252 acf.addMap(cdnaSeq, aaSeq, map);
253 mappingPerformed = true;
257 proteinAlignment.addCodonFrame(acf);
261 * If at least one mapping was possible but none was done, then the
262 * alignments are already as mapped as they can be.
264 if (mappingPossible && !mappingPerformed)
266 return MappingResult.AlreadyMapped;
270 return mappingPerformed ? MappingResult.Mapped
271 : MappingResult.NotMapped;
276 * Answers true if the mappings include one between the given (dataset)
279 public static boolean mappingExists(AlignedCodonFrame[] codonFrames,
280 SequenceI aaSeq, SequenceI cdnaSeq)
282 if (codonFrames != null)
284 for (AlignedCodonFrame acf : codonFrames)
286 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
296 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
297 * must be three times the length of the protein, possibly after ignoring
298 * start and/or stop codons. Returns null if no mapping is determined.
304 public static MapList mapProteinToCdna(SequenceI proteinSeq,
307 String aaSeqString = proteinSeq.getDatasetSequence()
308 .getSequenceAsString();
309 String cdnaSeqString = cdnaSeq.getDatasetSequence()
310 .getSequenceAsString();
311 if (aaSeqString == null || cdnaSeqString == null)
316 final int mappedLength = 3 * aaSeqString.length();
317 int cdnaLength = cdnaSeqString.length();
319 int cdnaEnd = cdnaLength;
320 final int proteinStart = 1;
321 final int proteinEnd = aaSeqString.length();
324 * If lengths don't match, try ignoring stop codon.
326 if (cdnaLength != mappedLength)
328 for (Object stop : ResidueProperties.STOP)
330 if (cdnaSeqString.toUpperCase().endsWith((String) stop))
340 * If lengths still don't match, try ignoring start codon.
342 if (cdnaLength != mappedLength
343 && cdnaSeqString.toUpperCase().startsWith(
344 ResidueProperties.START))
350 if (cdnaLength == mappedLength)
352 MapList map = new MapList(new int[]
353 { cdnaStart, cdnaEnd }, new int[]
354 { proteinStart, proteinEnd }, 3, 1);
364 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
365 * currently assumes that we are aligning cDNA to match protein.
368 * the sequence to be realigned
370 * the alignment whose sequence alignment is to be 'copied'
372 * character string represent a gap in the realigned sequence
373 * @param preserveUnmappedGaps
374 * @param preserveMappedGaps
375 * @return true if the sequence was realigned, false if it could not be
377 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
378 String gap, boolean preserveMappedGaps,
379 boolean preserveUnmappedGaps)
382 * Get any mappings from the source alignment to the target (dataset) sequence.
384 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
385 // all mappings. Would it help to constrain this?
386 AlignedCodonFrame[] mappings = al.getCodonFrame(seq);
387 if (mappings == null)
393 * Locate the aligned source sequence whose dataset sequence is mapped. We
394 * just take the first match here (as we can't align cDNA like more than one
397 SequenceI alignFrom = null;
398 AlignedCodonFrame mapping = null;
399 for (AlignedCodonFrame mp : mappings)
401 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
402 if (alignFrom != null)
409 if (alignFrom == null)
413 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
414 preserveMappedGaps, preserveUnmappedGaps);
419 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
420 * match residues and codons.
427 * @param preserveUnmappedGaps
428 * @param preserveMappedGaps
430 public static void alignSequenceAs(SequenceI alignTo,
432 AlignedCodonFrame mapping, String myGap, char sourceGap,
433 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
435 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
436 final char[] thisSeq = alignTo.getSequence();
437 final char[] thatAligned = alignFrom.getSequence();
438 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
440 // aligned and dataset sequence positions, all base zero
444 int basesWritten = 0;
445 char myGapChar = myGap.charAt(0);
446 int ratio = myGap.length();
449 * Traverse the aligned protein sequence.
451 int sourceGapLength = 0;
452 for (char sourceChar : thatAligned)
454 if (sourceChar == sourceGap)
461 * Found a residue. Locate its mapped codon (start) position.
464 // Note mapping positions are base 1, our sequence positions base 0
465 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
467 if (mappedPos == null)
470 * Abort realignment if unmapped protein. Or could ignore it??
472 System.err.println("Can't align: no codon mapping to residue "
473 + sourceDsPos + "(" + sourceChar + ")");
477 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
478 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
479 int trailingCopiedGapLength = 0;
482 * Copy dna sequence up to and including this codon. Optionally, include
483 * gaps before the codon starts (in introns) and/or after the codon starts
486 * Note this only works for 'linear' splicing, not reverse or interleaved.
487 * But then 'align dna as protein' doesn't make much sense otherwise.
489 boolean inCodon = false;
490 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
492 final char c = thisSeq[thisSeqPos++];
498 * Is this the start of the mapped codon? If so, add in any extra gap
499 * due to the protein alignment.
501 if (basesWritten == mappedCodonStart)
504 int gapsToAdd = Math.max(0, ratio * sourceGapLength
505 - trailingCopiedGapLength);
506 for (int i = 0; i < gapsToAdd; i++)
508 thisAligned.append(myGapChar);
512 thisAligned.append(c);
513 trailingCopiedGapLength = 0;
515 else if ((!inCodon && preserveUnmappedGaps)
516 || (inCodon && preserveMappedGaps))
518 thisAligned.append(c);
519 trailingCopiedGapLength++;
524 * Expand (if necessary) the trailing gap to the size of the aligned gap.
526 int gapsToAdd = (ratio * sourceGapLength - trailingCopiedGapLength);
527 for (int i = 0; i < gapsToAdd; i++)
529 thisAligned.append(myGapChar);
534 * At end of protein sequence. Copy any remaining dna sequence, optionally
535 * including (intron) gaps. We do not copy trailing gaps in protein.
537 while (thisSeqPos < thisSeq.length)
539 final char c = thisSeq[thisSeqPos++];
540 if (c != myGapChar || preserveUnmappedGaps)
542 thisAligned.append(c);
547 * All done aligning, set the aligned sequence.
549 alignTo.setSequence(new String(thisAligned));