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 if (proteinAlignment == null || cdnaAlignment == null)
223 return MappingResult.NotMapped;
226 boolean mappingPossible = false;
227 boolean mappingPerformed = false;
229 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
232 * Build a look-up of cDNA sequences by name, for matching purposes.
234 Map<String, List<SequenceI>> cdnaSeqs = cdnaAlignment
235 .getSequencesByName();
237 for (SequenceI aaSeq : thisSeqs)
239 AlignedCodonFrame acf = new AlignedCodonFrame();
240 List<SequenceI> candidates = cdnaSeqs.get(aaSeq.getName());
241 if (candidates == null)
244 * No cDNA sequence with matching name, so no mapping possible for this
249 mappingPossible = true;
250 for (SequenceI cdnaSeq : candidates)
252 if (!mappingExists(proteinAlignment.getCodonFrames(),
253 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
255 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
258 acf.addMap(cdnaSeq, aaSeq, map);
259 mappingPerformed = true;
263 proteinAlignment.addCodonFrame(acf);
267 * If at least one mapping was possible but none was done, then the
268 * alignments are already as mapped as they can be.
270 if (mappingPossible && !mappingPerformed)
272 return MappingResult.AlreadyMapped;
276 return mappingPerformed ? MappingResult.Mapped
277 : MappingResult.NotMapped;
282 * Answers true if the mappings include one between the given (dataset)
285 public static boolean mappingExists(Set<AlignedCodonFrame> set,
286 SequenceI aaSeq, SequenceI cdnaSeq)
290 for (AlignedCodonFrame acf : set)
292 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
302 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
303 * must be three times the length of the protein, possibly after ignoring
304 * start and/or stop codons. Returns null if no mapping is determined.
310 public static MapList mapProteinToCdna(SequenceI proteinSeq,
314 * Here we handle either dataset sequence set (desktop) or absent (applet)
316 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
317 String aaSeqString = proteinDataset != null ? proteinDataset
318 .getSequenceAsString() : proteinSeq.getSequenceAsString();
319 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
320 String cdnaSeqString = cdnaDataset != null ? cdnaDataset
321 .getSequenceAsString() : cdnaSeq.getSequenceAsString();
322 if (aaSeqString == null || cdnaSeqString == null)
327 final int mappedLength = 3 * aaSeqString.length();
328 int cdnaLength = cdnaSeqString.length();
330 int cdnaEnd = cdnaLength;
331 final int proteinStart = 1;
332 final int proteinEnd = aaSeqString.length();
335 * If lengths don't match, try ignoring stop codon.
337 if (cdnaLength != mappedLength)
339 for (Object stop : ResidueProperties.STOP)
341 if (cdnaSeqString.toUpperCase().endsWith((String) stop))
351 * If lengths still don't match, try ignoring start codon.
353 if (cdnaLength != mappedLength
354 && cdnaSeqString.toUpperCase().startsWith(
355 ResidueProperties.START))
361 if (cdnaLength == mappedLength)
363 MapList map = new MapList(new int[]
364 { cdnaStart, cdnaEnd }, new int[]
365 { proteinStart, proteinEnd }, 3, 1);
375 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
376 * currently assumes that we are aligning cDNA to match protein.
379 * the sequence to be realigned
381 * the alignment whose sequence alignment is to be 'copied'
383 * character string represent a gap in the realigned sequence
384 * @param preserveUnmappedGaps
385 * @param preserveMappedGaps
386 * @return true if the sequence was realigned, false if it could not be
388 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
389 String gap, boolean preserveMappedGaps,
390 boolean preserveUnmappedGaps)
393 * Get any mappings from the source alignment to the target (dataset) sequence.
395 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
396 // all mappings. Would it help to constrain this?
397 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
398 if (mappings == null)
404 * Locate the aligned source sequence whose dataset sequence is mapped. We
405 * just take the first match here (as we can't align cDNA like more than one
408 SequenceI alignFrom = null;
409 AlignedCodonFrame mapping = null;
410 for (AlignedCodonFrame mp : mappings)
412 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
413 if (alignFrom != null)
420 if (alignFrom == null)
424 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
425 preserveMappedGaps, preserveUnmappedGaps);
430 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
431 * match residues and codons. Flags control whether existing gaps in unmapped
432 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
433 * and exon are only retained if both flags are set.
440 * @param preserveUnmappedGaps
441 * @param preserveMappedGaps
443 public static void alignSequenceAs(SequenceI alignTo,
445 AlignedCodonFrame mapping, String myGap, char sourceGap,
446 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
448 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
449 final char[] thisSeq = alignTo.getSequence();
450 final char[] thatAligned = alignFrom.getSequence();
451 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
453 // aligned and dataset sequence positions, all base zero
457 int basesWritten = 0;
458 char myGapChar = myGap.charAt(0);
459 int ratio = myGap.length();
462 * Traverse the aligned protein sequence.
464 int sourceGapMappedLength = 0;
465 boolean inExon = false;
466 for (char sourceChar : thatAligned)
468 if (sourceChar == sourceGap)
470 sourceGapMappedLength += ratio;
475 * Found a residue. Locate its mapped codon (start) position.
478 // Note mapping positions are base 1, our sequence positions base 0
479 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
481 if (mappedPos == null)
484 * Abort realignment if unmapped protein. Or could ignore it??
486 System.err.println("Can't align: no codon mapping to residue "
487 + sourceDsPos + "(" + sourceChar + ")");
491 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
492 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
493 StringBuilder trailingCopiedGap = new StringBuilder();
496 * Copy dna sequence up to and including this codon. Optionally, include
497 * gaps before the codon starts (in introns) and/or after the codon starts
500 * Note this only works for 'linear' splicing, not reverse or interleaved.
501 * But then 'align dna as protein' doesn't make much sense otherwise.
503 int intronLength = 0;
504 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
506 final char c = thisSeq[thisSeqPos++];
511 if (basesWritten < mappedCodonStart)
514 * Found an unmapped (intron) base. First add in any preceding gaps
517 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
519 thisAligned.append(trailingCopiedGap.toString());
520 intronLength += trailingCopiedGap.length();
521 trailingCopiedGap = new StringBuilder();
528 final boolean startOfCodon = basesWritten == mappedCodonStart;
529 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
530 preserveUnmappedGaps, sourceGapMappedLength, inExon,
531 trailingCopiedGap.length(), intronLength, startOfCodon);
532 for (int i = 0; i < gapsToAdd; i++)
534 thisAligned.append(myGapChar);
536 sourceGapMappedLength = 0;
539 thisAligned.append(c);
540 trailingCopiedGap = new StringBuilder();
544 if (inExon && preserveMappedGaps)
546 trailingCopiedGap.append(myGapChar);
548 else if (!inExon && preserveUnmappedGaps)
550 trailingCopiedGap.append(myGapChar);
557 * At end of protein sequence. Copy any remaining dna sequence, optionally
558 * including (intron) gaps. We do not copy trailing gaps in protein.
560 while (thisSeqPos < thisSeq.length)
562 final char c = thisSeq[thisSeqPos++];
563 if (c != myGapChar || preserveUnmappedGaps)
565 thisAligned.append(c);
570 * All done aligning, set the aligned sequence.
572 alignTo.setSequence(new String(thisAligned));
576 * Helper method to work out how many gaps to insert when realigning.
578 * @param preserveMappedGaps
579 * @param preserveUnmappedGaps
580 * @param sourceGapMappedLength
582 * @param trailingCopiedGap
583 * @param intronLength
584 * @param startOfCodon
587 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
588 boolean preserveUnmappedGaps, int sourceGapMappedLength,
589 boolean inExon, int trailingGapLength,
590 int intronLength, final boolean startOfCodon)
596 * Reached start of codon. Ignore trailing gaps in intron unless we are
597 * preserving gaps in both exon and intron. Ignore them anyway if the
598 * protein alignment introduces a gap at least as large as the intronic
601 if (inExon && !preserveMappedGaps)
603 trailingGapLength = 0;
605 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
607 trailingGapLength = 0;
611 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
615 if (intronLength + trailingGapLength <= sourceGapMappedLength)
617 gapsToAdd = sourceGapMappedLength - intronLength;
621 gapsToAdd = Math.min(intronLength + trailingGapLength
622 - sourceGapMappedLength, trailingGapLength);
629 * second or third base of codon; check for any gaps in dna
631 if (!preserveMappedGaps)
633 trailingGapLength = 0;
635 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);