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.analysis;
23 import jalview.datamodel.AlignedCodon;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.FeatureProperties;
31 import jalview.datamodel.IncompleteCodonException;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.SearchResults;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.gff.SequenceOntologyFactory;
39 import jalview.io.gff.SequenceOntologyI;
40 import jalview.schemes.ResidueProperties;
41 import jalview.util.Comparison;
42 import jalview.util.DBRefUtils;
43 import jalview.util.MapList;
44 import jalview.util.MappingUtils;
45 import jalview.util.StringUtils;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.HashMap;
53 import java.util.HashSet;
54 import java.util.Iterator;
55 import java.util.LinkedHashMap;
56 import java.util.List;
58 import java.util.Map.Entry;
59 import java.util.NoSuchElementException;
61 import java.util.TreeMap;
64 * grab bag of useful alignment manipulation operations Expect these to be
65 * refactored elsewhere at some point.
70 public class AlignmentUtils
74 * given an existing alignment, create a new alignment including all, or up to
75 * flankSize additional symbols from each sequence's dataset sequence
81 public static AlignmentI expandContext(AlignmentI core, int flankSize)
83 List<SequenceI> sq = new ArrayList<SequenceI>();
85 for (SequenceI s : core.getSequences())
87 SequenceI newSeq = s.deriveSequence();
88 final int newSeqStart = newSeq.getStart() - 1;
89 if (newSeqStart > maxoffset
90 && newSeq.getDatasetSequence().getStart() < s.getStart())
92 maxoffset = newSeqStart;
98 maxoffset = Math.min(maxoffset, flankSize);
102 * now add offset left and right to create an expanded alignment
104 for (SequenceI s : sq)
107 while (ds.getDatasetSequence() != null)
109 ds = ds.getDatasetSequence();
111 int s_end = s.findPosition(s.getStart() + s.getLength());
112 // find available flanking residues for sequence
113 int ustream_ds = s.getStart() - ds.getStart();
114 int dstream_ds = ds.getEnd() - s_end;
116 // build new flanked sequence
118 // compute gap padding to start of flanking sequence
119 int offset = maxoffset - ustream_ds;
121 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
124 if (flankSize < ustream_ds)
126 // take up to flankSize residues
127 offset = maxoffset - flankSize;
128 ustream_ds = flankSize;
130 if (flankSize <= dstream_ds)
132 dstream_ds = flankSize - 1;
135 // TODO use Character.toLowerCase to avoid creating String objects?
136 char[] upstream = new String(ds.getSequence(s.getStart() - 1
137 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
138 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
139 + dstream_ds)).toLowerCase().toCharArray();
140 char[] coreseq = s.getSequence();
141 char[] nseq = new char[offset + upstream.length + downstream.length
143 char c = core.getGapCharacter();
146 for (; p < offset; p++)
151 System.arraycopy(upstream, 0, nseq, p, upstream.length);
152 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
154 System.arraycopy(downstream, 0, nseq, p + coreseq.length
155 + upstream.length, downstream.length);
156 s.setSequence(new String(nseq));
157 s.setStart(s.getStart() - ustream_ds);
158 s.setEnd(s_end + downstream.length);
160 AlignmentI newAl = new jalview.datamodel.Alignment(
161 sq.toArray(new SequenceI[0]));
162 for (SequenceI s : sq)
164 if (s.getAnnotation() != null)
166 for (AlignmentAnnotation aa : s.getAnnotation())
168 aa.adjustForAlignment(); // JAL-1712 fix
169 newAl.addAnnotation(aa);
173 newAl.setDataset(core.getDataset());
178 * Returns the index (zero-based position) of a sequence in an alignment, or
185 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
189 for (SequenceI alSeq : al.getSequences())
202 * Returns a map of lists of sequences in the alignment, keyed by sequence
203 * name. For use in mapping between different alignment views of the same
206 * @see jalview.datamodel.AlignmentI#getSequencesByName()
208 public static Map<String, List<SequenceI>> getSequencesByName(
211 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
212 for (SequenceI seq : al.getSequences())
214 String name = seq.getName();
217 List<SequenceI> seqs = theMap.get(name);
220 seqs = new ArrayList<SequenceI>();
221 theMap.put(name, seqs);
230 * Build mapping of protein to cDNA alignment. Mappings are made between
231 * sequences where the cDNA translates to the protein sequence. Any new
232 * mappings are added to the protein alignment. Returns true if any mappings
233 * either already exist or were added, else false.
235 * @param proteinAlignment
236 * @param cdnaAlignment
239 public static boolean mapProteinAlignmentToCdna(
240 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
242 if (proteinAlignment == null || cdnaAlignment == null)
247 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
248 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
251 * First pass - map sequences where cross-references exist. This include
252 * 1-to-many mappings to support, for example, variant cDNA.
254 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
255 cdnaAlignment, mappedDna, mappedProtein, true);
258 * Second pass - map sequences where no cross-references exist. This only
259 * does 1-to-1 mappings and assumes corresponding sequences are in the same
260 * order in the alignments.
262 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
263 mappedDna, mappedProtein, false);
264 return mappingPerformed;
268 * Make mappings between compatible sequences (where the cDNA translation
269 * matches the protein).
271 * @param proteinAlignment
272 * @param cdnaAlignment
274 * a set of mapped DNA sequences (to add to)
275 * @param mappedProtein
276 * a set of mapped Protein sequences (to add to)
278 * if true, only map sequences where xrefs exist
281 protected static boolean mapProteinToCdna(
282 final AlignmentI proteinAlignment,
283 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
284 Set<SequenceI> mappedProtein, boolean xrefsOnly)
286 boolean mappingExistsOrAdded = false;
287 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
288 for (SequenceI aaSeq : thisSeqs)
290 boolean proteinMapped = false;
291 AlignedCodonFrame acf = new AlignedCodonFrame();
293 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
296 * Always try to map if sequences have xref to each other; this supports
297 * variant cDNA or alternative splicing for a protein sequence.
299 * If no xrefs, try to map progressively, assuming that alignments have
300 * mappable sequences in corresponding order. These are not
301 * many-to-many, as that would risk mixing species with similar cDNA
304 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
310 * Don't map non-xrefd sequences more than once each. This heuristic
311 * allows us to pair up similar sequences in ordered alignments.
314 && (mappedProtein.contains(aaSeq) || mappedDna
319 if (mappingExists(proteinAlignment.getCodonFrames(),
320 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
322 mappingExistsOrAdded = true;
326 MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
329 acf.addMap(cdnaSeq, aaSeq, map);
330 mappingExistsOrAdded = true;
331 proteinMapped = true;
332 mappedDna.add(cdnaSeq);
333 mappedProtein.add(aaSeq);
339 proteinAlignment.addCodonFrame(acf);
342 return mappingExistsOrAdded;
346 * Answers true if the mappings include one between the given (dataset)
349 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
350 SequenceI aaSeq, SequenceI cdnaSeq)
352 if (mappings != null)
354 for (AlignedCodonFrame acf : mappings)
356 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
366 * Builds a mapping (if possible) of a cDNA to a protein sequence.
368 * <li>first checks if the cdna translates exactly to the protein sequence</li>
369 * <li>else checks for translation after removing a STOP codon</li>
370 * <li>else checks for translation after removing a START codon</li>
371 * <li>if that fails, inspect CDS features on the cDNA sequence</li>
373 * Returns null if no mapping is determined.
376 * the aligned protein sequence
378 * the aligned cdna sequence
381 public static MapList mapCdnaToProtein(SequenceI proteinSeq,
385 * Here we handle either dataset sequence set (desktop) or absent (applet).
386 * Use only the char[] form of the sequence to avoid creating possibly large
389 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
390 char[] aaSeqChars = proteinDataset != null ? proteinDataset
391 .getSequence() : proteinSeq.getSequence();
392 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
393 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
394 : cdnaSeq.getSequence();
395 if (aaSeqChars == null || cdnaSeqChars == null)
401 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
403 final int mappedLength = 3 * aaSeqChars.length;
404 int cdnaLength = cdnaSeqChars.length;
405 int cdnaStart = cdnaSeq.getStart();
406 int cdnaEnd = cdnaSeq.getEnd();
407 final int proteinStart = proteinSeq.getStart();
408 final int proteinEnd = proteinSeq.getEnd();
411 * If lengths don't match, try ignoring stop codon (if present)
413 if (cdnaLength != mappedLength && cdnaLength > 2)
415 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
417 for (String stop : ResidueProperties.STOP)
419 if (lastCodon.equals(stop))
429 * If lengths still don't match, try ignoring start codon.
432 if (cdnaLength != mappedLength
434 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
435 .equals(ResidueProperties.START))
442 if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
445 * protein is translation of dna (+/- start/stop codons)
447 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
448 { proteinStart, proteinEnd }, 3, 1);
453 * translation failed - try mapping CDS annotated regions of dna
455 return mapCdsToProtein(cdnaSeq, proteinSeq);
459 * Test whether the given cdna sequence, starting at the given offset,
460 * translates to the given amino acid sequence, using the standard translation
461 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
463 * @param cdnaSeqChars
468 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
471 if (cdnaSeqChars == null || aaSeqChars == null)
477 int dnaPos = cdnaStart;
478 for (; dnaPos < cdnaSeqChars.length - 2
479 && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
481 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
482 final String translated = ResidueProperties.codonTranslate(codon);
485 * allow * in protein to match untranslatable in dna
487 final char aaRes = aaSeqChars[aaPos];
488 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
492 if (translated == null || !(aaRes == translated.charAt(0)))
495 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
496 // + codon + "(" + translated + ") != " + aaRes));
502 * check we matched all of the protein sequence
504 if (aaPos != aaSeqChars.length)
510 * check we matched all of the dna except
511 * for optional trailing STOP codon
513 if (dnaPos == cdnaSeqChars.length)
517 if (dnaPos == cdnaSeqChars.length - 3)
519 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
520 if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
529 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
530 * currently assumes that we are aligning cDNA to match protein.
533 * the sequence to be realigned
535 * the alignment whose sequence alignment is to be 'copied'
537 * character string represent a gap in the realigned sequence
538 * @param preserveUnmappedGaps
539 * @param preserveMappedGaps
540 * @return true if the sequence was realigned, false if it could not be
542 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
543 String gap, boolean preserveMappedGaps,
544 boolean preserveUnmappedGaps)
547 * Get any mappings from the source alignment to the target (dataset)
550 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
551 // all mappings. Would it help to constrain this?
552 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
553 if (mappings == null || mappings.isEmpty())
559 * Locate the aligned source sequence whose dataset sequence is mapped. We
560 * just take the first match here (as we can't align like more than one
563 SequenceI alignFrom = null;
564 AlignedCodonFrame mapping = null;
565 for (AlignedCodonFrame mp : mappings)
567 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
568 if (alignFrom != null)
575 if (alignFrom == null)
579 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
580 preserveMappedGaps, preserveUnmappedGaps);
585 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
586 * match residues and codons. Flags control whether existing gaps in unmapped
587 * (intron) and mapped (exon) regions are preserved or not. Gaps between
588 * intron and exon are only retained if both flags are set.
595 * @param preserveUnmappedGaps
596 * @param preserveMappedGaps
598 public static void alignSequenceAs(SequenceI alignTo,
599 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
600 char sourceGap, boolean preserveMappedGaps,
601 boolean preserveUnmappedGaps)
603 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
605 // aligned and dataset sequence positions, all base zero
609 int basesWritten = 0;
610 char myGapChar = myGap.charAt(0);
611 int ratio = myGap.length();
613 int fromOffset = alignFrom.getStart() - 1;
614 int toOffset = alignTo.getStart() - 1;
615 int sourceGapMappedLength = 0;
616 boolean inExon = false;
617 final char[] thisSeq = alignTo.getSequence();
618 final char[] thatAligned = alignFrom.getSequence();
619 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
622 * Traverse the 'model' aligned sequence
624 for (char sourceChar : thatAligned)
626 if (sourceChar == sourceGap)
628 sourceGapMappedLength += ratio;
633 * Found a non-gap character. Locate its mapped region if any.
636 // Note mapping positions are base 1, our sequence positions base 0
637 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
638 sourceDsPos + fromOffset);
639 if (mappedPos == null)
642 * unmapped position; treat like a gap
644 sourceGapMappedLength += ratio;
645 // System.err.println("Can't align: no codon mapping to residue "
646 // + sourceDsPos + "(" + sourceChar + ")");
651 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
652 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
653 StringBuilder trailingCopiedGap = new StringBuilder();
656 * Copy dna sequence up to and including this codon. Optionally, include
657 * gaps before the codon starts (in introns) and/or after the codon starts
660 * Note this only works for 'linear' splicing, not reverse or interleaved.
661 * But then 'align dna as protein' doesn't make much sense otherwise.
663 int intronLength = 0;
664 while (basesWritten + toOffset < mappedCodonEnd
665 && thisSeqPos < thisSeq.length)
667 final char c = thisSeq[thisSeqPos++];
671 int sourcePosition = basesWritten + toOffset;
672 if (sourcePosition < mappedCodonStart)
675 * Found an unmapped (intron) base. First add in any preceding gaps
678 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
680 thisAligned.append(trailingCopiedGap.toString());
681 intronLength += trailingCopiedGap.length();
682 trailingCopiedGap = new StringBuilder();
689 final boolean startOfCodon = sourcePosition == mappedCodonStart;
690 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
691 preserveUnmappedGaps, sourceGapMappedLength, inExon,
692 trailingCopiedGap.length(), intronLength, startOfCodon);
693 for (int i = 0; i < gapsToAdd; i++)
695 thisAligned.append(myGapChar);
697 sourceGapMappedLength = 0;
700 thisAligned.append(c);
701 trailingCopiedGap = new StringBuilder();
705 if (inExon && preserveMappedGaps)
707 trailingCopiedGap.append(myGapChar);
709 else if (!inExon && preserveUnmappedGaps)
711 trailingCopiedGap.append(myGapChar);
718 * At end of model aligned sequence. Copy any remaining target sequence, optionally
719 * including (intron) gaps.
721 while (thisSeqPos < thisSeq.length)
723 final char c = thisSeq[thisSeqPos++];
724 if (c != myGapChar || preserveUnmappedGaps)
726 thisAligned.append(c);
728 sourceGapMappedLength--;
732 * finally add gaps to pad for any trailing source gaps or
733 * unmapped characters
735 if (preserveUnmappedGaps)
737 while (sourceGapMappedLength > 0)
739 thisAligned.append(myGapChar);
740 sourceGapMappedLength--;
745 * All done aligning, set the aligned sequence.
747 alignTo.setSequence(new String(thisAligned));
751 * Helper method to work out how many gaps to insert when realigning.
753 * @param preserveMappedGaps
754 * @param preserveUnmappedGaps
755 * @param sourceGapMappedLength
757 * @param trailingCopiedGap
758 * @param intronLength
759 * @param startOfCodon
762 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
763 boolean preserveUnmappedGaps, int sourceGapMappedLength,
764 boolean inExon, int trailingGapLength, int intronLength,
765 final boolean startOfCodon)
771 * Reached start of codon. Ignore trailing gaps in intron unless we are
772 * preserving gaps in both exon and intron. Ignore them anyway if the
773 * protein alignment introduces a gap at least as large as the intronic
776 if (inExon && !preserveMappedGaps)
778 trailingGapLength = 0;
780 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
782 trailingGapLength = 0;
786 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
790 if (intronLength + trailingGapLength <= sourceGapMappedLength)
792 gapsToAdd = sourceGapMappedLength - intronLength;
796 gapsToAdd = Math.min(intronLength + trailingGapLength
797 - sourceGapMappedLength, trailingGapLength);
804 * second or third base of codon; check for any gaps in dna
806 if (!preserveMappedGaps)
808 trailingGapLength = 0;
810 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
816 * Returns a list of sequences mapped from the given sequences and aligned
817 * (gapped) in the same way. For example, the cDNA for aligned protein, where
818 * a single gap in protein generates three gaps in cDNA.
821 * @param gapCharacter
825 public static List<SequenceI> getAlignedTranslation(
826 List<SequenceI> sequences, char gapCharacter,
827 Set<AlignedCodonFrame> mappings)
829 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
831 for (SequenceI seq : sequences)
833 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
835 alignedSeqs.addAll(mapped);
841 * Returns sequences aligned 'like' the source sequence, as mapped by the
842 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
843 * will support 1-to-many as well.
846 * @param gapCharacter
850 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
851 char gapCharacter, Set<AlignedCodonFrame> mappings)
853 List<SequenceI> result = new ArrayList<SequenceI>();
854 for (AlignedCodonFrame mapping : mappings)
856 if (mapping.involvesSequence(seq))
858 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
869 * Returns the translation of 'seq' (as held in the mapping) with
870 * corresponding alignment (gaps).
873 * @param gapCharacter
877 protected static SequenceI getAlignedTranslation(SequenceI seq,
878 char gapCharacter, AlignedCodonFrame mapping)
880 String gap = String.valueOf(gapCharacter);
881 boolean toDna = false;
883 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
886 // mapping is from protein to nucleotide
888 // should ideally get gap count ratio from mapping
889 gap = String.valueOf(new char[] { gapCharacter, gapCharacter,
894 // mapping is from nucleotide to protein
895 mapTo = mapping.getAaForDnaSeq(seq);
898 StringBuilder newseq = new StringBuilder(seq.getLength()
901 int residueNo = 0; // in seq, base 1
902 int[] phrase = new int[fromRatio];
903 int phraseOffset = 0;
905 boolean first = true;
906 final Sequence alignedSeq = new Sequence("", "");
908 for (char c : seq.getSequence())
910 if (c == gapCharacter)
913 if (gapWidth >= fromRatio)
921 phrase[phraseOffset++] = residueNo + 1;
922 if (phraseOffset == fromRatio)
925 * Have read a whole codon (or protein residue), now translate: map
926 * source phrase to positions in target sequence add characters at
927 * these positions to newseq Note mapping positions are base 1, our
928 * sequence positions base 0.
930 SearchResults sr = new SearchResults();
931 for (int pos : phrase)
933 mapping.markMappedRegion(seq, pos, sr);
935 newseq.append(sr.getCharacters());
939 // Hack: Copy sequence dataset, name and description from
940 // SearchResults.match[0].sequence
941 // TODO? carry over sequence names from original 'complement'
943 SequenceI mappedTo = sr.getResultSequence(0);
944 alignedSeq.setName(mappedTo.getName());
945 alignedSeq.setDescription(mappedTo.getDescription());
946 alignedSeq.setDatasetSequence(mappedTo);
953 alignedSeq.setSequence(newseq.toString());
958 * Realigns the given protein to match the alignment of the dna, using codon
959 * mappings to translate aligned codon positions to protein residues.
962 * the alignment whose sequences are realigned by this method
964 * the dna alignment whose alignment we are 'copying'
965 * @return the number of sequences that were realigned
967 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
969 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
970 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
971 protein, dna, unmappedProtein);
972 return alignProteinAs(protein, alignedCodons, unmappedProtein);
976 * Builds a map whose key is an aligned codon position (3 alignment column
977 * numbers base 0), and whose value is a map from protein sequence to each
978 * protein's peptide residue for that codon. The map generates an ordering of
979 * the codons, and allows us to read off the peptides at each position in
980 * order to assemble 'aligned' protein sequences.
983 * the protein alignment
985 * the coding dna alignment
986 * @param unmappedProtein
987 * any unmapped proteins are added to this list
990 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
991 AlignmentI protein, AlignmentI dna,
992 List<SequenceI> unmappedProtein)
995 * maintain a list of any proteins with no mappings - these will be
996 * rendered 'as is' in the protein alignment as we can't align them
998 unmappedProtein.addAll(protein.getSequences());
1000 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1003 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
1004 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
1005 * comparator keeps the codon positions ordered.
1007 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
1008 new CodonComparator());
1010 for (SequenceI dnaSeq : dna.getSequences())
1012 for (AlignedCodonFrame mapping : mappings)
1014 SequenceI prot = mapping.findAlignedSequence(
1015 dnaSeq.getDatasetSequence(), protein);
1018 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
1019 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
1020 seqMap, alignedCodons);
1021 unmappedProtein.remove(prot);
1027 * Finally add any unmapped peptide start residues (e.g. for incomplete
1028 * codons) as if at the codon position before the second residue
1030 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
1031 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
1033 return alignedCodons;
1037 * Scans for any protein mapped from position 2 (meaning unmapped start
1038 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
1039 * preceding position in the alignment
1041 * @param alignedCodons
1042 * the codon-to-peptide map
1043 * @param mappedSequenceCount
1044 * the number of distinct sequences in the map
1046 protected static void addUnmappedPeptideStarts(
1047 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1048 int mappedSequenceCount)
1050 // TODO delete this ugly hack once JAL-2022 is resolved
1051 // i.e. we can model startPhase > 0 (incomplete start codon)
1053 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
1054 AlignedCodon lastCodon = null;
1055 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
1057 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
1060 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
1063 SequenceI seq = sequenceCodon.getKey();
1064 if (sequencesChecked.contains(seq))
1068 sequencesChecked.add(seq);
1069 AlignedCodon codon = sequenceCodon.getValue();
1070 if (codon.peptideCol > 1)
1073 .println("Problem mapping protein with >1 unmapped start positions: "
1076 else if (codon.peptideCol == 1)
1079 * first position (peptideCol == 0) was unmapped - add it
1081 if (lastCodon != null)
1083 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
1084 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
1086 toAdd.put(seq, firstPeptide);
1091 * unmapped residue at start of alignment (no prior column) -
1092 * 'insert' at nominal codon [0, 0, 0]
1094 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
1095 String.valueOf(seq.getCharAt(0)), 0);
1096 toAdd.put(seq, firstPeptide);
1099 if (sequencesChecked.size() == mappedSequenceCount)
1101 // no need to check past first mapped position in all sequences
1105 lastCodon = entry.getKey();
1109 * add any new codons safely after iterating over the map
1111 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
1113 addCodonToMap(alignedCodons, startCodon.getValue(),
1114 startCodon.getKey());
1119 * Update the aligned protein sequences to match the codon alignments given in
1123 * @param alignedCodons
1124 * an ordered map of codon positions (columns), with sequence/peptide
1125 * values present in each column
1126 * @param unmappedProtein
1129 protected static int alignProteinAs(AlignmentI protein,
1130 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1131 List<SequenceI> unmappedProtein)
1134 * Prefill aligned sequences with gaps before inserting aligned protein
1137 int alignedWidth = alignedCodons.size();
1138 char[] gaps = new char[alignedWidth];
1139 Arrays.fill(gaps, protein.getGapCharacter());
1140 String allGaps = String.valueOf(gaps);
1141 for (SequenceI seq : protein.getSequences())
1143 if (!unmappedProtein.contains(seq))
1145 seq.setSequence(allGaps);
1150 for (AlignedCodon codon : alignedCodons.keySet())
1152 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1154 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1156 // place translated codon at its column position in sequence
1157 entry.getKey().getSequence()[column] = entry.getValue().product
1166 * Populate the map of aligned codons by traversing the given sequence
1167 * mapping, locating the aligned positions of mapped codons, and adding those
1168 * positions and their translation products to the map.
1171 * the aligned sequence we are mapping from
1173 * the sequence to be aligned to the codons
1175 * the gap character in the dna sequence
1177 * a mapping to a sequence translation
1178 * @param alignedCodons
1179 * the map we are building up
1181 static void addCodonPositions(SequenceI dna, SequenceI protein,
1182 char gapChar, Mapping seqMap,
1183 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1185 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1188 * add codon positions, and their peptide translations, to the alignment
1189 * map, while remembering the first codon mapped
1191 while (codons.hasNext())
1195 AlignedCodon codon = codons.next();
1196 addCodonToMap(alignedCodons, codon, protein);
1197 } catch (IncompleteCodonException e)
1199 // possible incomplete trailing codon - ignore
1200 } catch (NoSuchElementException e)
1202 // possibly peptide lacking STOP
1208 * Helper method to add a codon-to-peptide entry to the aligned codons map
1210 * @param alignedCodons
1214 protected static void addCodonToMap(
1215 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1216 AlignedCodon codon, SequenceI protein)
1218 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1219 if (seqProduct == null)
1221 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1222 alignedCodons.put(codon, seqProduct);
1224 seqProduct.put(protein, codon);
1228 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1229 * between at least one pair of sequences in the two alignments. Currently,
1232 * <li>One alignment must be nucleotide, and the other protein</li>
1233 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1234 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1235 * <li>The translation may ignore start and stop codons if present in the
1243 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1245 if (al1 == null || al2 == null)
1251 * Require one nucleotide and one protein
1253 if (al1.isNucleotide() == al2.isNucleotide())
1257 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1258 AlignmentI protein = dna == al1 ? al2 : al1;
1259 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1260 for (SequenceI dnaSeq : dna.getSequences())
1262 for (SequenceI proteinSeq : protein.getSequences())
1264 if (isMappable(dnaSeq, proteinSeq, mappings))
1274 * Returns true if the dna sequence is mapped, or could be mapped, to the
1282 protected static boolean isMappable(SequenceI dnaSeq,
1283 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1285 if (dnaSeq == null || proteinSeq == null)
1290 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1291 .getDatasetSequence();
1292 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1293 : proteinSeq.getDatasetSequence();
1295 for (AlignedCodonFrame mapping : mappings)
1297 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1307 * Just try to make a mapping (it is not yet stored), test whether
1310 return mapCdnaToProtein(proteinDs, dnaDs) != null;
1314 * Finds any reference annotations associated with the sequences in
1315 * sequenceScope, that are not already added to the alignment, and adds them
1316 * to the 'candidates' map. Also populates a lookup table of annotation
1317 * labels, keyed by calcId, for use in constructing tooltips or the like.
1319 * @param sequenceScope
1320 * the sequences to scan for reference annotations
1321 * @param labelForCalcId
1322 * (optional) map to populate with label for calcId
1324 * map to populate with annotations for sequence
1326 * the alignment to check for presence of annotations
1328 public static void findAddableReferenceAnnotations(
1329 List<SequenceI> sequenceScope,
1330 Map<String, String> labelForCalcId,
1331 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1334 if (sequenceScope == null)
1340 * For each sequence in scope, make a list of any annotations on the
1341 * underlying dataset sequence which are not already on the alignment.
1343 * Add to a map of { alignmentSequence, <List of annotations to add> }
1345 for (SequenceI seq : sequenceScope)
1347 SequenceI dataset = seq.getDatasetSequence();
1348 if (dataset == null)
1352 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1353 if (datasetAnnotations == null)
1357 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1358 for (AlignmentAnnotation dsann : datasetAnnotations)
1361 * Find matching annotations on the alignment. If none is found, then
1362 * add this annotation to the list of 'addable' annotations for this
1365 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1366 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1367 if (!matchedAlignmentAnnotations.iterator().hasNext())
1370 if (labelForCalcId != null)
1372 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1377 * Save any addable annotations for this sequence
1379 if (!result.isEmpty())
1381 candidates.put(seq, result);
1387 * Adds annotations to the top of the alignment annotations, in the same order
1388 * as their related sequences.
1390 * @param annotations
1391 * the annotations to add
1393 * the alignment to add them to
1394 * @param selectionGroup
1395 * current selection group (or null if none)
1397 public static void addReferenceAnnotations(
1398 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1399 final AlignmentI alignment, final SequenceGroup selectionGroup)
1401 for (SequenceI seq : annotations.keySet())
1403 for (AlignmentAnnotation ann : annotations.get(seq))
1405 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1407 int endRes = ann.annotations.length;
1408 if (selectionGroup != null)
1410 startRes = selectionGroup.getStartRes();
1411 endRes = selectionGroup.getEndRes();
1413 copyAnn.restrict(startRes, endRes);
1416 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1417 * original annotation is already on the sequence.
1419 if (!seq.hasAnnotation(ann))
1421 seq.addAlignmentAnnotation(copyAnn);
1424 copyAnn.adjustForAlignment();
1425 // add to the alignment and set visible
1426 alignment.addAnnotation(copyAnn);
1427 copyAnn.visible = true;
1433 * Set visibility of alignment annotations of specified types (labels), for
1434 * specified sequences. This supports controls like
1435 * "Show all secondary structure", "Hide all Temp factor", etc.
1437 * @al the alignment to scan for annotations
1439 * the types (labels) of annotations to be updated
1440 * @param forSequences
1441 * if not null, only annotations linked to one of these sequences are
1442 * in scope for update; if null, acts on all sequence annotations
1444 * if this flag is true, 'types' is ignored (label not checked)
1446 * if true, set visibility on, else set off
1448 public static void showOrHideSequenceAnnotations(AlignmentI al,
1449 Collection<String> types, List<SequenceI> forSequences,
1450 boolean anyType, boolean doShow)
1452 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1454 if (anyType || types.contains(aa.label))
1456 if ((aa.sequenceRef != null)
1457 && (forSequences == null || forSequences
1458 .contains(aa.sequenceRef)))
1460 aa.visible = doShow;
1467 * Returns true if either sequence has a cross-reference to the other
1473 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1475 // Note: moved here from class CrossRef as the latter class has dependencies
1476 // not availability to the applet's classpath
1477 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1481 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1482 * that sequence name is structured as Source|AccessionId.
1488 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1490 if (seq1 == null || seq2 == null)
1494 String name = seq2.getName();
1495 final DBRefEntry[] xrefs = seq1.getDBRefs();
1498 for (DBRefEntry xref : xrefs)
1500 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1501 // case-insensitive test, consistent with DBRefEntry.equalRef()
1502 if (xrefName.equalsIgnoreCase(name))
1512 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1513 * nucleotide sequences, and updates mappings to match. The new sequences are
1514 * aligned as per the original sequence, with entirely gapped columns (codon
1515 * interrupted by intron) omitted.
1518 * aligned dna sequences
1520 * from dna to protein; these are replaced with new mappings
1522 * @return an alignment whose sequences are the cds-only parts of the dna
1523 * sequences (or null if no mappings are found)
1525 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1526 List<AlignedCodonFrame> mappings, AlignmentI al)
1528 List<int[]> cdsColumns = findCdsColumns(dna);
1531 * create CDS sequences and new mappings
1532 * (from cdna to cds, and cds to peptide)
1534 List<AlignedCodonFrame> newMappings = new ArrayList<AlignedCodonFrame>();
1535 List<SequenceI> cdsSequences = new ArrayList<SequenceI>();
1536 char gap = al.getGapCharacter();
1538 for (SequenceI dnaSeq : dna)
1540 final SequenceI ds = dnaSeq.getDatasetSequence();
1541 List<AlignedCodonFrame> seqMappings = MappingUtils
1542 .findMappingsForSequence(ds, mappings);
1543 for (AlignedCodonFrame acf : seqMappings)
1545 AlignedCodonFrame newMapping = new AlignedCodonFrame();
1546 final List<SequenceI> mappedCds = makeCdsSequences(dnaSeq, acf,
1547 cdsColumns, newMapping, gap);
1548 if (!mappedCds.isEmpty())
1550 cdsSequences.addAll(mappedCds);
1551 newMappings.add(newMapping);
1555 AlignmentI newAl = new Alignment(
1556 cdsSequences.toArray(new SequenceI[cdsSequences.size()]));
1559 * add new sequences to the shared dataset, set it on the new alignment
1561 List<SequenceI> dsseqs = al.getDataset().getSequences();
1562 for (SequenceI seq : newAl.getSequences())
1564 if (!dsseqs.contains(seq.getDatasetSequence()))
1566 dsseqs.add(seq.getDatasetSequence());
1569 newAl.setDataset(al.getDataset());
1572 * Replace the old mappings with the new ones
1575 mappings.addAll(newMappings);
1581 * Returns a consolidated list of column ranges where at least one sequence
1582 * has a CDS feature. This assumes CDS features are on genomic sequence i.e.
1583 * are for contiguous CDS ranges (no gaps).
1588 public static List<int[]> findCdsColumns(SequenceI[] seqs)
1590 // TODO use refactored code from AlignViewController
1591 // markColumnsContainingFeatures, not reinvent the wheel!
1593 List<int[]> result = new ArrayList<int[]>();
1594 for (SequenceI seq : seqs)
1596 result.addAll(findCdsColumns(seq));
1600 * sort and compact the list into ascending, non-overlapping ranges
1602 Collections.sort(result, new Comparator<int[]>()
1605 public int compare(int[] o1, int[] o2)
1607 return Integer.compare(o1[0], o2[0]);
1610 result = MapList.coalesceRanges(result);
1615 public static List<int[]> findCdsColumns(SequenceI seq)
1617 List<int[]> result = new ArrayList<int[]>();
1618 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1619 SequenceFeature[] sfs = seq.getSequenceFeatures();
1622 for (SequenceFeature sf : sfs)
1624 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1626 int colStart = seq.findIndex(sf.getBegin());
1627 int colEnd = seq.findIndex(sf.getEnd());
1628 result.add(new int[] { colStart, colEnd });
1636 * Answers true if all sequences have a gap at (or do not extend to) the
1637 * specified column position (base 1)
1643 public static boolean isGappedColumn(List<SequenceI> seqs, int col)
1647 for (SequenceI seq : seqs)
1649 if (!Comparison.isGap(seq.getCharAt(col - 1)))
1659 * Returns the column ranges (base 1) of each aligned sequence that are
1660 * involved in any mapping. This is a helper method for aligning protein
1661 * products of aligned transcripts.
1663 * @param mappedSequences
1664 * (possibly gapped) dna sequences
1668 protected static List<List<int[]>> getMappedColumns(
1669 List<SequenceI> mappedSequences, List<AlignedCodonFrame> mappings)
1671 List<List<int[]>> result = new ArrayList<List<int[]>>();
1672 for (SequenceI seq : mappedSequences)
1674 List<int[]> columns = new ArrayList<int[]>();
1675 List<AlignedCodonFrame> seqMappings = MappingUtils
1676 .findMappingsForSequence(seq, mappings);
1677 for (AlignedCodonFrame mapping : seqMappings)
1679 List<Mapping> maps = mapping.getMappingsForSequence(seq);
1680 for (Mapping map : maps)
1683 * Get the codon regions as { [2, 5], [7, 12], [14, 14] etc }
1684 * Find and add the overall aligned column range for each
1686 for (int[] cdsRange : map.getMap().getFromRanges())
1688 int startPos = cdsRange[0];
1689 int endPos = cdsRange[1];
1690 int startCol = seq.findIndex(startPos);
1691 int endCol = seq.findIndex(endPos);
1692 columns.add(new int[] { startCol, endCol });
1696 result.add(columns);
1702 * Helper method to make cds-only sequences and populate their mappings to
1705 * For example, if ggCCaTTcGAg has mappings [3, 4, 6, 7, 9, 10] to protein
1706 * then generate a sequence CCTTGA with mapping [1, 6] to the same protein
1709 * Typically eukaryotic dna will include cds encoding for a single peptide
1710 * sequence i.e. return a single result. Bacterial dna may have overlapping
1711 * cds mappings coding for multiple peptides so return multiple results
1712 * (example EMBL KF591215).
1715 * a dna aligned sequence
1717 * containing one or more mappings of the sequence to protein
1718 * @param ungappedCdsColumns
1719 * @param newMappings
1720 * the new mapping to populate, from the cds-only sequences to their
1721 * mapped protein sequences
1724 protected static List<SequenceI> makeCdsSequences(SequenceI dnaSeq,
1725 AlignedCodonFrame mapping, List<int[]> ungappedCdsColumns,
1726 AlignedCodonFrame newMappings, char gapChar)
1728 List<SequenceI> cdsSequences = new ArrayList<SequenceI>();
1729 List<Mapping> seqMappings = mapping.getMappingsForSequence(dnaSeq);
1731 for (Mapping seqMapping : seqMappings)
1733 SequenceI cds = makeCdsSequence(dnaSeq, seqMapping,
1734 ungappedCdsColumns, gapChar);
1735 cds.createDatasetSequence();
1736 cdsSequences.add(cds);
1739 * add new mappings, from dna to cds, and from cds to peptide
1741 MapList dnaToCds = addCdsMappings(dnaSeq.getDatasetSequence(), cds,
1742 seqMapping, newMappings);
1745 * transfer any features on dna that overlap the CDS
1747 transferFeatures(dnaSeq, cds, dnaToCds, null, SequenceOntologyI.CDS);
1749 return cdsSequences;
1753 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1754 * feature start/end ranges, optionally omitting specified feature types.
1755 * Returns the number of features copied.
1760 * if not null, only features of this type are copied (including
1761 * subtypes in the Sequence Ontology)
1763 * the mapping from 'fromSeq' to 'toSeq'
1766 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1767 MapList mapping, String select, String... omitting)
1769 SequenceI copyTo = toSeq;
1770 while (copyTo.getDatasetSequence() != null)
1772 copyTo = copyTo.getDatasetSequence();
1775 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1777 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1780 for (SequenceFeature sf : sfs)
1782 String type = sf.getType();
1783 if (select != null && !so.isA(type, select))
1787 boolean omit = false;
1788 for (String toOmit : omitting)
1790 if (type.equals(toOmit))
1801 * locate the mapped range - null if either start or end is
1802 * not mapped (no partial overlaps are calculated)
1804 int start = sf.getBegin();
1805 int end = sf.getEnd();
1806 int[] mappedTo = mapping.locateInTo(start, end);
1808 * if whole exon range doesn't map, try interpreting it
1809 * as 5' or 3' exon overlapping the CDS range
1811 if (mappedTo == null)
1813 mappedTo = mapping.locateInTo(end, end);
1814 if (mappedTo != null)
1817 * end of exon is in CDS range - 5' overlap
1818 * to a range from the start of the peptide
1823 if (mappedTo == null)
1825 mappedTo = mapping.locateInTo(start, start);
1826 if (mappedTo != null)
1829 * start of exon is in CDS range - 3' overlap
1830 * to a range up to the end of the peptide
1832 mappedTo[1] = toSeq.getLength();
1835 if (mappedTo != null)
1837 SequenceFeature copy = new SequenceFeature(sf);
1838 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1839 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1840 copyTo.addSequenceFeature(copy);
1849 * Creates and adds mappings
1851 * <li>from cds to peptide</li>
1852 * <li>from dna to cds</li>
1854 * and returns the dna-to-cds mapping
1859 * @param newMappings
1862 protected static MapList addCdsMappings(SequenceI dnaSeq,
1863 SequenceI cdsSeq, Mapping dnaMapping,
1864 AlignedCodonFrame newMappings)
1866 cdsSeq.createDatasetSequence();
1869 * CDS to peptide is just a contiguous 3:1 mapping, with
1870 * the peptide ranges taken unchanged from the dna mapping
1872 List<int[]> cdsRanges = new ArrayList<int[]>();
1873 SequenceI cdsDataset = cdsSeq.getDatasetSequence();
1874 cdsRanges.add(new int[] { 1, cdsDataset.getLength() });
1875 MapList cdsToPeptide = new MapList(cdsRanges, dnaMapping.getMap()
1876 .getToRanges(), 3, 1);
1877 newMappings.addMap(cdsDataset, dnaMapping.getTo(), cdsToPeptide);
1880 * dna 'from' ranges map 1:1 to the contiguous extracted CDS
1882 MapList dnaToCds = new MapList(dnaMapping.getMap().getFromRanges(),
1884 newMappings.addMap(dnaSeq, cdsDataset, dnaToCds);
1889 * Makes and returns a CDS-only sequence, where the CDS regions are identified
1890 * as the 'from' ranges of the mapping on the dna.
1893 * nucleotide sequence
1895 * mappings from CDS regions of nucleotide
1896 * @param ungappedCdsColumns
1899 protected static SequenceI makeCdsSequence(SequenceI dnaSeq,
1900 Mapping seqMapping, List<int[]> ungappedCdsColumns, char gapChar)
1902 int cdsWidth = MappingUtils.getLength(ungappedCdsColumns);
1905 * populate CDS columns with the aligned
1906 * column character if that column is mapped (which may be a gap
1907 * if an intron interrupts a codon), else with a gap
1909 List<int[]> fromRanges = seqMapping.getMap().getFromRanges();
1910 char[] cdsChars = new char[cdsWidth];
1912 for (int[] columns : ungappedCdsColumns)
1914 for (int i = columns[0]; i <= columns[1]; i++)
1916 char dnaChar = dnaSeq.getCharAt(i - 1);
1917 if (Comparison.isGap(dnaChar))
1919 cdsChars[pos] = gapChar;
1923 int seqPos = dnaSeq.findPosition(i - 1);
1924 if (MappingUtils.contains(fromRanges, seqPos))
1926 cdsChars[pos] = dnaChar;
1930 cdsChars[pos] = gapChar;
1936 SequenceI cdsSequence = new Sequence(dnaSeq.getName(),
1937 String.valueOf(cdsChars));
1939 transferDbRefs(seqMapping.getTo(), cdsSequence);
1945 * Locate any xrefs to CDS databases on the protein product and attach to the
1946 * CDS sequence. Also add as a sub-token of the sequence name.
1951 protected static void transferDbRefs(SequenceI from, SequenceI to)
1953 String cdsAccId = FeatureProperties.getCodingFeature(DBRefSource.EMBL);
1954 DBRefEntry[] cdsRefs = DBRefUtils.selectRefs(from.getDBRefs(),
1955 DBRefSource.CODINGDBS);
1956 if (cdsRefs != null)
1958 for (DBRefEntry cdsRef : cdsRefs)
1960 to.addDBRef(new DBRefEntry(cdsRef));
1961 cdsAccId = cdsRef.getAccessionId();
1964 if (!to.getName().contains(cdsAccId))
1966 to.setName(to.getName() + "|" + cdsAccId);
1971 * Returns a mapping from dna to protein by inspecting sequence features of
1972 * type "CDS" on the dna.
1978 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1979 SequenceI proteinSeq)
1981 List<int[]> ranges = findCdsPositions(dnaSeq);
1982 int mappedDnaLength = MappingUtils.getLength(ranges);
1984 int proteinLength = proteinSeq.getLength();
1985 int proteinStart = proteinSeq.getStart();
1986 int proteinEnd = proteinSeq.getEnd();
1989 * incomplete start codon may mean X at start of peptide
1990 * we ignore both for mapping purposes
1992 if (proteinSeq.getCharAt(0) == 'X')
1994 // todo JAL-2022 support startPhase > 0
1998 List<int[]> proteinRange = new ArrayList<int[]>();
2001 * dna length should map to protein (or protein plus stop codon)
2003 int codesForResidues = mappedDnaLength / 3;
2004 if (codesForResidues == (proteinLength + 1))
2006 // assuming extra codon is for STOP and not in peptide
2009 if (codesForResidues == proteinLength)
2011 proteinRange.add(new int[] { proteinStart, proteinEnd });
2012 return new MapList(ranges, proteinRange, 3, 1);
2018 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
2019 * start/end positions of sequence features of type "CDS" (or a sub-type of
2020 * CDS in the Sequence Ontology)
2025 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
2027 List<int[]> result = new ArrayList<int[]>();
2028 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
2033 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2034 for (SequenceFeature sf : sfs)
2037 * process a CDS feature (or a sub-type of CDS)
2039 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
2043 phase = Integer.parseInt(sf.getPhase());
2044 } catch (NumberFormatException e)
2049 * phase > 0 on first codon means 5' incomplete - skip to the start
2050 * of the next codon; example ENST00000496384
2052 int begin = sf.getBegin();
2053 int end = sf.getEnd();
2054 if (result.isEmpty())
2056 // TODO JAL-2022 support start phase > 0
2060 continue; // shouldn't happen?
2063 result.add(new int[] { begin, end });
2070 * Maps exon features from dna to protein, and computes variants in peptide
2071 * product generated by variants in dna, and adds them as sequence_variant
2072 * features on the protein sequence. Returns the number of variant features
2077 * @param dnaToProtein
2079 public static int computeProteinFeatures(SequenceI dnaSeq,
2080 SequenceI peptide, MapList dnaToProtein)
2082 while (dnaSeq.getDatasetSequence() != null)
2084 dnaSeq = dnaSeq.getDatasetSequence();
2086 while (peptide.getDatasetSequence() != null)
2088 peptide = peptide.getDatasetSequence();
2091 transferFeatures(dnaSeq, peptide, dnaToProtein,
2092 SequenceOntologyI.EXON);
2094 LinkedHashMap<Integer, String[][]> variants = buildDnaVariantsMap(
2095 dnaSeq, dnaToProtein);
2098 * scan codon variations, compute peptide variants and add to peptide sequence
2101 for (Entry<Integer, String[][]> variant : variants.entrySet())
2103 int peptidePos = variant.getKey();
2104 String[][] codonVariants = variant.getValue();
2105 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1)); // 0-based
2106 List<String> peptideVariants = computePeptideVariants(codonVariants,
2108 if (!peptideVariants.isEmpty())
2110 String desc = StringUtils.listToDelimitedString(peptideVariants,
2112 SequenceFeature sf = new SequenceFeature(
2113 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
2114 peptidePos, 0f, null);
2115 peptide.addSequenceFeature(sf);
2121 * ugly sort to get sequence features in start position order
2122 * - would be better to store in Sequence as a TreeSet instead?
2124 Arrays.sort(peptide.getSequenceFeatures(),
2125 new Comparator<SequenceFeature>()
2128 public int compare(SequenceFeature o1, SequenceFeature o2)
2130 int c = Integer.compare(o1.getBegin(), o2.getBegin());
2131 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
2139 * Builds a map whose key is position in the protein sequence, and value is an
2140 * array of all variants for the coding codon positions
2143 * @param dnaToProtein
2146 static LinkedHashMap<Integer, String[][]> buildDnaVariantsMap(
2147 SequenceI dnaSeq, MapList dnaToProtein)
2150 * map from peptide position to all variant features of the codon for it
2151 * LinkedHashMap ensures we add the peptide features in sequence order
2153 LinkedHashMap<Integer, String[][]> variants = new LinkedHashMap<Integer, String[][]>();
2154 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2156 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2157 if (dnaFeatures == null)
2162 int dnaStart = dnaSeq.getStart();
2163 int[] lastCodon = null;
2164 int lastPeptidePostion = 0;
2167 * build a map of codon variations for peptides
2169 for (SequenceFeature sf : dnaFeatures)
2171 int dnaCol = sf.getBegin();
2172 if (dnaCol != sf.getEnd())
2174 // not handling multi-locus variant features
2177 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2179 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2182 // feature doesn't lie within coding region
2185 int peptidePosition = mapsTo[0];
2186 String[][] codonVariants = variants.get(peptidePosition);
2187 if (codonVariants == null)
2189 codonVariants = new String[3][];
2190 variants.put(peptidePosition, codonVariants);
2194 * extract dna variants to a string array
2196 String alls = (String) sf.getValue("alleles");
2201 String[] alleles = alls.toUpperCase().split(",");
2203 for (String allele : alleles)
2205 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2209 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2211 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2212 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2213 peptidePosition, peptidePosition));
2214 lastPeptidePostion = peptidePosition;
2218 * save nucleotide (and this variant) for each codon position
2220 for (int codonPos = 0; codonPos < 3; codonPos++)
2222 String nucleotide = String.valueOf(
2223 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2225 if (codonVariants[codonPos] == null)
2228 * record current dna base
2230 codonVariants[codonPos] = new String[] { nucleotide };
2232 if (codon[codonPos] == dnaCol)
2235 * add alleles to dna base (and any previously found alleles)
2237 String[] known = codonVariants[codonPos];
2238 String[] dnaVariants = new String[alleles.length + known.length];
2239 System.arraycopy(known, 0, dnaVariants, 0, known.length);
2240 System.arraycopy(alleles, 0, dnaVariants, known.length,
2242 codonVariants[codonPos] = dnaVariants;
2251 * Returns a sorted, non-redundant list of all peptide translations generated
2252 * by the given dna variants, excluding the current residue value
2254 * @param codonVariants
2255 * an array of base values (acgtACGT) for codon positions 1, 2, 3
2257 * the current residue translation
2260 static List<String> computePeptideVariants(
2261 String[][] codonVariants, String residue)
2263 List<String> result = new ArrayList<String>();
2264 for (String base1 : codonVariants[0])
2266 for (String base2 : codonVariants[1])
2268 for (String base3 : codonVariants[2])
2270 String codon = base1 + base2 + base3;
2272 * get peptide translation of codon e.g. GAT -> D
2273 * note that variants which are not single alleles,
2274 * e.g. multibase variants or HGMD_MUTATION etc
2277 String peptide = codon.contains("-") ? "-"
2278 : (codon.length() > 3 ? null : ResidueProperties
2279 .codonTranslate(codon));
2280 if (peptide != null && !result.contains(peptide)
2281 && !peptide.equalsIgnoreCase(residue))
2283 result.add(peptide);
2290 * sort alphabetically with STOP at the end
2292 Collections.sort(result, new Comparator<String>()
2296 public int compare(String o1, String o2)
2298 if ("STOP".equals(o1))
2302 else if ("STOP".equals(o2))
2308 return o1.compareTo(o2);