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 static jalview.io.gff.GffConstants.CLINICAL_SIGNIFICANCE;
25 import jalview.datamodel.AlignedCodon;
26 import jalview.datamodel.AlignedCodonFrame;
27 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.DBRefEntry;
32 import jalview.datamodel.IncompleteCodonException;
33 import jalview.datamodel.Mapping;
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.MapList;
43 import jalview.util.MappingUtils;
44 import jalview.util.StringUtils;
46 import java.io.UnsupportedEncodingException;
47 import java.net.URLEncoder;
48 import java.util.ArrayList;
49 import java.util.Arrays;
50 import java.util.Collection;
51 import java.util.Collections;
52 import java.util.Comparator;
53 import java.util.HashMap;
54 import java.util.HashSet;
55 import java.util.Iterator;
56 import java.util.LinkedHashMap;
57 import java.util.List;
59 import java.util.Map.Entry;
60 import java.util.NoSuchElementException;
62 import java.util.TreeMap;
65 * grab bag of useful alignment manipulation operations Expect these to be
66 * refactored elsewhere at some point.
71 public class AlignmentUtils
74 private static final String SEQUENCE_VARIANT = "sequence_variant:";
75 private static final String ID = "ID";
78 * A data model to hold the 'normal' base value at a position, and an optional
79 * sequence variant feature
81 static class DnaVariant
85 SequenceFeature variant;
87 DnaVariant(String nuc)
92 DnaVariant(String nuc, SequenceFeature var)
100 * given an existing alignment, create a new alignment including all, or up to
101 * flankSize additional symbols from each sequence's dataset sequence
107 public static AlignmentI expandContext(AlignmentI core, int flankSize)
109 List<SequenceI> sq = new ArrayList<SequenceI>();
111 for (SequenceI s : core.getSequences())
113 SequenceI newSeq = s.deriveSequence();
114 final int newSeqStart = newSeq.getStart() - 1;
115 if (newSeqStart > maxoffset
116 && newSeq.getDatasetSequence().getStart() < s.getStart())
118 maxoffset = newSeqStart;
124 maxoffset = Math.min(maxoffset, flankSize);
128 * now add offset left and right to create an expanded alignment
130 for (SequenceI s : sq)
133 while (ds.getDatasetSequence() != null)
135 ds = ds.getDatasetSequence();
137 int s_end = s.findPosition(s.getStart() + s.getLength());
138 // find available flanking residues for sequence
139 int ustream_ds = s.getStart() - ds.getStart();
140 int dstream_ds = ds.getEnd() - s_end;
142 // build new flanked sequence
144 // compute gap padding to start of flanking sequence
145 int offset = maxoffset - ustream_ds;
147 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
150 if (flankSize < ustream_ds)
152 // take up to flankSize residues
153 offset = maxoffset - flankSize;
154 ustream_ds = flankSize;
156 if (flankSize <= dstream_ds)
158 dstream_ds = flankSize - 1;
161 // TODO use Character.toLowerCase to avoid creating String objects?
162 char[] upstream = new String(ds.getSequence(s.getStart() - 1
163 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
164 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
165 + dstream_ds)).toLowerCase().toCharArray();
166 char[] coreseq = s.getSequence();
167 char[] nseq = new char[offset + upstream.length + downstream.length
169 char c = core.getGapCharacter();
172 for (; p < offset; p++)
177 System.arraycopy(upstream, 0, nseq, p, upstream.length);
178 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
180 System.arraycopy(downstream, 0, nseq, p + coreseq.length
181 + upstream.length, downstream.length);
182 s.setSequence(new String(nseq));
183 s.setStart(s.getStart() - ustream_ds);
184 s.setEnd(s_end + downstream.length);
186 AlignmentI newAl = new jalview.datamodel.Alignment(
187 sq.toArray(new SequenceI[0]));
188 for (SequenceI s : sq)
190 if (s.getAnnotation() != null)
192 for (AlignmentAnnotation aa : s.getAnnotation())
194 aa.adjustForAlignment(); // JAL-1712 fix
195 newAl.addAnnotation(aa);
199 newAl.setDataset(core.getDataset());
204 * Returns the index (zero-based position) of a sequence in an alignment, or
211 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
215 for (SequenceI alSeq : al.getSequences())
228 * Returns a map of lists of sequences in the alignment, keyed by sequence
229 * name. For use in mapping between different alignment views of the same
232 * @see jalview.datamodel.AlignmentI#getSequencesByName()
234 public static Map<String, List<SequenceI>> getSequencesByName(
237 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
238 for (SequenceI seq : al.getSequences())
240 String name = seq.getName();
243 List<SequenceI> seqs = theMap.get(name);
246 seqs = new ArrayList<SequenceI>();
247 theMap.put(name, seqs);
256 * Build mapping of protein to cDNA alignment. Mappings are made between
257 * sequences where the cDNA translates to the protein sequence. Any new
258 * mappings are added to the protein alignment. Returns true if any mappings
259 * either already exist or were added, else false.
261 * @param proteinAlignment
262 * @param cdnaAlignment
265 public static boolean mapProteinAlignmentToCdna(
266 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
268 if (proteinAlignment == null || cdnaAlignment == null)
273 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
274 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
277 * First pass - map sequences where cross-references exist. This include
278 * 1-to-many mappings to support, for example, variant cDNA.
280 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
281 cdnaAlignment, mappedDna, mappedProtein, true);
284 * Second pass - map sequences where no cross-references exist. This only
285 * does 1-to-1 mappings and assumes corresponding sequences are in the same
286 * order in the alignments.
288 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
289 mappedDna, mappedProtein, false);
290 return mappingPerformed;
294 * Make mappings between compatible sequences (where the cDNA translation
295 * matches the protein).
297 * @param proteinAlignment
298 * @param cdnaAlignment
300 * a set of mapped DNA sequences (to add to)
301 * @param mappedProtein
302 * a set of mapped Protein sequences (to add to)
304 * if true, only map sequences where xrefs exist
307 protected static boolean mapProteinToCdna(
308 final AlignmentI proteinAlignment,
309 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
310 Set<SequenceI> mappedProtein, boolean xrefsOnly)
312 boolean mappingExistsOrAdded = false;
313 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
314 for (SequenceI aaSeq : thisSeqs)
316 boolean proteinMapped = false;
317 AlignedCodonFrame acf = new AlignedCodonFrame();
319 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
322 * Always try to map if sequences have xref to each other; this supports
323 * variant cDNA or alternative splicing for a protein sequence.
325 * If no xrefs, try to map progressively, assuming that alignments have
326 * mappable sequences in corresponding order. These are not
327 * many-to-many, as that would risk mixing species with similar cDNA
330 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
336 * Don't map non-xrefd sequences more than once each. This heuristic
337 * allows us to pair up similar sequences in ordered alignments.
340 && (mappedProtein.contains(aaSeq) || mappedDna
345 if (mappingExists(proteinAlignment.getCodonFrames(),
346 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
348 mappingExistsOrAdded = true;
352 MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
355 acf.addMap(cdnaSeq, aaSeq, map);
356 mappingExistsOrAdded = true;
357 proteinMapped = true;
358 mappedDna.add(cdnaSeq);
359 mappedProtein.add(aaSeq);
365 proteinAlignment.addCodonFrame(acf);
368 return mappingExistsOrAdded;
372 * Answers true if the mappings include one between the given (dataset)
375 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
376 SequenceI aaSeq, SequenceI cdnaSeq)
378 if (mappings != null)
380 for (AlignedCodonFrame acf : mappings)
382 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
392 * Builds a mapping (if possible) of a cDNA to a protein sequence.
394 * <li>first checks if the cdna translates exactly to the protein sequence</li>
395 * <li>else checks for translation after removing a STOP codon</li>
396 * <li>else checks for translation after removing a START codon</li>
397 * <li>if that fails, inspect CDS features on the cDNA sequence</li>
399 * Returns null if no mapping is determined.
402 * the aligned protein sequence
404 * the aligned cdna sequence
407 public static MapList mapCdnaToProtein(SequenceI proteinSeq,
411 * Here we handle either dataset sequence set (desktop) or absent (applet).
412 * Use only the char[] form of the sequence to avoid creating possibly large
415 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
416 char[] aaSeqChars = proteinDataset != null ? proteinDataset
417 .getSequence() : proteinSeq.getSequence();
418 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
419 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
420 : cdnaSeq.getSequence();
421 if (aaSeqChars == null || cdnaSeqChars == null)
427 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
429 final int mappedLength = 3 * aaSeqChars.length;
430 int cdnaLength = cdnaSeqChars.length;
431 int cdnaStart = cdnaSeq.getStart();
432 int cdnaEnd = cdnaSeq.getEnd();
433 final int proteinStart = proteinSeq.getStart();
434 final int proteinEnd = proteinSeq.getEnd();
437 * If lengths don't match, try ignoring stop codon (if present)
439 if (cdnaLength != mappedLength && cdnaLength > 2)
441 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
443 for (String stop : ResidueProperties.STOP)
445 if (lastCodon.equals(stop))
455 * If lengths still don't match, try ignoring start codon.
458 if (cdnaLength != mappedLength
460 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
461 .equals(ResidueProperties.START))
468 if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
471 * protein is translation of dna (+/- start/stop codons)
473 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
474 { proteinStart, proteinEnd }, 3, 1);
479 * translation failed - try mapping CDS annotated regions of dna
481 return mapCdsToProtein(cdnaSeq, proteinSeq);
485 * Test whether the given cdna sequence, starting at the given offset,
486 * translates to the given amino acid sequence, using the standard translation
487 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
489 * @param cdnaSeqChars
494 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
497 if (cdnaSeqChars == null || aaSeqChars == null)
503 int dnaPos = cdnaStart;
504 for (; dnaPos < cdnaSeqChars.length - 2
505 && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
507 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
508 final String translated = ResidueProperties.codonTranslate(codon);
511 * allow * in protein to match untranslatable in dna
513 final char aaRes = aaSeqChars[aaPos];
514 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
518 if (translated == null || !(aaRes == translated.charAt(0)))
521 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
522 // + codon + "(" + translated + ") != " + aaRes));
528 * check we matched all of the protein sequence
530 if (aaPos != aaSeqChars.length)
536 * check we matched all of the dna except
537 * for optional trailing STOP codon
539 if (dnaPos == cdnaSeqChars.length)
543 if (dnaPos == cdnaSeqChars.length - 3)
545 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
546 if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
555 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
556 * currently assumes that we are aligning cDNA to match protein.
559 * the sequence to be realigned
561 * the alignment whose sequence alignment is to be 'copied'
563 * character string represent a gap in the realigned sequence
564 * @param preserveUnmappedGaps
565 * @param preserveMappedGaps
566 * @return true if the sequence was realigned, false if it could not be
568 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
569 String gap, boolean preserveMappedGaps,
570 boolean preserveUnmappedGaps)
573 * Get any mappings from the source alignment to the target (dataset)
576 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
577 // all mappings. Would it help to constrain this?
578 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
579 if (mappings == null || mappings.isEmpty())
585 * Locate the aligned source sequence whose dataset sequence is mapped. We
586 * just take the first match here (as we can't align like more than one
589 SequenceI alignFrom = null;
590 AlignedCodonFrame mapping = null;
591 for (AlignedCodonFrame mp : mappings)
593 alignFrom = mp.findAlignedSequence(seq, al);
594 if (alignFrom != null)
601 if (alignFrom == null)
605 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
606 preserveMappedGaps, preserveUnmappedGaps);
611 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
612 * match residues and codons. Flags control whether existing gaps in unmapped
613 * (intron) and mapped (exon) regions are preserved or not. Gaps between
614 * intron and exon are only retained if both flags are set.
621 * @param preserveUnmappedGaps
622 * @param preserveMappedGaps
624 public static void alignSequenceAs(SequenceI alignTo,
625 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
626 char sourceGap, boolean preserveMappedGaps,
627 boolean preserveUnmappedGaps)
629 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
631 // aligned and dataset sequence positions, all base zero
635 int basesWritten = 0;
636 char myGapChar = myGap.charAt(0);
637 int ratio = myGap.length();
639 int fromOffset = alignFrom.getStart() - 1;
640 int toOffset = alignTo.getStart() - 1;
641 int sourceGapMappedLength = 0;
642 boolean inExon = false;
643 final char[] thisSeq = alignTo.getSequence();
644 final char[] thatAligned = alignFrom.getSequence();
645 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
648 * Traverse the 'model' aligned sequence
650 for (char sourceChar : thatAligned)
652 if (sourceChar == sourceGap)
654 sourceGapMappedLength += ratio;
659 * Found a non-gap character. Locate its mapped region if any.
662 // Note mapping positions are base 1, our sequence positions base 0
663 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
664 sourceDsPos + fromOffset);
665 if (mappedPos == null)
668 * unmapped position; treat like a gap
670 sourceGapMappedLength += ratio;
671 // System.err.println("Can't align: no codon mapping to residue "
672 // + sourceDsPos + "(" + sourceChar + ")");
677 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
678 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
679 StringBuilder trailingCopiedGap = new StringBuilder();
682 * Copy dna sequence up to and including this codon. Optionally, include
683 * gaps before the codon starts (in introns) and/or after the codon starts
686 * Note this only works for 'linear' splicing, not reverse or interleaved.
687 * But then 'align dna as protein' doesn't make much sense otherwise.
689 int intronLength = 0;
690 while (basesWritten + toOffset < mappedCodonEnd
691 && thisSeqPos < thisSeq.length)
693 final char c = thisSeq[thisSeqPos++];
697 int sourcePosition = basesWritten + toOffset;
698 if (sourcePosition < mappedCodonStart)
701 * Found an unmapped (intron) base. First add in any preceding gaps
704 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
706 thisAligned.append(trailingCopiedGap.toString());
707 intronLength += trailingCopiedGap.length();
708 trailingCopiedGap = new StringBuilder();
715 final boolean startOfCodon = sourcePosition == mappedCodonStart;
716 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
717 preserveUnmappedGaps, sourceGapMappedLength, inExon,
718 trailingCopiedGap.length(), intronLength, startOfCodon);
719 for (int i = 0; i < gapsToAdd; i++)
721 thisAligned.append(myGapChar);
723 sourceGapMappedLength = 0;
726 thisAligned.append(c);
727 trailingCopiedGap = new StringBuilder();
731 if (inExon && preserveMappedGaps)
733 trailingCopiedGap.append(myGapChar);
735 else if (!inExon && preserveUnmappedGaps)
737 trailingCopiedGap.append(myGapChar);
744 * At end of model aligned sequence. Copy any remaining target sequence, optionally
745 * including (intron) gaps.
747 while (thisSeqPos < thisSeq.length)
749 final char c = thisSeq[thisSeqPos++];
750 if (c != myGapChar || preserveUnmappedGaps)
752 thisAligned.append(c);
754 sourceGapMappedLength--;
758 * finally add gaps to pad for any trailing source gaps or
759 * unmapped characters
761 if (preserveUnmappedGaps)
763 while (sourceGapMappedLength > 0)
765 thisAligned.append(myGapChar);
766 sourceGapMappedLength--;
771 * All done aligning, set the aligned sequence.
773 alignTo.setSequence(new String(thisAligned));
777 * Helper method to work out how many gaps to insert when realigning.
779 * @param preserveMappedGaps
780 * @param preserveUnmappedGaps
781 * @param sourceGapMappedLength
783 * @param trailingCopiedGap
784 * @param intronLength
785 * @param startOfCodon
788 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
789 boolean preserveUnmappedGaps, int sourceGapMappedLength,
790 boolean inExon, int trailingGapLength, int intronLength,
791 final boolean startOfCodon)
797 * Reached start of codon. Ignore trailing gaps in intron unless we are
798 * preserving gaps in both exon and intron. Ignore them anyway if the
799 * protein alignment introduces a gap at least as large as the intronic
802 if (inExon && !preserveMappedGaps)
804 trailingGapLength = 0;
806 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
808 trailingGapLength = 0;
812 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
816 if (intronLength + trailingGapLength <= sourceGapMappedLength)
818 gapsToAdd = sourceGapMappedLength - intronLength;
822 gapsToAdd = Math.min(intronLength + trailingGapLength
823 - sourceGapMappedLength, trailingGapLength);
830 * second or third base of codon; check for any gaps in dna
832 if (!preserveMappedGaps)
834 trailingGapLength = 0;
836 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
842 * Realigns the given protein to match the alignment of the dna, using codon
843 * mappings to translate aligned codon positions to protein residues.
846 * the alignment whose sequences are realigned by this method
848 * the dna alignment whose alignment we are 'copying'
849 * @return the number of sequences that were realigned
851 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
853 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
854 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
855 protein, dna, unmappedProtein);
856 return alignProteinAs(protein, alignedCodons, unmappedProtein);
860 * Builds a map whose key is an aligned codon position (3 alignment column
861 * numbers base 0), and whose value is a map from protein sequence to each
862 * protein's peptide residue for that codon. The map generates an ordering of
863 * the codons, and allows us to read off the peptides at each position in
864 * order to assemble 'aligned' protein sequences.
867 * the protein alignment
869 * the coding dna alignment
870 * @param unmappedProtein
871 * any unmapped proteins are added to this list
874 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
875 AlignmentI protein, AlignmentI dna,
876 List<SequenceI> unmappedProtein)
879 * maintain a list of any proteins with no mappings - these will be
880 * rendered 'as is' in the protein alignment as we can't align them
882 unmappedProtein.addAll(protein.getSequences());
884 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
887 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
888 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
889 * comparator keeps the codon positions ordered.
891 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
892 new CodonComparator());
894 for (SequenceI dnaSeq : dna.getSequences())
896 for (AlignedCodonFrame mapping : mappings)
898 SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
901 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
902 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
903 seqMap, alignedCodons);
904 unmappedProtein.remove(prot);
910 * Finally add any unmapped peptide start residues (e.g. for incomplete
911 * codons) as if at the codon position before the second residue
913 // TODO resolve JAL-2022 so this fudge can be removed
914 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
915 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
917 return alignedCodons;
921 * Scans for any protein mapped from position 2 (meaning unmapped start
922 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
923 * preceding position in the alignment
925 * @param alignedCodons
926 * the codon-to-peptide map
927 * @param mappedSequenceCount
928 * the number of distinct sequences in the map
930 protected static void addUnmappedPeptideStarts(
931 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
932 int mappedSequenceCount)
934 // TODO delete this ugly hack once JAL-2022 is resolved
935 // i.e. we can model startPhase > 0 (incomplete start codon)
937 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
938 AlignedCodon lastCodon = null;
939 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
941 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
944 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
947 SequenceI seq = sequenceCodon.getKey();
948 if (sequencesChecked.contains(seq))
952 sequencesChecked.add(seq);
953 AlignedCodon codon = sequenceCodon.getValue();
954 if (codon.peptideCol > 1)
957 .println("Problem mapping protein with >1 unmapped start positions: "
960 else if (codon.peptideCol == 1)
963 * first position (peptideCol == 0) was unmapped - add it
965 if (lastCodon != null)
967 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
968 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
970 toAdd.put(seq, firstPeptide);
975 * unmapped residue at start of alignment (no prior column) -
976 * 'insert' at nominal codon [0, 0, 0]
978 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
979 String.valueOf(seq.getCharAt(0)), 0);
980 toAdd.put(seq, firstPeptide);
983 if (sequencesChecked.size() == mappedSequenceCount)
985 // no need to check past first mapped position in all sequences
989 lastCodon = entry.getKey();
993 * add any new codons safely after iterating over the map
995 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
997 addCodonToMap(alignedCodons, startCodon.getValue(),
998 startCodon.getKey());
1003 * Update the aligned protein sequences to match the codon alignments given in
1007 * @param alignedCodons
1008 * an ordered map of codon positions (columns), with sequence/peptide
1009 * values present in each column
1010 * @param unmappedProtein
1013 protected static int alignProteinAs(AlignmentI protein,
1014 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1015 List<SequenceI> unmappedProtein)
1018 * Prefill aligned sequences with gaps before inserting aligned protein
1021 int alignedWidth = alignedCodons.size();
1022 char[] gaps = new char[alignedWidth];
1023 Arrays.fill(gaps, protein.getGapCharacter());
1024 String allGaps = String.valueOf(gaps);
1025 for (SequenceI seq : protein.getSequences())
1027 if (!unmappedProtein.contains(seq))
1029 seq.setSequence(allGaps);
1034 for (AlignedCodon codon : alignedCodons.keySet())
1036 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1038 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1040 // place translated codon at its column position in sequence
1041 entry.getKey().getSequence()[column] = entry.getValue().product
1050 * Populate the map of aligned codons by traversing the given sequence
1051 * mapping, locating the aligned positions of mapped codons, and adding those
1052 * positions and their translation products to the map.
1055 * the aligned sequence we are mapping from
1057 * the sequence to be aligned to the codons
1059 * the gap character in the dna sequence
1061 * a mapping to a sequence translation
1062 * @param alignedCodons
1063 * the map we are building up
1065 static void addCodonPositions(SequenceI dna, SequenceI protein,
1066 char gapChar, Mapping seqMap,
1067 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1069 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1072 * add codon positions, and their peptide translations, to the alignment
1073 * map, while remembering the first codon mapped
1075 while (codons.hasNext())
1079 AlignedCodon codon = codons.next();
1080 addCodonToMap(alignedCodons, codon, protein);
1081 } catch (IncompleteCodonException e)
1083 // possible incomplete trailing codon - ignore
1084 } catch (NoSuchElementException e)
1086 // possibly peptide lacking STOP
1092 * Helper method to add a codon-to-peptide entry to the aligned codons map
1094 * @param alignedCodons
1098 protected static void addCodonToMap(
1099 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1100 AlignedCodon codon, SequenceI protein)
1102 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1103 if (seqProduct == null)
1105 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1106 alignedCodons.put(codon, seqProduct);
1108 seqProduct.put(protein, codon);
1112 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1113 * between at least one pair of sequences in the two alignments. Currently,
1116 * <li>One alignment must be nucleotide, and the other protein</li>
1117 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1118 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1119 * <li>The translation may ignore start and stop codons if present in the
1127 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1129 if (al1 == null || al2 == null)
1135 * Require one nucleotide and one protein
1137 if (al1.isNucleotide() == al2.isNucleotide())
1141 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1142 AlignmentI protein = dna == al1 ? al2 : al1;
1143 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1144 for (SequenceI dnaSeq : dna.getSequences())
1146 for (SequenceI proteinSeq : protein.getSequences())
1148 if (isMappable(dnaSeq, proteinSeq, mappings))
1158 * Returns true if the dna sequence is mapped, or could be mapped, to the
1166 protected static boolean isMappable(SequenceI dnaSeq,
1167 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1169 if (dnaSeq == null || proteinSeq == null)
1174 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1175 .getDatasetSequence();
1176 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1177 : proteinSeq.getDatasetSequence();
1179 for (AlignedCodonFrame mapping : mappings)
1181 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1191 * Just try to make a mapping (it is not yet stored), test whether
1194 return mapCdnaToProtein(proteinDs, dnaDs) != null;
1198 * Finds any reference annotations associated with the sequences in
1199 * sequenceScope, that are not already added to the alignment, and adds them
1200 * to the 'candidates' map. Also populates a lookup table of annotation
1201 * labels, keyed by calcId, for use in constructing tooltips or the like.
1203 * @param sequenceScope
1204 * the sequences to scan for reference annotations
1205 * @param labelForCalcId
1206 * (optional) map to populate with label for calcId
1208 * map to populate with annotations for sequence
1210 * the alignment to check for presence of annotations
1212 public static void findAddableReferenceAnnotations(
1213 List<SequenceI> sequenceScope,
1214 Map<String, String> labelForCalcId,
1215 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1218 if (sequenceScope == null)
1224 * For each sequence in scope, make a list of any annotations on the
1225 * underlying dataset sequence which are not already on the alignment.
1227 * Add to a map of { alignmentSequence, <List of annotations to add> }
1229 for (SequenceI seq : sequenceScope)
1231 SequenceI dataset = seq.getDatasetSequence();
1232 if (dataset == null)
1236 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1237 if (datasetAnnotations == null)
1241 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1242 for (AlignmentAnnotation dsann : datasetAnnotations)
1245 * Find matching annotations on the alignment. If none is found, then
1246 * add this annotation to the list of 'addable' annotations for this
1249 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1250 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1251 if (!matchedAlignmentAnnotations.iterator().hasNext())
1254 if (labelForCalcId != null)
1256 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1261 * Save any addable annotations for this sequence
1263 if (!result.isEmpty())
1265 candidates.put(seq, result);
1271 * Adds annotations to the top of the alignment annotations, in the same order
1272 * as their related sequences.
1274 * @param annotations
1275 * the annotations to add
1277 * the alignment to add them to
1278 * @param selectionGroup
1279 * current selection group (or null if none)
1281 public static void addReferenceAnnotations(
1282 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1283 final AlignmentI alignment, final SequenceGroup selectionGroup)
1285 for (SequenceI seq : annotations.keySet())
1287 for (AlignmentAnnotation ann : annotations.get(seq))
1289 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1291 int endRes = ann.annotations.length;
1292 if (selectionGroup != null)
1294 startRes = selectionGroup.getStartRes();
1295 endRes = selectionGroup.getEndRes();
1297 copyAnn.restrict(startRes, endRes);
1300 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1301 * original annotation is already on the sequence.
1303 if (!seq.hasAnnotation(ann))
1305 seq.addAlignmentAnnotation(copyAnn);
1308 copyAnn.adjustForAlignment();
1309 // add to the alignment and set visible
1310 alignment.addAnnotation(copyAnn);
1311 copyAnn.visible = true;
1317 * Set visibility of alignment annotations of specified types (labels), for
1318 * specified sequences. This supports controls like
1319 * "Show all secondary structure", "Hide all Temp factor", etc.
1321 * @al the alignment to scan for annotations
1323 * the types (labels) of annotations to be updated
1324 * @param forSequences
1325 * if not null, only annotations linked to one of these sequences are
1326 * in scope for update; if null, acts on all sequence annotations
1328 * if this flag is true, 'types' is ignored (label not checked)
1330 * if true, set visibility on, else set off
1332 public static void showOrHideSequenceAnnotations(AlignmentI al,
1333 Collection<String> types, List<SequenceI> forSequences,
1334 boolean anyType, boolean doShow)
1336 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
1339 for (AlignmentAnnotation aa : anns)
1341 if (anyType || types.contains(aa.label))
1343 if ((aa.sequenceRef != null)
1344 && (forSequences == null || forSequences
1345 .contains(aa.sequenceRef)))
1347 aa.visible = doShow;
1355 * Returns true if either sequence has a cross-reference to the other
1361 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1363 // Note: moved here from class CrossRef as the latter class has dependencies
1364 // not availability to the applet's classpath
1365 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1369 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1370 * that sequence name is structured as Source|AccessionId.
1376 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1378 if (seq1 == null || seq2 == null)
1382 String name = seq2.getName();
1383 final DBRefEntry[] xrefs = seq1.getDBRefs();
1386 for (DBRefEntry xref : xrefs)
1388 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1389 // case-insensitive test, consistent with DBRefEntry.equalRef()
1390 if (xrefName.equalsIgnoreCase(name))
1400 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1401 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1402 * added to the original alignment's dataset, which is shared by the new
1403 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1404 * added to the alignment dataset.
1407 * aligned dna sequences
1409 * - throws error if not given a dataset
1411 * (optional) to restrict results to CDS that map to specified
1413 * @return an alignment whose sequences are the cds-only parts of the dna
1414 * sequences (or null if no mappings are found)
1416 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1417 AlignmentI dataset, AlignmentI products)
1419 if (dataset.getDataset() != null)
1422 "IMPLEMENTATION ERROR: dataset.getDataset() must be null!");
1424 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1425 List<AlignedCodonFrame> mappings = dataset.getCodonFrames();
1426 HashSet<SequenceI> productSeqs = null;
1427 if (products != null)
1429 productSeqs = new HashSet<SequenceI>();
1430 for (SequenceI seq : products.getSequences())
1432 productSeqs.add(seq.getDatasetSequence() == null ? seq : seq
1433 .getDatasetSequence());
1438 * construct CDS sequences from the (cds-to-protein) mappings made earlier;
1439 * this makes it possible to model multiple products from dna (e.g. EMBL);
1440 * however it does mean we don't have the EMBL protein_id (a property on
1441 * the CDS features) in order to make the CDS sequence name :-(
1443 for (SequenceI seq : dna)
1445 SequenceI seqDss = seq.getDatasetSequence() == null ? seq : seq
1446 .getDatasetSequence();
1447 List<AlignedCodonFrame> seqMappings = MappingUtils
1448 .findMappingsForSequence(seq, mappings);
1449 for (AlignedCodonFrame mapping : seqMappings)
1451 List<Mapping> mappingsFromSequence = mapping.getMappingsFromSequence(seq);
1453 for (Mapping aMapping : mappingsFromSequence)
1455 if (aMapping.getMap().getFromRatio() == 1)
1458 * not a dna-to-protein mapping (likely dna-to-cds)
1464 * check for an existing CDS sequence i.e. a 3:1 mapping to
1465 * the dna mapping's product
1467 SequenceI cdsSeq = null;
1469 // TODO better mappings collection data model so we can do
1470 // a direct lookup instead of double loops to find mappings
1472 SequenceI proteinProduct = aMapping.getTo();
1475 * skip if not mapped to one of a specified set of proteins
1477 if (productSeqs != null && !productSeqs.contains(proteinProduct))
1482 for (AlignedCodonFrame acf : MappingUtils
1483 .findMappingsForSequence(proteinProduct, mappings))
1485 for (SequenceToSequenceMapping map : acf.getMappings())
1487 if (map.getMapping().getMap().getFromRatio() == 3
1488 && proteinProduct == map.getMapping().getTo()
1489 && seqDss != map.getFromSeq())
1492 * found a 3:1 mapping to the protein product which is not
1493 * from the dna sequence...assume it is from the CDS sequence
1494 * TODO mappings data model that brings together related
1495 * dna-cds-protein mappings in one object
1497 cdsSeq = map.getFromSeq();
1504 * mappings are always to dataset sequences so create an aligned
1505 * sequence to own it; add the dataset sequence to the dataset
1507 SequenceI derivedSequence = cdsSeq.deriveSequence();
1508 cdsSeqs.add(derivedSequence);
1509 if (!dataset.getSequences().contains(cdsSeq))
1511 dataset.addSequence(cdsSeq);
1517 * didn't find mapped CDS sequence - construct it and add
1518 * its dataset sequence to the dataset
1520 cdsSeq = makeCdsSequence(seq.getDatasetSequence(), aMapping);
1521 SequenceI cdsSeqDss = cdsSeq.createDatasetSequence();
1522 cdsSeqs.add(cdsSeq);
1523 if (!dataset.getSequences().contains(cdsSeqDss))
1525 dataset.addSequence(cdsSeqDss);
1529 * add a mapping from CDS to the (unchanged) mapped to range
1531 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1532 cdsSeq.getLength() });
1533 MapList map = new MapList(cdsRange, aMapping.getMap()
1534 .getToRanges(), aMapping.getMap().getFromRatio(),
1535 aMapping.getMap().getToRatio());
1536 AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
1537 cdsToProteinMapping.addMap(cdsSeq, proteinProduct, map);
1540 * guard against duplicating the mapping if repeating this action
1542 if (!mappings.contains(cdsToProteinMapping))
1544 mappings.add(cdsToProteinMapping);
1548 * add another mapping from original 'from' range to CDS
1550 AlignedCodonFrame dnaToProteinMapping = new AlignedCodonFrame();
1551 map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1553 dnaToProteinMapping.addMap(seq.getDatasetSequence(), cdsSeq, map);
1554 if (!mappings.contains(dnaToProteinMapping))
1556 mappings.add(dnaToProteinMapping);
1561 * transfer any features on dna that overlap the CDS
1563 transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1568 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1570 cds.setDataset(dataset);
1576 * Helper method that makes a CDS sequence as defined by the mappings from the
1577 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1578 * forward or reverse strand).
1582 * @return CDS sequence (as a dataset sequence)
1584 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1586 char[] seqChars = seq.getSequence();
1587 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1588 int cdsWidth = MappingUtils.getLength(fromRanges);
1589 char[] newSeqChars = new char[cdsWidth];
1592 for (int[] range : fromRanges)
1594 if (range[0] <= range[1])
1596 // forward strand mapping - just copy the range
1597 int length = range[1] - range[0] + 1;
1598 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1604 // reverse strand mapping - copy and complement one by one
1605 for (int i = range[0]; i >= range[1]; i--)
1607 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1612 SequenceI newSeq = new Sequence(seq.getName() + "|"
1613 + mapping.getTo().getName(), newSeqChars, 1, newPos);
1618 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1619 * feature start/end ranges, optionally omitting specified feature types.
1620 * Returns the number of features copied.
1625 * if not null, only features of this type are copied (including
1626 * subtypes in the Sequence Ontology)
1628 * the mapping from 'fromSeq' to 'toSeq'
1631 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1632 MapList mapping, String select, String... omitting)
1634 SequenceI copyTo = toSeq;
1635 while (copyTo.getDatasetSequence() != null)
1637 copyTo = copyTo.getDatasetSequence();
1640 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1642 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1645 for (SequenceFeature sf : sfs)
1647 String type = sf.getType();
1648 if (select != null && !so.isA(type, select))
1652 boolean omit = false;
1653 for (String toOmit : omitting)
1655 if (type.equals(toOmit))
1666 * locate the mapped range - null if either start or end is
1667 * not mapped (no partial overlaps are calculated)
1669 int start = sf.getBegin();
1670 int end = sf.getEnd();
1671 int[] mappedTo = mapping.locateInTo(start, end);
1673 * if whole exon range doesn't map, try interpreting it
1674 * as 5' or 3' exon overlapping the CDS range
1676 if (mappedTo == null)
1678 mappedTo = mapping.locateInTo(end, end);
1679 if (mappedTo != null)
1682 * end of exon is in CDS range - 5' overlap
1683 * to a range from the start of the peptide
1688 if (mappedTo == null)
1690 mappedTo = mapping.locateInTo(start, start);
1691 if (mappedTo != null)
1694 * start of exon is in CDS range - 3' overlap
1695 * to a range up to the end of the peptide
1697 mappedTo[1] = toSeq.getLength();
1700 if (mappedTo != null)
1702 SequenceFeature copy = new SequenceFeature(sf);
1703 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1704 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1705 copyTo.addSequenceFeature(copy);
1714 * Returns a mapping from dna to protein by inspecting sequence features of
1715 * type "CDS" on the dna.
1721 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1722 SequenceI proteinSeq)
1724 List<int[]> ranges = findCdsPositions(dnaSeq);
1725 int mappedDnaLength = MappingUtils.getLength(ranges);
1727 int proteinLength = proteinSeq.getLength();
1728 int proteinStart = proteinSeq.getStart();
1729 int proteinEnd = proteinSeq.getEnd();
1732 * incomplete start codon may mean X at start of peptide
1733 * we ignore both for mapping purposes
1735 if (proteinSeq.getCharAt(0) == 'X')
1737 // todo JAL-2022 support startPhase > 0
1741 List<int[]> proteinRange = new ArrayList<int[]>();
1744 * dna length should map to protein (or protein plus stop codon)
1746 int codesForResidues = mappedDnaLength / 3;
1747 if (codesForResidues == (proteinLength + 1))
1749 // assuming extra codon is for STOP and not in peptide
1752 if (codesForResidues == proteinLength)
1754 proteinRange.add(new int[] { proteinStart, proteinEnd });
1755 return new MapList(ranges, proteinRange, 3, 1);
1761 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1762 * start/end positions of sequence features of type "CDS" (or a sub-type of
1763 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1764 * position order, so this method is only valid for linear CDS in the same
1765 * sense as the protein product.
1770 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1772 List<int[]> result = new ArrayList<int[]>();
1773 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1779 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1782 for (SequenceFeature sf : sfs)
1785 * process a CDS feature (or a sub-type of CDS)
1787 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1792 phase = Integer.parseInt(sf.getPhase());
1793 } catch (NumberFormatException e)
1798 * phase > 0 on first codon means 5' incomplete - skip to the start
1799 * of the next codon; example ENST00000496384
1801 int begin = sf.getBegin();
1802 int end = sf.getEnd();
1803 if (result.isEmpty())
1808 // shouldn't happen!
1810 .println("Error: start phase extends beyond start CDS in "
1811 + dnaSeq.getName());
1814 result.add(new int[] { begin, end });
1819 * remove 'startPhase' positions (usually 0) from the first range
1820 * so we begin at the start of a complete codon
1822 if (!result.isEmpty())
1824 // TODO JAL-2022 correctly model start phase > 0
1825 result.get(0)[0] += startPhase;
1829 * Finally sort ranges by start position. This avoids a dependency on
1830 * keeping features in order on the sequence (if they are in order anyway,
1831 * the sort will have almost no work to do). The implicit assumption is CDS
1832 * ranges are assembled in order. Other cases should not use this method,
1833 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1835 Collections.sort(result, new Comparator<int[]>()
1838 public int compare(int[] o1, int[] o2)
1840 return Integer.compare(o1[0], o2[0]);
1847 * Maps exon features from dna to protein, and computes variants in peptide
1848 * product generated by variants in dna, and adds them as sequence_variant
1849 * features on the protein sequence. Returns the number of variant features
1854 * @param dnaToProtein
1856 public static int computeProteinFeatures(SequenceI dnaSeq,
1857 SequenceI peptide, MapList dnaToProtein)
1859 while (dnaSeq.getDatasetSequence() != null)
1861 dnaSeq = dnaSeq.getDatasetSequence();
1863 while (peptide.getDatasetSequence() != null)
1865 peptide = peptide.getDatasetSequence();
1868 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1871 * compute protein variants from dna variants and codon mappings;
1872 * NB - alternatively we could retrieve this using the REST service e.g.
1873 * http://rest.ensembl.org/overlap/translation
1874 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1875 * which would be a bit slower but possibly more reliable
1879 * build a map with codon variations for each potentially varying peptide
1881 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1882 dnaSeq, dnaToProtein);
1885 * scan codon variations, compute peptide variants and add to peptide sequence
1888 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1890 int peptidePos = variant.getKey();
1891 List<DnaVariant>[] codonVariants = variant.getValue();
1892 count += computePeptideVariants(peptide, peptidePos, codonVariants);
1896 * sort to get sequence features in start position order
1897 * - would be better to store in Sequence as a TreeSet or NCList?
1899 if (peptide.getSequenceFeatures() != null)
1901 Arrays.sort(peptide.getSequenceFeatures(),
1902 new Comparator<SequenceFeature>()
1905 public int compare(SequenceFeature o1, SequenceFeature o2)
1907 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1908 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1917 * Computes non-synonymous peptide variants from codon variants and adds them
1918 * as sequence_variant features on the protein sequence (one feature per
1919 * allele variant). Selected attributes (variant id, clinical significance)
1920 * are copied over to the new features.
1923 * the protein sequence
1925 * the position to compute peptide variants for
1926 * @param codonVariants
1927 * a list of dna variants per codon position
1928 * @return the number of features added
1930 static int computePeptideVariants(SequenceI peptide, int peptidePos,
1931 List<DnaVariant>[] codonVariants)
1933 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1935 String base1 = codonVariants[0].get(0).base;
1936 String base2 = codonVariants[1].get(0).base;
1937 String base3 = codonVariants[2].get(0).base;
1940 * variants in first codon base
1942 for (DnaVariant var : codonVariants[0])
1944 if (var.variant != null)
1946 String alleles = (String) var.variant.getValue("alleles");
1947 if (alleles != null)
1949 for (String base : alleles.split(","))
1951 String codon = base + base2 + base3;
1952 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1962 * variants in second codon base
1964 for (DnaVariant var : codonVariants[1])
1966 if (var.variant != null)
1968 String alleles = (String) var.variant.getValue("alleles");
1969 if (alleles != null)
1971 for (String base : alleles.split(","))
1973 String codon = base1 + base + base3;
1974 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1984 * variants in third codon base
1986 for (DnaVariant var : codonVariants[2])
1988 if (var.variant != null)
1990 String alleles = (String) var.variant.getValue("alleles");
1991 if (alleles != null)
1993 for (String base : alleles.split(","))
1995 String codon = base1 + base2 + base;
1996 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2009 * Helper method that adds a peptide variant feature, provided the given codon
2010 * translates to a value different to the current residue (is a non-synonymous
2011 * variant). ID and clinical_significance attributes of the dna variant (if
2012 * present) are copied to the new feature.
2019 * @return true if a feature was added, else false
2021 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
2022 String residue, DnaVariant var, String codon)
2025 * get peptide translation of codon e.g. GAT -> D
2026 * note that variants which are not single alleles,
2027 * e.g. multibase variants or HGMD_MUTATION etc
2028 * are currently ignored here
2030 String trans = codon.contains("-") ? "-"
2031 : (codon.length() > 3 ? null : ResidueProperties
2032 .codonTranslate(codon));
2033 if (trans != null && !trans.equals(residue))
2035 String residue3Char = StringUtils
2036 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
2037 String trans3Char = StringUtils
2038 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
2039 String desc = "p." + residue3Char + peptidePos + trans3Char;
2040 // set score to 0f so 'graduated colour' option is offered! JAL-2060
2041 SequenceFeature sf = new SequenceFeature(
2042 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
2043 peptidePos, 0f, "Jalview");
2044 StringBuilder attributes = new StringBuilder(32);
2045 String id = (String) var.variant.getValue(ID);
2048 if (id.startsWith(SEQUENCE_VARIANT))
2050 id = id.substring(SEQUENCE_VARIANT.length());
2052 sf.setValue(ID, id);
2053 attributes.append(ID).append("=").append(id);
2054 // TODO handle other species variants
2055 StringBuilder link = new StringBuilder(32);
2058 link.append(desc).append(" ").append(id)
2059 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
2060 .append(URLEncoder.encode(id, "UTF-8"));
2061 sf.addLink(link.toString());
2062 } catch (UnsupportedEncodingException e)
2067 String clinSig = (String) var.variant
2068 .getValue(CLINICAL_SIGNIFICANCE);
2069 if (clinSig != null)
2071 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
2072 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
2075 peptide.addSequenceFeature(sf);
2076 if (attributes.length() > 0)
2078 sf.setAttributes(attributes.toString());
2086 * Builds a map whose key is position in the protein sequence, and value is a
2087 * list of the base and all variants for each corresponding codon position
2090 * @param dnaToProtein
2093 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
2094 SequenceI dnaSeq, MapList dnaToProtein)
2097 * map from peptide position to all variants of the codon which codes for it
2098 * LinkedHashMap ensures we keep the peptide features in sequence order
2100 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2101 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2103 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2104 if (dnaFeatures == null)
2109 int dnaStart = dnaSeq.getStart();
2110 int[] lastCodon = null;
2111 int lastPeptidePostion = 0;
2114 * build a map of codon variations for peptides
2116 for (SequenceFeature sf : dnaFeatures)
2118 int dnaCol = sf.getBegin();
2119 if (dnaCol != sf.getEnd())
2121 // not handling multi-locus variant features
2124 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2126 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2129 // feature doesn't lie within coding region
2132 int peptidePosition = mapsTo[0];
2133 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2134 if (codonVariants == null)
2136 codonVariants = new ArrayList[3];
2137 codonVariants[0] = new ArrayList<DnaVariant>();
2138 codonVariants[1] = new ArrayList<DnaVariant>();
2139 codonVariants[2] = new ArrayList<DnaVariant>();
2140 variants.put(peptidePosition, codonVariants);
2144 * extract dna variants to a string array
2146 String alls = (String) sf.getValue("alleles");
2151 String[] alleles = alls.toUpperCase().split(",");
2153 for (String allele : alleles)
2155 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2159 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2161 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2162 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2163 peptidePosition, peptidePosition));
2164 lastPeptidePostion = peptidePosition;
2168 * save nucleotide (and any variant) for each codon position
2170 for (int codonPos = 0; codonPos < 3; codonPos++)
2172 String nucleotide = String.valueOf(
2173 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2175 List<DnaVariant> codonVariant = codonVariants[codonPos];
2176 if (codon[codonPos] == dnaCol)
2178 if (!codonVariant.isEmpty()
2179 && codonVariant.get(0).variant == null)
2182 * already recorded base value, add this variant
2184 codonVariant.get(0).variant = sf;
2189 * add variant with base value
2191 codonVariant.add(new DnaVariant(nucleotide, sf));
2194 else if (codonVariant.isEmpty())
2197 * record (possibly non-varying) base value
2199 codonVariant.add(new DnaVariant(nucleotide));
2208 * Makes an alignment with a copy of the given sequences, adding in any
2209 * non-redundant sequences which are mapped to by the cross-referenced
2216 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2219 AlignmentI copy = new Alignment(new Alignment(seqs));
2222 * add mappings between sequences to the new alignment
2224 AlignedCodonFrame mappings = new AlignedCodonFrame();
2225 copy.addCodonFrame(mappings);
2226 for (int i = 0; i < copy.getHeight(); i++)
2228 SequenceI from = seqs[i];
2229 SequenceI to = copy.getSequenceAt(i);
2230 if (to.getDatasetSequence() != null)
2232 to = to.getDatasetSequence();
2234 int start = from.getStart();
2235 int end = from.getEnd();
2236 MapList map = new MapList(new int[] { start, end }, new int[] {
2237 start, end }, 1, 1);
2238 mappings.addMap(to, from, map);
2241 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2244 for (SequenceI xref : xrefs)
2246 DBRefEntry[] dbrefs = xref.getDBRefs();
2249 for (DBRefEntry dbref : dbrefs)
2251 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2255 SequenceI mappedTo = dbref.getMap().getTo();
2256 SequenceI match = matcher.findIdMatch(mappedTo);
2259 matcher.add(mappedTo);
2260 copy.addSequence(mappedTo);
2270 * Try to align sequences in 'unaligned' to match the alignment of their
2271 * mapped regions in 'aligned'. For example, could use this to align CDS
2272 * sequences which are mapped to their parent cDNA sequences.
2274 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2275 * dna-to-protein or protein-to-dna use alternative methods.
2278 * sequences to be aligned
2280 * holds aligned sequences and their mappings
2283 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2285 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2286 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2287 unaligned, aligned, unmapped);
2288 int width = columnMap.size();
2289 char gap = unaligned.getGapCharacter();
2290 int realignedCount = 0;
2292 for (SequenceI seq : unaligned.getSequences())
2294 if (!unmapped.contains(seq))
2296 char[] newSeq = new char[width];
2297 Arrays.fill(newSeq, gap);
2302 * traverse the map to find columns populated
2305 for (Integer column : columnMap.keySet())
2307 Character c = columnMap.get(column).get(seq);
2311 * sequence has a character at this position
2321 * trim trailing gaps
2323 if (lastCol < width)
2325 char[] tmp = new char[lastCol + 1];
2326 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2329 seq.setSequence(String.valueOf(newSeq));
2333 return realignedCount;
2337 * Returns a map whose key is alignment column number (base 1), and whose
2338 * values are a map of sequence characters in that column.
2345 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2346 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2349 * Map will hold, for each aligned column position, a map of
2350 * {unalignedSequence, characterPerSequence} at that position.
2351 * TreeMap keeps the entries in ascending column order.
2353 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2356 * record any sequences that have no mapping so can't be realigned
2358 unmapped.addAll(unaligned.getSequences());
2360 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2362 for (SequenceI seq : unaligned.getSequences())
2364 for (AlignedCodonFrame mapping : mappings)
2366 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2367 if (fromSeq != null)
2369 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2370 if (addMappedPositions(seq, fromSeq, seqMap, map))
2372 unmapped.remove(seq);
2381 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2382 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2383 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2387 * the sequence whose column positions we are recording
2389 * a sequence that is mapped to the first sequence
2391 * the mapping from 'fromSeq' to 'seq'
2393 * a map to add the column positions (in fromSeq) of the mapped
2397 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2398 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2406 * invert mapping if it is from unaligned to aligned sequence
2408 if (seqMap.getTo() == fromSeq.getDatasetSequence())
2410 seqMap = new Mapping(seq.getDatasetSequence(), seqMap.getMap()
2414 char[] fromChars = fromSeq.getSequence();
2415 int toStart = seq.getStart();
2416 char[] toChars = seq.getSequence();
2419 * traverse [start, end, start, end...] ranges in fromSeq
2421 for (int[] fromRange : seqMap.getMap().getFromRanges())
2423 for (int i = 0; i < fromRange.length - 1; i += 2)
2425 boolean forward = fromRange[i + 1] >= fromRange[i];
2428 * find the range mapped to (sequence positions base 1)
2430 int[] range = seqMap.locateMappedRange(fromRange[i],
2434 System.err.println("Error in mapping " + seqMap + " from "
2435 + fromSeq.getName());
2438 int fromCol = fromSeq.findIndex(fromRange[i]);
2439 int mappedCharPos = range[0];
2442 * walk over the 'from' aligned sequence in forward or reverse
2443 * direction; when a non-gap is found, record the column position
2444 * of the next character of the mapped-to sequence; stop when all
2445 * the characters of the range have been counted
2447 while (mappedCharPos <= range[1] && fromCol <= fromChars.length
2450 if (!Comparison.isGap(fromChars[fromCol - 1]))
2453 * mapped from sequence has a character in this column
2454 * record the column position for the mapped to character
2456 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2457 if (seqsMap == null)
2459 seqsMap = new HashMap<SequenceI, Character>();
2460 map.put(fromCol, seqsMap);
2462 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2465 fromCol += (forward ? 1 : -1);
2472 // strictly temporary hack until proper criteria for aligning protein to cds
2473 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2474 public static boolean looksLikeEnsembl(AlignmentI alignment)
2476 for (SequenceI seq : alignment.getSequences())
2478 String name = seq.getName();
2479 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))