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.SearchResults;
27 import jalview.datamodel.Sequence;
28 import jalview.datamodel.SequenceI;
29 import jalview.schemes.ResidueProperties;
30 import jalview.util.MapList;
32 import java.util.ArrayList;
33 import java.util.LinkedHashMap;
34 import java.util.List;
39 * grab bag of useful alignment manipulation operations Expect these to be
40 * refactored elsewhere at some point.
45 public class AlignmentUtils
49 * Represents the 3 possible results of trying to map one alignment to
52 public enum MappingResult
54 Mapped, NotMapped, AlreadyMapped
58 * given an existing alignment, create a new alignment including all, or up to
59 * flankSize additional symbols from each sequence's dataset sequence
65 public static AlignmentI expandContext(AlignmentI core, int flankSize)
67 List<SequenceI> sq = new ArrayList<SequenceI>();
69 for (SequenceI s : core.getSequences())
71 SequenceI newSeq = s.deriveSequence();
72 if (newSeq.getStart() > maxoffset
73 && newSeq.getDatasetSequence().getStart() < s.getStart())
75 maxoffset = newSeq.getStart();
81 maxoffset = flankSize;
83 // now add offset to create a new expanded alignment
84 for (SequenceI s : sq)
87 while (ds.getDatasetSequence() != null)
89 ds = ds.getDatasetSequence();
91 int s_end = s.findPosition(s.getStart() + s.getLength());
92 // find available flanking residues for sequence
93 int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
96 // build new flanked sequence
98 // compute gap padding to start of flanking sequence
99 int offset = maxoffset - ustream_ds;
101 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
104 if (flankSize < ustream_ds)
106 // take up to flankSize residues
107 offset = maxoffset - flankSize;
108 ustream_ds = flankSize;
110 if (flankSize < dstream_ds)
112 dstream_ds = flankSize;
115 char[] upstream = new String(ds.getSequence(s.getStart() - 1
116 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
117 char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
118 + dstream_ds)).toLowerCase().toCharArray();
119 char[] coreseq = s.getSequence();
120 char[] nseq = new char[offset + upstream.length + downstream.length
122 char c = core.getGapCharacter();
123 // TODO could lowercase the flanking regions
125 for (; p < offset; p++)
129 // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
130 // new String(downstream).toLowerCase());
131 System.arraycopy(upstream, 0, nseq, p, upstream.length);
132 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
134 System.arraycopy(downstream, 0, nseq, p + coreseq.length
135 + upstream.length, downstream.length);
136 s.setSequence(new String(nseq));
137 s.setStart(s.getStart() - ustream_ds);
138 s.setEnd(s_end + downstream.length);
140 AlignmentI newAl = new jalview.datamodel.Alignment(
141 sq.toArray(new SequenceI[0]));
142 for (SequenceI s : sq)
144 if (s.getAnnotation() != null)
146 for (AlignmentAnnotation aa : s.getAnnotation())
148 newAl.addAnnotation(aa);
152 newAl.setDataset(core.getDataset());
157 * Returns the index (zero-based position) of a sequence in an alignment, or
164 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
168 for (SequenceI alSeq : al.getSequences())
181 * Returns a map of lists of sequences in the alignment, keyed by sequence
182 * name. For use in mapping between different alignment views of the same
185 * @see jalview.datamodel.AlignmentI#getSequencesByName()
187 public static Map<String, List<SequenceI>> getSequencesByName(
190 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
191 for (SequenceI seq : al.getSequences())
193 String name = seq.getName();
196 List<SequenceI> seqs = theMap.get(name);
199 seqs = new ArrayList<SequenceI>();
200 theMap.put(name, seqs);
209 * Build mapping of protein to cDNA alignment. Mappings are made between
210 * sequences which have the same name and compatible lengths. Has a 3-valued
211 * result: either Mapped (at least one sequence mapping was created),
212 * AlreadyMapped (all possible sequence mappings already exist), or NotMapped
213 * (no possible sequence mappings exist).
215 * @param proteinAlignment
216 * @param cdnaAlignment
219 public static MappingResult mapProteinToCdna(
220 final AlignmentI proteinAlignment,
221 final AlignmentI cdnaAlignment)
223 if (proteinAlignment == null || cdnaAlignment == null)
225 return MappingResult.NotMapped;
228 boolean mappingPossible = false;
229 boolean mappingPerformed = false;
231 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
234 * Build a look-up of cDNA sequences by name, for matching purposes.
236 Map<String, List<SequenceI>> cdnaSeqs = cdnaAlignment
237 .getSequencesByName();
239 for (SequenceI aaSeq : thisSeqs)
241 AlignedCodonFrame acf = new AlignedCodonFrame();
242 List<SequenceI> candidates = cdnaSeqs.get(aaSeq.getName());
243 if (candidates == null)
246 * No cDNA sequence with matching name, so no mapping possible for this
251 mappingPossible = true;
252 for (SequenceI cdnaSeq : candidates)
254 if (!mappingExists(proteinAlignment.getCodonFrames(),
255 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
257 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
260 acf.addMap(cdnaSeq, aaSeq, map);
261 mappingPerformed = true;
265 proteinAlignment.addCodonFrame(acf);
269 * If at least one mapping was possible but none was done, then the
270 * alignments are already as mapped as they can be.
272 if (mappingPossible && !mappingPerformed)
274 return MappingResult.AlreadyMapped;
278 return mappingPerformed ? MappingResult.Mapped
279 : MappingResult.NotMapped;
284 * Answers true if the mappings include one between the given (dataset)
287 public static boolean mappingExists(Set<AlignedCodonFrame> set,
288 SequenceI aaSeq, SequenceI cdnaSeq)
292 for (AlignedCodonFrame acf : set)
294 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
304 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
305 * must be three times the length of the protein, possibly after ignoring
306 * start and/or stop codons. Returns null if no mapping is determined.
312 public static MapList mapProteinToCdna(SequenceI proteinSeq,
316 * Here we handle either dataset sequence set (desktop) or absent (applet)
318 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
319 String aaSeqString = proteinDataset != null ? proteinDataset
320 .getSequenceAsString() : proteinSeq.getSequenceAsString();
321 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
322 String cdnaSeqString = cdnaDataset != null ? cdnaDataset
323 .getSequenceAsString() : cdnaSeq.getSequenceAsString();
324 if (aaSeqString == null || cdnaSeqString == null)
329 final int mappedLength = 3 * aaSeqString.length();
330 int cdnaLength = cdnaSeqString.length();
332 int cdnaEnd = cdnaLength;
333 final int proteinStart = 1;
334 final int proteinEnd = aaSeqString.length();
337 * If lengths don't match, try ignoring stop codon.
339 if (cdnaLength != mappedLength)
341 for (Object stop : ResidueProperties.STOP)
343 if (cdnaSeqString.toUpperCase().endsWith((String) stop))
353 * If lengths still don't match, try ignoring start codon.
355 if (cdnaLength != mappedLength
356 && cdnaSeqString.toUpperCase().startsWith(
357 ResidueProperties.START))
363 if (cdnaLength == mappedLength)
365 MapList map = new MapList(new int[]
366 { cdnaStart, cdnaEnd }, new int[]
367 { proteinStart, proteinEnd }, 3, 1);
377 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
378 * currently assumes that we are aligning cDNA to match protein.
381 * the sequence to be realigned
383 * the alignment whose sequence alignment is to be 'copied'
385 * character string represent a gap in the realigned sequence
386 * @param preserveUnmappedGaps
387 * @param preserveMappedGaps
388 * @return true if the sequence was realigned, false if it could not be
390 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
391 String gap, boolean preserveMappedGaps,
392 boolean preserveUnmappedGaps)
395 * Get any mappings from the source alignment to the target (dataset) sequence.
397 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
398 // all mappings. Would it help to constrain this?
399 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
400 if (mappings == null)
406 * Locate the aligned source sequence whose dataset sequence is mapped. We
407 * just take the first match here (as we can't align cDNA like more than one
410 SequenceI alignFrom = null;
411 AlignedCodonFrame mapping = null;
412 for (AlignedCodonFrame mp : mappings)
414 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
415 if (alignFrom != null)
422 if (alignFrom == null)
426 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
427 preserveMappedGaps, preserveUnmappedGaps);
432 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
433 * match residues and codons. Flags control whether existing gaps in unmapped
434 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
435 * and exon are only retained if both flags are set.
442 * @param preserveUnmappedGaps
443 * @param preserveMappedGaps
445 public static void alignSequenceAs(SequenceI alignTo,
447 AlignedCodonFrame mapping, String myGap, char sourceGap,
448 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
450 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
451 final char[] thisSeq = alignTo.getSequence();
452 final char[] thatAligned = alignFrom.getSequence();
453 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
455 // aligned and dataset sequence positions, all base zero
459 int basesWritten = 0;
460 char myGapChar = myGap.charAt(0);
461 int ratio = myGap.length();
464 * Traverse the aligned protein sequence.
466 int sourceGapMappedLength = 0;
467 boolean inExon = false;
468 for (char sourceChar : thatAligned)
470 if (sourceChar == sourceGap)
472 sourceGapMappedLength += ratio;
477 * Found a residue. Locate its mapped codon (start) position.
480 // Note mapping positions are base 1, our sequence positions base 0
481 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
483 if (mappedPos == null)
486 * Abort realignment if unmapped protein. Or could ignore it??
488 System.err.println("Can't align: no codon mapping to residue "
489 + sourceDsPos + "(" + sourceChar + ")");
493 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
494 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
495 StringBuilder trailingCopiedGap = new StringBuilder();
498 * Copy dna sequence up to and including this codon. Optionally, include
499 * gaps before the codon starts (in introns) and/or after the codon starts
502 * Note this only works for 'linear' splicing, not reverse or interleaved.
503 * But then 'align dna as protein' doesn't make much sense otherwise.
505 int intronLength = 0;
506 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
508 final char c = thisSeq[thisSeqPos++];
513 if (basesWritten < mappedCodonStart)
516 * Found an unmapped (intron) base. First add in any preceding gaps
519 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
521 thisAligned.append(trailingCopiedGap.toString());
522 intronLength += trailingCopiedGap.length();
523 trailingCopiedGap = new StringBuilder();
530 final boolean startOfCodon = basesWritten == mappedCodonStart;
531 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
532 preserveUnmappedGaps, sourceGapMappedLength, inExon,
533 trailingCopiedGap.length(), intronLength, startOfCodon);
534 for (int i = 0; i < gapsToAdd; i++)
536 thisAligned.append(myGapChar);
538 sourceGapMappedLength = 0;
541 thisAligned.append(c);
542 trailingCopiedGap = new StringBuilder();
546 if (inExon && preserveMappedGaps)
548 trailingCopiedGap.append(myGapChar);
550 else if (!inExon && preserveUnmappedGaps)
552 trailingCopiedGap.append(myGapChar);
559 * At end of protein sequence. Copy any remaining dna sequence, optionally
560 * including (intron) gaps. We do not copy trailing gaps in protein.
562 while (thisSeqPos < thisSeq.length)
564 final char c = thisSeq[thisSeqPos++];
565 if (c != myGapChar || preserveUnmappedGaps)
567 thisAligned.append(c);
572 * All done aligning, set the aligned sequence.
574 alignTo.setSequence(new String(thisAligned));
578 * Helper method to work out how many gaps to insert when realigning.
580 * @param preserveMappedGaps
581 * @param preserveUnmappedGaps
582 * @param sourceGapMappedLength
584 * @param trailingCopiedGap
585 * @param intronLength
586 * @param startOfCodon
589 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
590 boolean preserveUnmappedGaps, int sourceGapMappedLength,
591 boolean inExon, int trailingGapLength,
592 int intronLength, final boolean startOfCodon)
598 * Reached start of codon. Ignore trailing gaps in intron unless we are
599 * preserving gaps in both exon and intron. Ignore them anyway if the
600 * protein alignment introduces a gap at least as large as the intronic
603 if (inExon && !preserveMappedGaps)
605 trailingGapLength = 0;
607 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
609 trailingGapLength = 0;
613 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
617 if (intronLength + trailingGapLength <= sourceGapMappedLength)
619 gapsToAdd = sourceGapMappedLength - intronLength;
623 gapsToAdd = Math.min(intronLength + trailingGapLength
624 - sourceGapMappedLength, trailingGapLength);
631 * second or third base of codon; check for any gaps in dna
633 if (!preserveMappedGaps)
635 trailingGapLength = 0;
637 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
643 * Returns a list of sequences mapped from the given sequences and aligned
644 * (gapped) in the same way. For example, the cDNA for aligned protein, where
645 * a single gap in protein generates three gaps in cDNA.
648 * @param gapCharacter
652 public static List<SequenceI> getAlignedTranslation(
653 List<SequenceI> sequences, char gapCharacter,
654 Set<AlignedCodonFrame> mappings)
656 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
658 for (SequenceI seq : sequences)
660 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
662 alignedSeqs.addAll(mapped);
668 * Returns sequences aligned 'like' the source sequence, as mapped by the
669 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
670 * will support 1-to-many as well.
673 * @param gapCharacter
677 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
678 char gapCharacter, Set<AlignedCodonFrame> mappings)
680 List<SequenceI> result = new ArrayList<SequenceI>();
681 for (AlignedCodonFrame mapping : mappings)
683 if (mapping.involvesSequence(seq))
685 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
696 * Returns the translation of 'seq' (as held in the mapping) with
697 * corresponding alignment (gaps).
700 * @param gapCharacter
704 protected static SequenceI getAlignedTranslation(SequenceI seq,
705 char gapCharacter, AlignedCodonFrame mapping)
707 String gap = String.valueOf(gapCharacter);
708 boolean toDna = false;
710 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
713 // mapping is from protein to nucleotide
715 // should ideally get gap count ratio from mapping
716 gap = String.valueOf(new char[]
717 { gapCharacter, gapCharacter, gapCharacter });
721 // mapping is from nucleotide to protein
722 mapTo = mapping.getAaForDnaSeq(seq);
725 StringBuilder newseq = new StringBuilder(seq.getLength()
728 int residueNo = 0; // in seq, base 1
729 int[] phrase = new int[fromRatio];
730 int phraseOffset = 0;
732 boolean first = true;
733 final Sequence alignedSeq = new Sequence("", "");
735 for (char c : seq.getSequence())
737 if (c == gapCharacter)
740 if (gapWidth >= fromRatio)
748 phrase[phraseOffset++] = residueNo + 1;
749 if (phraseOffset == fromRatio)
752 * Have read a whole codon (or protein residue), now translate: map
753 * source phrase to positions in target sequence add characters at
754 * these positions to newseq Note mapping positions are base 1, our
755 * sequence positions base 0.
757 SearchResults sr = new SearchResults();
758 for (int pos : phrase)
760 mapping.markMappedRegion(seq, pos, sr);
762 newseq.append(sr.toString());
766 // Hack: Copy sequence dataset, name and description from
767 // SearchResults.match[0].sequence
768 // TODO? carry over sequence names from original 'complement'
770 SequenceI mappedTo = sr.getResultSequence(0);
771 alignedSeq.setName(mappedTo.getName());
772 alignedSeq.setDescription(mappedTo.getDescription());
773 alignedSeq.setDatasetSequence(mappedTo);
780 alignedSeq.setSequence(newseq.toString());