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.IncompleteCodonException;
30 import jalview.datamodel.Mapping;
31 import jalview.datamodel.Sequence;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.io.gff.SequenceOntologyFactory;
36 import jalview.io.gff.SequenceOntologyI;
37 import jalview.schemes.ResidueProperties;
38 import jalview.util.Comparison;
39 import jalview.util.MapList;
40 import jalview.util.MappingUtils;
42 import java.io.UnsupportedEncodingException;
43 import java.net.URLEncoder;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Collection;
47 import java.util.Collections;
48 import java.util.Comparator;
49 import java.util.HashMap;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.LinkedHashMap;
53 import java.util.List;
55 import java.util.Map.Entry;
56 import java.util.NoSuchElementException;
58 import java.util.TreeMap;
61 * grab bag of useful alignment manipulation operations Expect these to be
62 * refactored elsewhere at some point.
67 public class AlignmentUtils
70 private static final String SEQUENCE_VARIANT = "sequence_variant:";
71 private static final String ID = "ID";
72 private static final String CLINICAL_SIGNIFICANCE = "clinical_significance";
75 * A data model to hold the 'normal' base value at a position, and an optional
76 * sequence variant feature
78 static class DnaVariant
82 SequenceFeature variant;
84 DnaVariant(String nuc)
89 DnaVariant(String nuc, SequenceFeature var)
97 * given an existing alignment, create a new alignment including all, or up to
98 * flankSize additional symbols from each sequence's dataset sequence
104 public static AlignmentI expandContext(AlignmentI core, int flankSize)
106 List<SequenceI> sq = new ArrayList<SequenceI>();
108 for (SequenceI s : core.getSequences())
110 SequenceI newSeq = s.deriveSequence();
111 final int newSeqStart = newSeq.getStart() - 1;
112 if (newSeqStart > maxoffset
113 && newSeq.getDatasetSequence().getStart() < s.getStart())
115 maxoffset = newSeqStart;
121 maxoffset = Math.min(maxoffset, flankSize);
125 * now add offset left and right to create an expanded alignment
127 for (SequenceI s : sq)
130 while (ds.getDatasetSequence() != null)
132 ds = ds.getDatasetSequence();
134 int s_end = s.findPosition(s.getStart() + s.getLength());
135 // find available flanking residues for sequence
136 int ustream_ds = s.getStart() - ds.getStart();
137 int dstream_ds = ds.getEnd() - s_end;
139 // build new flanked sequence
141 // compute gap padding to start of flanking sequence
142 int offset = maxoffset - ustream_ds;
144 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
147 if (flankSize < ustream_ds)
149 // take up to flankSize residues
150 offset = maxoffset - flankSize;
151 ustream_ds = flankSize;
153 if (flankSize <= dstream_ds)
155 dstream_ds = flankSize - 1;
158 // TODO use Character.toLowerCase to avoid creating String objects?
159 char[] upstream = new String(ds.getSequence(s.getStart() - 1
160 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
161 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
162 + dstream_ds)).toLowerCase().toCharArray();
163 char[] coreseq = s.getSequence();
164 char[] nseq = new char[offset + upstream.length + downstream.length
166 char c = core.getGapCharacter();
169 for (; p < offset; p++)
174 System.arraycopy(upstream, 0, nseq, p, upstream.length);
175 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
177 System.arraycopy(downstream, 0, nseq, p + coreseq.length
178 + upstream.length, downstream.length);
179 s.setSequence(new String(nseq));
180 s.setStart(s.getStart() - ustream_ds);
181 s.setEnd(s_end + downstream.length);
183 AlignmentI newAl = new jalview.datamodel.Alignment(
184 sq.toArray(new SequenceI[0]));
185 for (SequenceI s : sq)
187 if (s.getAnnotation() != null)
189 for (AlignmentAnnotation aa : s.getAnnotation())
191 aa.adjustForAlignment(); // JAL-1712 fix
192 newAl.addAnnotation(aa);
196 newAl.setDataset(core.getDataset());
201 * Returns the index (zero-based position) of a sequence in an alignment, or
208 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
212 for (SequenceI alSeq : al.getSequences())
225 * Returns a map of lists of sequences in the alignment, keyed by sequence
226 * name. For use in mapping between different alignment views of the same
229 * @see jalview.datamodel.AlignmentI#getSequencesByName()
231 public static Map<String, List<SequenceI>> getSequencesByName(
234 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
235 for (SequenceI seq : al.getSequences())
237 String name = seq.getName();
240 List<SequenceI> seqs = theMap.get(name);
243 seqs = new ArrayList<SequenceI>();
244 theMap.put(name, seqs);
253 * Build mapping of protein to cDNA alignment. Mappings are made between
254 * sequences where the cDNA translates to the protein sequence. Any new
255 * mappings are added to the protein alignment. Returns true if any mappings
256 * either already exist or were added, else false.
258 * @param proteinAlignment
259 * @param cdnaAlignment
262 public static boolean mapProteinAlignmentToCdna(
263 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
265 if (proteinAlignment == null || cdnaAlignment == null)
270 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
271 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
274 * First pass - map sequences where cross-references exist. This include
275 * 1-to-many mappings to support, for example, variant cDNA.
277 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
278 cdnaAlignment, mappedDna, mappedProtein, true);
281 * Second pass - map sequences where no cross-references exist. This only
282 * does 1-to-1 mappings and assumes corresponding sequences are in the same
283 * order in the alignments.
285 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
286 mappedDna, mappedProtein, false);
287 return mappingPerformed;
291 * Make mappings between compatible sequences (where the cDNA translation
292 * matches the protein).
294 * @param proteinAlignment
295 * @param cdnaAlignment
297 * a set of mapped DNA sequences (to add to)
298 * @param mappedProtein
299 * a set of mapped Protein sequences (to add to)
301 * if true, only map sequences where xrefs exist
304 protected static boolean mapProteinToCdna(
305 final AlignmentI proteinAlignment,
306 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
307 Set<SequenceI> mappedProtein, boolean xrefsOnly)
309 boolean mappingExistsOrAdded = false;
310 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
311 for (SequenceI aaSeq : thisSeqs)
313 boolean proteinMapped = false;
314 AlignedCodonFrame acf = new AlignedCodonFrame();
316 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
319 * Always try to map if sequences have xref to each other; this supports
320 * variant cDNA or alternative splicing for a protein sequence.
322 * If no xrefs, try to map progressively, assuming that alignments have
323 * mappable sequences in corresponding order. These are not
324 * many-to-many, as that would risk mixing species with similar cDNA
327 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
333 * Don't map non-xrefd sequences more than once each. This heuristic
334 * allows us to pair up similar sequences in ordered alignments.
337 && (mappedProtein.contains(aaSeq) || mappedDna
342 if (mappingExists(proteinAlignment.getCodonFrames(),
343 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
345 mappingExistsOrAdded = true;
349 MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
352 acf.addMap(cdnaSeq, aaSeq, map);
353 mappingExistsOrAdded = true;
354 proteinMapped = true;
355 mappedDna.add(cdnaSeq);
356 mappedProtein.add(aaSeq);
362 proteinAlignment.addCodonFrame(acf);
365 return mappingExistsOrAdded;
369 * Answers true if the mappings include one between the given (dataset)
372 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
373 SequenceI aaSeq, SequenceI cdnaSeq)
375 if (mappings != null)
377 for (AlignedCodonFrame acf : mappings)
379 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
389 * Builds a mapping (if possible) of a cDNA to a protein sequence.
391 * <li>first checks if the cdna translates exactly to the protein sequence</li>
392 * <li>else checks for translation after removing a STOP codon</li>
393 * <li>else checks for translation after removing a START codon</li>
394 * <li>if that fails, inspect CDS features on the cDNA sequence</li>
396 * Returns null if no mapping is determined.
399 * the aligned protein sequence
401 * the aligned cdna sequence
404 public static MapList mapCdnaToProtein(SequenceI proteinSeq,
408 * Here we handle either dataset sequence set (desktop) or absent (applet).
409 * Use only the char[] form of the sequence to avoid creating possibly large
412 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
413 char[] aaSeqChars = proteinDataset != null ? proteinDataset
414 .getSequence() : proteinSeq.getSequence();
415 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
416 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
417 : cdnaSeq.getSequence();
418 if (aaSeqChars == null || cdnaSeqChars == null)
424 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
426 final int mappedLength = 3 * aaSeqChars.length;
427 int cdnaLength = cdnaSeqChars.length;
428 int cdnaStart = cdnaSeq.getStart();
429 int cdnaEnd = cdnaSeq.getEnd();
430 final int proteinStart = proteinSeq.getStart();
431 final int proteinEnd = proteinSeq.getEnd();
434 * If lengths don't match, try ignoring stop codon (if present)
436 if (cdnaLength != mappedLength && cdnaLength > 2)
438 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
440 for (String stop : ResidueProperties.STOP)
442 if (lastCodon.equals(stop))
452 * If lengths still don't match, try ignoring start codon.
455 if (cdnaLength != mappedLength
457 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
458 .equals(ResidueProperties.START))
465 if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
468 * protein is translation of dna (+/- start/stop codons)
470 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
471 { proteinStart, proteinEnd }, 3, 1);
476 * translation failed - try mapping CDS annotated regions of dna
478 return mapCdsToProtein(cdnaSeq, proteinSeq);
482 * Test whether the given cdna sequence, starting at the given offset,
483 * translates to the given amino acid sequence, using the standard translation
484 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
486 * @param cdnaSeqChars
491 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
494 if (cdnaSeqChars == null || aaSeqChars == null)
500 int dnaPos = cdnaStart;
501 for (; dnaPos < cdnaSeqChars.length - 2
502 && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
504 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
505 final String translated = ResidueProperties.codonTranslate(codon);
508 * allow * in protein to match untranslatable in dna
510 final char aaRes = aaSeqChars[aaPos];
511 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
515 if (translated == null || !(aaRes == translated.charAt(0)))
518 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
519 // + codon + "(" + translated + ") != " + aaRes));
525 * check we matched all of the protein sequence
527 if (aaPos != aaSeqChars.length)
533 * check we matched all of the dna except
534 * for optional trailing STOP codon
536 if (dnaPos == cdnaSeqChars.length)
540 if (dnaPos == cdnaSeqChars.length - 3)
542 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
543 if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
552 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
553 * currently assumes that we are aligning cDNA to match protein.
556 * the sequence to be realigned
558 * the alignment whose sequence alignment is to be 'copied'
560 * character string represent a gap in the realigned sequence
561 * @param preserveUnmappedGaps
562 * @param preserveMappedGaps
563 * @return true if the sequence was realigned, false if it could not be
565 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
566 String gap, boolean preserveMappedGaps,
567 boolean preserveUnmappedGaps)
570 * Get any mappings from the source alignment to the target (dataset)
573 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
574 // all mappings. Would it help to constrain this?
575 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
576 if (mappings == null || mappings.isEmpty())
582 * Locate the aligned source sequence whose dataset sequence is mapped. We
583 * just take the first match here (as we can't align like more than one
586 SequenceI alignFrom = null;
587 AlignedCodonFrame mapping = null;
588 for (AlignedCodonFrame mp : mappings)
590 alignFrom = mp.findAlignedSequence(seq, al);
591 if (alignFrom != null)
598 if (alignFrom == null)
602 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
603 preserveMappedGaps, preserveUnmappedGaps);
608 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
609 * match residues and codons. Flags control whether existing gaps in unmapped
610 * (intron) and mapped (exon) regions are preserved or not. Gaps between
611 * intron and exon are only retained if both flags are set.
618 * @param preserveUnmappedGaps
619 * @param preserveMappedGaps
621 public static void alignSequenceAs(SequenceI alignTo,
622 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
623 char sourceGap, boolean preserveMappedGaps,
624 boolean preserveUnmappedGaps)
626 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
628 // aligned and dataset sequence positions, all base zero
632 int basesWritten = 0;
633 char myGapChar = myGap.charAt(0);
634 int ratio = myGap.length();
636 int fromOffset = alignFrom.getStart() - 1;
637 int toOffset = alignTo.getStart() - 1;
638 int sourceGapMappedLength = 0;
639 boolean inExon = false;
640 final char[] thisSeq = alignTo.getSequence();
641 final char[] thatAligned = alignFrom.getSequence();
642 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
645 * Traverse the 'model' aligned sequence
647 for (char sourceChar : thatAligned)
649 if (sourceChar == sourceGap)
651 sourceGapMappedLength += ratio;
656 * Found a non-gap character. Locate its mapped region if any.
659 // Note mapping positions are base 1, our sequence positions base 0
660 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
661 sourceDsPos + fromOffset);
662 if (mappedPos == null)
665 * unmapped position; treat like a gap
667 sourceGapMappedLength += ratio;
668 // System.err.println("Can't align: no codon mapping to residue "
669 // + sourceDsPos + "(" + sourceChar + ")");
674 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
675 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
676 StringBuilder trailingCopiedGap = new StringBuilder();
679 * Copy dna sequence up to and including this codon. Optionally, include
680 * gaps before the codon starts (in introns) and/or after the codon starts
683 * Note this only works for 'linear' splicing, not reverse or interleaved.
684 * But then 'align dna as protein' doesn't make much sense otherwise.
686 int intronLength = 0;
687 while (basesWritten + toOffset < mappedCodonEnd
688 && thisSeqPos < thisSeq.length)
690 final char c = thisSeq[thisSeqPos++];
694 int sourcePosition = basesWritten + toOffset;
695 if (sourcePosition < mappedCodonStart)
698 * Found an unmapped (intron) base. First add in any preceding gaps
701 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
703 thisAligned.append(trailingCopiedGap.toString());
704 intronLength += trailingCopiedGap.length();
705 trailingCopiedGap = new StringBuilder();
712 final boolean startOfCodon = sourcePosition == mappedCodonStart;
713 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
714 preserveUnmappedGaps, sourceGapMappedLength, inExon,
715 trailingCopiedGap.length(), intronLength, startOfCodon);
716 for (int i = 0; i < gapsToAdd; i++)
718 thisAligned.append(myGapChar);
720 sourceGapMappedLength = 0;
723 thisAligned.append(c);
724 trailingCopiedGap = new StringBuilder();
728 if (inExon && preserveMappedGaps)
730 trailingCopiedGap.append(myGapChar);
732 else if (!inExon && preserveUnmappedGaps)
734 trailingCopiedGap.append(myGapChar);
741 * At end of model aligned sequence. Copy any remaining target sequence, optionally
742 * including (intron) gaps.
744 while (thisSeqPos < thisSeq.length)
746 final char c = thisSeq[thisSeqPos++];
747 if (c != myGapChar || preserveUnmappedGaps)
749 thisAligned.append(c);
751 sourceGapMappedLength--;
755 * finally add gaps to pad for any trailing source gaps or
756 * unmapped characters
758 if (preserveUnmappedGaps)
760 while (sourceGapMappedLength > 0)
762 thisAligned.append(myGapChar);
763 sourceGapMappedLength--;
768 * All done aligning, set the aligned sequence.
770 alignTo.setSequence(new String(thisAligned));
774 * Helper method to work out how many gaps to insert when realigning.
776 * @param preserveMappedGaps
777 * @param preserveUnmappedGaps
778 * @param sourceGapMappedLength
780 * @param trailingCopiedGap
781 * @param intronLength
782 * @param startOfCodon
785 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
786 boolean preserveUnmappedGaps, int sourceGapMappedLength,
787 boolean inExon, int trailingGapLength, int intronLength,
788 final boolean startOfCodon)
794 * Reached start of codon. Ignore trailing gaps in intron unless we are
795 * preserving gaps in both exon and intron. Ignore them anyway if the
796 * protein alignment introduces a gap at least as large as the intronic
799 if (inExon && !preserveMappedGaps)
801 trailingGapLength = 0;
803 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
805 trailingGapLength = 0;
809 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
813 if (intronLength + trailingGapLength <= sourceGapMappedLength)
815 gapsToAdd = sourceGapMappedLength - intronLength;
819 gapsToAdd = Math.min(intronLength + trailingGapLength
820 - sourceGapMappedLength, trailingGapLength);
827 * second or third base of codon; check for any gaps in dna
829 if (!preserveMappedGaps)
831 trailingGapLength = 0;
833 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
839 * Realigns the given protein to match the alignment of the dna, using codon
840 * mappings to translate aligned codon positions to protein residues.
843 * the alignment whose sequences are realigned by this method
845 * the dna alignment whose alignment we are 'copying'
846 * @return the number of sequences that were realigned
848 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
850 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
851 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
852 protein, dna, unmappedProtein);
853 return alignProteinAs(protein, alignedCodons, unmappedProtein);
857 * Builds a map whose key is an aligned codon position (3 alignment column
858 * numbers base 0), and whose value is a map from protein sequence to each
859 * protein's peptide residue for that codon. The map generates an ordering of
860 * the codons, and allows us to read off the peptides at each position in
861 * order to assemble 'aligned' protein sequences.
864 * the protein alignment
866 * the coding dna alignment
867 * @param unmappedProtein
868 * any unmapped proteins are added to this list
871 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
872 AlignmentI protein, AlignmentI dna,
873 List<SequenceI> unmappedProtein)
876 * maintain a list of any proteins with no mappings - these will be
877 * rendered 'as is' in the protein alignment as we can't align them
879 unmappedProtein.addAll(protein.getSequences());
881 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
884 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
885 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
886 * comparator keeps the codon positions ordered.
888 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
889 new CodonComparator());
891 for (SequenceI dnaSeq : dna.getSequences())
893 for (AlignedCodonFrame mapping : mappings)
895 SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
898 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
899 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
900 seqMap, alignedCodons);
901 unmappedProtein.remove(prot);
907 * Finally add any unmapped peptide start residues (e.g. for incomplete
908 * codons) as if at the codon position before the second residue
910 // TODO resolve JAL-2022 so this fudge can be removed
911 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
912 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
914 return alignedCodons;
918 * Scans for any protein mapped from position 2 (meaning unmapped start
919 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
920 * preceding position in the alignment
922 * @param alignedCodons
923 * the codon-to-peptide map
924 * @param mappedSequenceCount
925 * the number of distinct sequences in the map
927 protected static void addUnmappedPeptideStarts(
928 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
929 int mappedSequenceCount)
931 // TODO delete this ugly hack once JAL-2022 is resolved
932 // i.e. we can model startPhase > 0 (incomplete start codon)
934 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
935 AlignedCodon lastCodon = null;
936 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
938 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
941 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
944 SequenceI seq = sequenceCodon.getKey();
945 if (sequencesChecked.contains(seq))
949 sequencesChecked.add(seq);
950 AlignedCodon codon = sequenceCodon.getValue();
951 if (codon.peptideCol > 1)
954 .println("Problem mapping protein with >1 unmapped start positions: "
957 else if (codon.peptideCol == 1)
960 * first position (peptideCol == 0) was unmapped - add it
962 if (lastCodon != null)
964 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
965 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
967 toAdd.put(seq, firstPeptide);
972 * unmapped residue at start of alignment (no prior column) -
973 * 'insert' at nominal codon [0, 0, 0]
975 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
976 String.valueOf(seq.getCharAt(0)), 0);
977 toAdd.put(seq, firstPeptide);
980 if (sequencesChecked.size() == mappedSequenceCount)
982 // no need to check past first mapped position in all sequences
986 lastCodon = entry.getKey();
990 * add any new codons safely after iterating over the map
992 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
994 addCodonToMap(alignedCodons, startCodon.getValue(),
995 startCodon.getKey());
1000 * Update the aligned protein sequences to match the codon alignments given in
1004 * @param alignedCodons
1005 * an ordered map of codon positions (columns), with sequence/peptide
1006 * values present in each column
1007 * @param unmappedProtein
1010 protected static int alignProteinAs(AlignmentI protein,
1011 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1012 List<SequenceI> unmappedProtein)
1015 * Prefill aligned sequences with gaps before inserting aligned protein
1018 int alignedWidth = alignedCodons.size();
1019 char[] gaps = new char[alignedWidth];
1020 Arrays.fill(gaps, protein.getGapCharacter());
1021 String allGaps = String.valueOf(gaps);
1022 for (SequenceI seq : protein.getSequences())
1024 if (!unmappedProtein.contains(seq))
1026 seq.setSequence(allGaps);
1031 for (AlignedCodon codon : alignedCodons.keySet())
1033 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1035 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1037 // place translated codon at its column position in sequence
1038 entry.getKey().getSequence()[column] = entry.getValue().product
1047 * Populate the map of aligned codons by traversing the given sequence
1048 * mapping, locating the aligned positions of mapped codons, and adding those
1049 * positions and their translation products to the map.
1052 * the aligned sequence we are mapping from
1054 * the sequence to be aligned to the codons
1056 * the gap character in the dna sequence
1058 * a mapping to a sequence translation
1059 * @param alignedCodons
1060 * the map we are building up
1062 static void addCodonPositions(SequenceI dna, SequenceI protein,
1063 char gapChar, Mapping seqMap,
1064 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1066 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1069 * add codon positions, and their peptide translations, to the alignment
1070 * map, while remembering the first codon mapped
1072 while (codons.hasNext())
1076 AlignedCodon codon = codons.next();
1077 addCodonToMap(alignedCodons, codon, protein);
1078 } catch (IncompleteCodonException e)
1080 // possible incomplete trailing codon - ignore
1081 } catch (NoSuchElementException e)
1083 // possibly peptide lacking STOP
1089 * Helper method to add a codon-to-peptide entry to the aligned codons map
1091 * @param alignedCodons
1095 protected static void addCodonToMap(
1096 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1097 AlignedCodon codon, SequenceI protein)
1099 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1100 if (seqProduct == null)
1102 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1103 alignedCodons.put(codon, seqProduct);
1105 seqProduct.put(protein, codon);
1109 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1110 * between at least one pair of sequences in the two alignments. Currently,
1113 * <li>One alignment must be nucleotide, and the other protein</li>
1114 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1115 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1116 * <li>The translation may ignore start and stop codons if present in the
1124 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1126 if (al1 == null || al2 == null)
1132 * Require one nucleotide and one protein
1134 if (al1.isNucleotide() == al2.isNucleotide())
1138 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1139 AlignmentI protein = dna == al1 ? al2 : al1;
1140 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1141 for (SequenceI dnaSeq : dna.getSequences())
1143 for (SequenceI proteinSeq : protein.getSequences())
1145 if (isMappable(dnaSeq, proteinSeq, mappings))
1155 * Returns true if the dna sequence is mapped, or could be mapped, to the
1163 protected static boolean isMappable(SequenceI dnaSeq,
1164 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1166 if (dnaSeq == null || proteinSeq == null)
1171 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1172 .getDatasetSequence();
1173 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1174 : proteinSeq.getDatasetSequence();
1176 for (AlignedCodonFrame mapping : mappings)
1178 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1188 * Just try to make a mapping (it is not yet stored), test whether
1191 return mapCdnaToProtein(proteinDs, dnaDs) != null;
1195 * Finds any reference annotations associated with the sequences in
1196 * sequenceScope, that are not already added to the alignment, and adds them
1197 * to the 'candidates' map. Also populates a lookup table of annotation
1198 * labels, keyed by calcId, for use in constructing tooltips or the like.
1200 * @param sequenceScope
1201 * the sequences to scan for reference annotations
1202 * @param labelForCalcId
1203 * (optional) map to populate with label for calcId
1205 * map to populate with annotations for sequence
1207 * the alignment to check for presence of annotations
1209 public static void findAddableReferenceAnnotations(
1210 List<SequenceI> sequenceScope,
1211 Map<String, String> labelForCalcId,
1212 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1215 if (sequenceScope == null)
1221 * For each sequence in scope, make a list of any annotations on the
1222 * underlying dataset sequence which are not already on the alignment.
1224 * Add to a map of { alignmentSequence, <List of annotations to add> }
1226 for (SequenceI seq : sequenceScope)
1228 SequenceI dataset = seq.getDatasetSequence();
1229 if (dataset == null)
1233 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1234 if (datasetAnnotations == null)
1238 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1239 for (AlignmentAnnotation dsann : datasetAnnotations)
1242 * Find matching annotations on the alignment. If none is found, then
1243 * add this annotation to the list of 'addable' annotations for this
1246 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1247 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1248 if (!matchedAlignmentAnnotations.iterator().hasNext())
1251 if (labelForCalcId != null)
1253 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1258 * Save any addable annotations for this sequence
1260 if (!result.isEmpty())
1262 candidates.put(seq, result);
1268 * Adds annotations to the top of the alignment annotations, in the same order
1269 * as their related sequences.
1271 * @param annotations
1272 * the annotations to add
1274 * the alignment to add them to
1275 * @param selectionGroup
1276 * current selection group (or null if none)
1278 public static void addReferenceAnnotations(
1279 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1280 final AlignmentI alignment, final SequenceGroup selectionGroup)
1282 for (SequenceI seq : annotations.keySet())
1284 for (AlignmentAnnotation ann : annotations.get(seq))
1286 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1288 int endRes = ann.annotations.length;
1289 if (selectionGroup != null)
1291 startRes = selectionGroup.getStartRes();
1292 endRes = selectionGroup.getEndRes();
1294 copyAnn.restrict(startRes, endRes);
1297 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1298 * original annotation is already on the sequence.
1300 if (!seq.hasAnnotation(ann))
1302 seq.addAlignmentAnnotation(copyAnn);
1305 copyAnn.adjustForAlignment();
1306 // add to the alignment and set visible
1307 alignment.addAnnotation(copyAnn);
1308 copyAnn.visible = true;
1314 * Set visibility of alignment annotations of specified types (labels), for
1315 * specified sequences. This supports controls like
1316 * "Show all secondary structure", "Hide all Temp factor", etc.
1318 * @al the alignment to scan for annotations
1320 * the types (labels) of annotations to be updated
1321 * @param forSequences
1322 * if not null, only annotations linked to one of these sequences are
1323 * in scope for update; if null, acts on all sequence annotations
1325 * if this flag is true, 'types' is ignored (label not checked)
1327 * if true, set visibility on, else set off
1329 public static void showOrHideSequenceAnnotations(AlignmentI al,
1330 Collection<String> types, List<SequenceI> forSequences,
1331 boolean anyType, boolean doShow)
1333 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1335 if (anyType || types.contains(aa.label))
1337 if ((aa.sequenceRef != null)
1338 && (forSequences == null || forSequences
1339 .contains(aa.sequenceRef)))
1341 aa.visible = doShow;
1348 * Returns true if either sequence has a cross-reference to the other
1354 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1356 // Note: moved here from class CrossRef as the latter class has dependencies
1357 // not availability to the applet's classpath
1358 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1362 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1363 * that sequence name is structured as Source|AccessionId.
1369 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1371 if (seq1 == null || seq2 == null)
1375 String name = seq2.getName();
1376 final DBRefEntry[] xrefs = seq1.getDBRefs();
1379 for (DBRefEntry xref : xrefs)
1381 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1382 // case-insensitive test, consistent with DBRefEntry.equalRef()
1383 if (xrefName.equalsIgnoreCase(name))
1393 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1394 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1395 * added to the original alignment's dataset, which is shared by the new
1396 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1397 * added to the alignment dataset.
1400 * aligned dna sequences
1402 * from dna to protein
1404 * @return an alignment whose sequences are the cds-only parts of the dna
1405 * sequences (or null if no mappings are found)
1407 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1408 List<AlignedCodonFrame> mappings, AlignmentI al)
1410 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1412 for (SequenceI seq : dna)
1414 AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1415 List<AlignedCodonFrame> seqMappings = MappingUtils
1416 .findMappingsForSequence(seq, mappings);
1417 List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1418 for (AlignedCodonFrame mapping : seqMappings)
1420 for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1422 SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1424 cdsSeqs.add(cdsSeq);
1427 * add a mapping from CDS to the (unchanged) mapped to range
1429 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1430 cdsSeq.getLength() });
1431 MapList map = new MapList(cdsRange, aMapping.getMap()
1432 .getToRanges(), aMapping.getMap().getFromRatio(),
1433 aMapping.getMap().getToRatio());
1434 cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1437 * add another mapping from original 'from' range to CDS
1439 map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1441 cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1443 alignmentMappings.add(cdsMappings);
1446 * transfer any features on dna that overlap the CDS
1448 transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1454 * add CDS seqs to shared dataset
1456 Alignment dataset = al.getDataset();
1457 for (SequenceI seq : cdsSeqs)
1459 if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1461 dataset.addSequence(seq.getDatasetSequence());
1464 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1466 cds.setDataset(dataset);
1472 * Helper method that makes a CDS sequence as defined by the mappings from the
1473 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1474 * forward or reverse strand).
1480 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1482 char[] seqChars = seq.getSequence();
1483 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1484 int cdsWidth = MappingUtils.getLength(fromRanges);
1485 char[] newSeqChars = new char[cdsWidth];
1488 for (int[] range : fromRanges)
1490 if (range[0] <= range[1])
1492 // forward strand mapping - just copy the range
1493 int length = range[1] - range[0] + 1;
1494 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1500 // reverse strand mapping - copy and complement one by one
1501 for (int i = range[0]; i >= range[1]; i--)
1503 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1508 SequenceI newSeq = new Sequence(seq.getName() + "|"
1509 + mapping.getTo().getName(), newSeqChars, 1, newPos);
1510 newSeq.createDatasetSequence();
1515 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1516 * feature start/end ranges, optionally omitting specified feature types.
1517 * Returns the number of features copied.
1522 * if not null, only features of this type are copied (including
1523 * subtypes in the Sequence Ontology)
1525 * the mapping from 'fromSeq' to 'toSeq'
1528 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1529 MapList mapping, String select, String... omitting)
1531 SequenceI copyTo = toSeq;
1532 while (copyTo.getDatasetSequence() != null)
1534 copyTo = copyTo.getDatasetSequence();
1537 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1539 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1542 for (SequenceFeature sf : sfs)
1544 String type = sf.getType();
1545 if (select != null && !so.isA(type, select))
1549 boolean omit = false;
1550 for (String toOmit : omitting)
1552 if (type.equals(toOmit))
1563 * locate the mapped range - null if either start or end is
1564 * not mapped (no partial overlaps are calculated)
1566 int start = sf.getBegin();
1567 int end = sf.getEnd();
1568 int[] mappedTo = mapping.locateInTo(start, end);
1570 * if whole exon range doesn't map, try interpreting it
1571 * as 5' or 3' exon overlapping the CDS range
1573 if (mappedTo == null)
1575 mappedTo = mapping.locateInTo(end, end);
1576 if (mappedTo != null)
1579 * end of exon is in CDS range - 5' overlap
1580 * to a range from the start of the peptide
1585 if (mappedTo == null)
1587 mappedTo = mapping.locateInTo(start, start);
1588 if (mappedTo != null)
1591 * start of exon is in CDS range - 3' overlap
1592 * to a range up to the end of the peptide
1594 mappedTo[1] = toSeq.getLength();
1597 if (mappedTo != null)
1599 SequenceFeature copy = new SequenceFeature(sf);
1600 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1601 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1602 copyTo.addSequenceFeature(copy);
1611 * Returns a mapping from dna to protein by inspecting sequence features of
1612 * type "CDS" on the dna.
1618 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1619 SequenceI proteinSeq)
1621 List<int[]> ranges = findCdsPositions(dnaSeq);
1622 int mappedDnaLength = MappingUtils.getLength(ranges);
1624 int proteinLength = proteinSeq.getLength();
1625 int proteinStart = proteinSeq.getStart();
1626 int proteinEnd = proteinSeq.getEnd();
1629 * incomplete start codon may mean X at start of peptide
1630 * we ignore both for mapping purposes
1632 if (proteinSeq.getCharAt(0) == 'X')
1634 // todo JAL-2022 support startPhase > 0
1638 List<int[]> proteinRange = new ArrayList<int[]>();
1641 * dna length should map to protein (or protein plus stop codon)
1643 int codesForResidues = mappedDnaLength / 3;
1644 if (codesForResidues == (proteinLength + 1))
1646 // assuming extra codon is for STOP and not in peptide
1649 if (codesForResidues == proteinLength)
1651 proteinRange.add(new int[] { proteinStart, proteinEnd });
1652 return new MapList(ranges, proteinRange, 3, 1);
1658 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1659 * start/end positions of sequence features of type "CDS" (or a sub-type of
1660 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1661 * position order, so this method is only valid for linear CDS in the same
1662 * sense as the protein product.
1667 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1669 List<int[]> result = new ArrayList<int[]>();
1670 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1676 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1679 for (SequenceFeature sf : sfs)
1682 * process a CDS feature (or a sub-type of CDS)
1684 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1689 phase = Integer.parseInt(sf.getPhase());
1690 } catch (NumberFormatException e)
1695 * phase > 0 on first codon means 5' incomplete - skip to the start
1696 * of the next codon; example ENST00000496384
1698 int begin = sf.getBegin();
1699 int end = sf.getEnd();
1700 if (result.isEmpty())
1705 // shouldn't happen!
1707 .println("Error: start phase extends beyond start CDS in "
1708 + dnaSeq.getName());
1711 result.add(new int[] { begin, end });
1716 * remove 'startPhase' positions (usually 0) from the first range
1717 * so we begin at the start of a complete codon
1719 if (!result.isEmpty())
1721 // TODO JAL-2022 correctly model start phase > 0
1722 result.get(0)[0] += startPhase;
1726 * Finally sort ranges by start position. This avoids a dependency on
1727 * keeping features in order on the sequence (if they are in order anyway,
1728 * the sort will have almost no work to do). The implicit assumption is CDS
1729 * ranges are assembled in order. Other cases should not use this method,
1730 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1732 Collections.sort(result, new Comparator<int[]>()
1735 public int compare(int[] o1, int[] o2)
1737 return Integer.compare(o1[0], o2[0]);
1744 * Maps exon features from dna to protein, and computes variants in peptide
1745 * product generated by variants in dna, and adds them as sequence_variant
1746 * features on the protein sequence. Returns the number of variant features
1751 * @param dnaToProtein
1753 public static int computeProteinFeatures(SequenceI dnaSeq,
1754 SequenceI peptide, MapList dnaToProtein)
1756 while (dnaSeq.getDatasetSequence() != null)
1758 dnaSeq = dnaSeq.getDatasetSequence();
1760 while (peptide.getDatasetSequence() != null)
1762 peptide = peptide.getDatasetSequence();
1765 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1768 * compute protein variants from dna variants and codon mappings;
1769 * NB - alternatively we could retrieve this using the REST service e.g.
1770 * http://rest.ensembl.org/overlap/translation
1771 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1772 * which would be a bit slower but possibly more reliable
1776 * build a map with codon variations for each potentially varying peptide
1778 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1779 dnaSeq, dnaToProtein);
1782 * scan codon variations, compute peptide variants and add to peptide sequence
1785 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1787 int peptidePos = variant.getKey();
1788 List<DnaVariant>[] codonVariants = variant.getValue();
1789 count += computePeptideVariants(peptide, peptidePos, codonVariants);
1793 * sort to get sequence features in start position order
1794 * - would be better to store in Sequence as a TreeSet or NCList?
1796 Arrays.sort(peptide.getSequenceFeatures(),
1797 new Comparator<SequenceFeature>()
1800 public int compare(SequenceFeature o1, SequenceFeature o2)
1802 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1803 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1811 * Computes non-synonymous peptide variants from codon variants and adds them
1812 * as sequence_variant features on the protein sequence (one feature per
1813 * allele variant). Selected attributes (variant id, clinical significance)
1814 * are copied over to the new features.
1817 * the protein sequence
1819 * the position to compute peptide variants for
1820 * @param codonVariants
1821 * a list of dna variants per codon position
1822 * @return the number of features added
1824 static int computePeptideVariants(SequenceI peptide, int peptidePos,
1825 List<DnaVariant>[] codonVariants)
1827 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1829 String base1 = codonVariants[0].get(0).base;
1830 String base2 = codonVariants[1].get(0).base;
1831 String base3 = codonVariants[2].get(0).base;
1834 * variants in first codon base
1836 for (DnaVariant var : codonVariants[0])
1838 if (var.variant != null)
1840 String alleles = (String) var.variant.getValue("alleles");
1841 if (alleles != null)
1843 for (String base : alleles.split(","))
1845 String codon = base + base2 + base3;
1846 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1856 * variants in second codon base
1858 for (DnaVariant var : codonVariants[1])
1860 if (var.variant != null)
1862 String alleles = (String) var.variant.getValue("alleles");
1863 if (alleles != null)
1865 for (String base : alleles.split(","))
1867 String codon = base1 + base + base3;
1868 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1878 * variants in third codon base
1880 for (DnaVariant var : codonVariants[2])
1882 if (var.variant != null)
1884 String alleles = (String) var.variant.getValue("alleles");
1885 if (alleles != null)
1887 for (String base : alleles.split(","))
1889 String codon = base1 + base2 + base;
1890 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1903 * Helper method that adds a peptide variant feature, provided the given codon
1904 * translates to a value different to the current residue (is a non-synonymous
1905 * variant). ID and clinical_significance attributes of the dna variant (if
1906 * present) are copied to the new feature.
1913 * @return true if a feature was added, else false
1915 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1916 String residue, DnaVariant var, String codon)
1919 * get peptide translation of codon e.g. GAT -> D
1920 * note that variants which are not single alleles,
1921 * e.g. multibase variants or HGMD_MUTATION etc
1922 * are currently ignored here
1924 String trans = codon.contains("-") ? "-"
1925 : (codon.length() > 3 ? null : ResidueProperties
1926 .codonTranslate(codon));
1927 if (trans != null && !trans.equals(residue))
1929 String desc = residue + "->" + trans;
1930 // set score to 0f so 'graduated colour' option is offered!
1931 SequenceFeature sf = new SequenceFeature(
1932 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1933 peptidePos, 0f, null);
1934 String id = (String) var.variant.getValue(ID);
1937 if (id.startsWith(SEQUENCE_VARIANT))
1939 id = id.substring(SEQUENCE_VARIANT.length());
1941 sf.setValue(ID, id);
1942 // TODO handle other species variants
1943 StringBuilder link = new StringBuilder(32);
1946 link.append(desc).append(" ").append(id)
1947 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
1948 .append(URLEncoder.encode(id, "UTF-8"));
1949 sf.addLink(link.toString());
1950 } catch (UnsupportedEncodingException e)
1955 String clinSig = (String) var.variant
1956 .getValue(CLINICAL_SIGNIFICANCE);
1957 if (clinSig != null)
1959 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
1961 peptide.addSequenceFeature(sf);
1968 * Builds a map whose key is position in the protein sequence, and value is a
1969 * list of the base and all variants for each corresponding codon position
1972 * @param dnaToProtein
1975 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
1976 SequenceI dnaSeq, MapList dnaToProtein)
1979 * map from peptide position to all variants of the codon which codes for it
1980 * LinkedHashMap ensures we keep the peptide features in sequence order
1982 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
1983 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1985 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
1986 if (dnaFeatures == null)
1991 int dnaStart = dnaSeq.getStart();
1992 int[] lastCodon = null;
1993 int lastPeptidePostion = 0;
1996 * build a map of codon variations for peptides
1998 for (SequenceFeature sf : dnaFeatures)
2000 int dnaCol = sf.getBegin();
2001 if (dnaCol != sf.getEnd())
2003 // not handling multi-locus variant features
2006 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2008 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2011 // feature doesn't lie within coding region
2014 int peptidePosition = mapsTo[0];
2015 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2016 if (codonVariants == null)
2018 codonVariants = new ArrayList[3];
2019 codonVariants[0] = new ArrayList<DnaVariant>();
2020 codonVariants[1] = new ArrayList<DnaVariant>();
2021 codonVariants[2] = new ArrayList<DnaVariant>();
2022 variants.put(peptidePosition, codonVariants);
2026 * extract dna variants to a string array
2028 String alls = (String) sf.getValue("alleles");
2033 String[] alleles = alls.toUpperCase().split(",");
2035 for (String allele : alleles)
2037 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2041 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2043 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2044 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2045 peptidePosition, peptidePosition));
2046 lastPeptidePostion = peptidePosition;
2050 * save nucleotide (and any variant) for each codon position
2052 for (int codonPos = 0; codonPos < 3; codonPos++)
2054 String nucleotide = String.valueOf(
2055 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2057 List<DnaVariant> codonVariant = codonVariants[codonPos];
2058 if (codon[codonPos] == dnaCol)
2060 if (!codonVariant.isEmpty()
2061 && codonVariant.get(0).variant == null)
2064 * already recorded base value, add this variant
2066 codonVariant.get(0).variant = sf;
2071 * add variant with base value
2073 codonVariant.add(new DnaVariant(nucleotide, sf));
2076 else if (codonVariant.isEmpty())
2079 * record (possibly non-varying) base value
2081 codonVariant.add(new DnaVariant(nucleotide));
2090 * Makes an alignment with a copy of the given sequences, adding in any
2091 * non-redundant sequences which are mapped to by the cross-referenced
2098 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2101 AlignmentI copy = new Alignment(new Alignment(seqs));
2103 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2106 for (SequenceI xref : xrefs)
2108 DBRefEntry[] dbrefs = xref.getDBRefs();
2111 for (DBRefEntry dbref : dbrefs)
2113 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2117 SequenceI mappedTo = dbref.getMap().getTo();
2118 SequenceI match = matcher.findIdMatch(mappedTo);
2121 matcher.add(mappedTo);
2122 copy.addSequence(mappedTo);
2132 * Try to align sequences in 'unaligned' to match the alignment of their
2133 * mapped regions in 'aligned'. For example, could use this to align CDS
2134 * sequences which are mapped to their parent cDNA sequences.
2136 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2137 * dna-to-protein or protein-to-dna use alternative methods.
2140 * sequences to be aligned
2142 * holds aligned sequences and their mappings
2145 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2147 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2148 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2149 unaligned, aligned, unmapped);
2150 int width = columnMap.size();
2151 char gap = unaligned.getGapCharacter();
2152 int realignedCount = 0;
2154 for (SequenceI seq : unaligned.getSequences())
2156 if (!unmapped.contains(seq))
2158 char[] newSeq = new char[width];
2159 Arrays.fill(newSeq, gap);
2164 * traverse the map to find columns populated
2167 for (Integer column : columnMap.keySet())
2169 Character c = columnMap.get(column).get(seq);
2173 * sequence has a character at this position
2183 * trim trailing gaps
2185 if (lastCol < width)
2187 char[] tmp = new char[lastCol + 1];
2188 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2191 seq.setSequence(String.valueOf(newSeq));
2195 return realignedCount;
2199 * Returns a map whose key is alignment column number (base 1), and whose
2200 * values are a map of sequence characters in that column.
2207 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2208 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2211 * Map will hold, for each aligned column position, a map of
2212 * {unalignedSequence, sequenceCharacter} at that position.
2213 * TreeMap keeps the entries in ascending column order.
2215 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2218 * r any sequences that have no mapping so can't be realigned
2220 unmapped.addAll(unaligned.getSequences());
2222 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2224 for (SequenceI seq : unaligned.getSequences())
2226 for (AlignedCodonFrame mapping : mappings)
2228 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2229 if (fromSeq != null)
2231 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2232 if (addMappedPositions(seq, fromSeq, seqMap, map))
2234 unmapped.remove(seq);
2243 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2244 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2245 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2249 * the sequence whose column positions we are recording
2251 * a sequence that is mapped to the first sequence
2253 * the mapping from 'fromSeq' to 'seq'
2255 * a map to add the column positions (in fromSeq) of the mapped
2259 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2260 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2267 char[] fromChars = fromSeq.getSequence();
2268 int toStart = seq.getStart();
2269 char[] toChars = seq.getSequence();
2272 * traverse [start, end, start, end...] ranges in fromSeq
2274 for (int[] fromRange : seqMap.getMap().getFromRanges())
2276 for (int i = 0; i < fromRange.length - 1; i += 2)
2278 boolean forward = fromRange[i + 1] >= fromRange[i];
2281 * find the range mapped to (sequence positions base 1)
2283 int[] range = seqMap.locateMappedRange(fromRange[i],
2287 System.err.println("Error in mapping " + seqMap + " from "
2288 + fromSeq.getName());
2291 int fromCol = fromSeq.findIndex(fromRange[i]);
2292 int mappedCharPos = range[0];
2295 * walk over the 'from' aligned sequence in forward or reverse
2296 * direction; when a non-gap is found, record the column position
2297 * of the next character of the mapped-to sequence; stop when all
2298 * the characters of the range have been counted
2300 while (mappedCharPos <= range[1])
2302 if (!Comparison.isGap(fromChars[fromCol - 1]))
2305 * mapped from sequence has a character in this column
2306 * record the column position for the mapped to character
2308 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2309 if (seqsMap == null)
2311 seqsMap = new HashMap<SequenceI, Character>();
2312 map.put(fromCol, seqsMap);
2314 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2317 fromCol += (forward ? 1 : -1);
2324 // strictly temporary hack until proper criteria for aligning protein to cds
2325 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2326 public static boolean looksLikeEnsembl(AlignmentI alignment)
2328 for (SequenceI seq : alignment.getSequences())
2330 String name = seq.getName();
2331 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))