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 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1338 if (anyType || types.contains(aa.label))
1340 if ((aa.sequenceRef != null)
1341 && (forSequences == null || forSequences
1342 .contains(aa.sequenceRef)))
1344 aa.visible = doShow;
1351 * Returns true if either sequence has a cross-reference to the other
1357 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1359 // Note: moved here from class CrossRef as the latter class has dependencies
1360 // not availability to the applet's classpath
1361 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1365 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1366 * that sequence name is structured as Source|AccessionId.
1372 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1374 if (seq1 == null || seq2 == null)
1378 String name = seq2.getName();
1379 final DBRefEntry[] xrefs = seq1.getDBRefs();
1382 for (DBRefEntry xref : xrefs)
1384 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1385 // case-insensitive test, consistent with DBRefEntry.equalRef()
1386 if (xrefName.equalsIgnoreCase(name))
1396 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1397 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1398 * added to the original alignment's dataset, which is shared by the new
1399 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1400 * added to the alignment dataset.
1403 * aligned dna sequences
1405 * - throws error if not given a dataset
1406 * @return an alignment whose sequences are the cds-only parts of the dna
1407 * sequences (or null if no mappings are found)
1409 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1412 if (dataset.getDataset() != null)
1415 "IMPLEMENTATION ERROR: dataset.getDataset() must be null!");
1417 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1418 List<AlignedCodonFrame> mappings = dataset.getCodonFrames();
1422 * construct CDS sequences from the (cds-to-protein) mappings made earlier;
1423 * this makes it possible to model multiple products from dna (e.g. EMBL);
1424 * however it does mean we don't have the EMBL protein_id (a property on
1425 * the CDS features) in order to make the CDS sequence name :-(
1427 for (SequenceI seq : dna)
1429 SequenceI seqDss = seq.getDatasetSequence() == null ? seq : seq
1430 .getDatasetSequence();
1431 List<AlignedCodonFrame> seqMappings = MappingUtils
1432 .findMappingsForSequence(seq, mappings);
1433 for (AlignedCodonFrame mapping : seqMappings)
1435 List<Mapping> mappingsFromSequence = mapping.getMappingsFromSequence(seq);
1437 for (Mapping aMapping : mappingsFromSequence)
1439 if (aMapping.getMap().getFromRatio() == 1)
1442 * not a dna-to-protein mapping (likely dna-to-cds)
1448 * check for an existing CDS sequence i.e. a 3:1 mapping to
1449 * the dna mapping's product
1451 SequenceI cdsSeq = null;
1452 // TODO better mappings collection data model so we can do
1453 // a table lookup instead of double loops to find mappings
1454 SequenceI proteinProduct = aMapping.getTo();
1455 for (AlignedCodonFrame acf : MappingUtils
1456 .findMappingsForSequence(proteinProduct, mappings))
1458 for (SequenceToSequenceMapping map : acf.getMappings())
1460 if (map.getMapping().getMap().getFromRatio() == 3
1461 && proteinProduct == map.getMapping().getTo()
1462 && seqDss != map.getFromSeq())
1465 * found a 3:1 mapping to the protein product which is not
1466 * from the dna sequence...assume it is from the CDS sequence
1467 * TODO mappings data model that brings together related
1468 * dna-cds-protein mappings in one object
1470 cdsSeq = map.getFromSeq();
1477 * mappings are always to dataset sequences so create an aligned
1478 * sequence to own it; add the dataset sequence to the dataset
1480 SequenceI derivedSequence = cdsSeq.deriveSequence();
1481 cdsSeqs.add(derivedSequence);
1482 if (!dataset.getSequences().contains(cdsSeq))
1484 dataset.addSequence(cdsSeq);
1490 * didn't find mapped CDS sequence - construct it and add
1491 * its dataset sequence to the dataset
1493 cdsSeq = makeCdsSequence(seq.getDatasetSequence(), aMapping);
1494 SequenceI cdsSeqDss = cdsSeq.createDatasetSequence();
1495 cdsSeqs.add(cdsSeq);
1496 if (!dataset.getSequences().contains(cdsSeqDss))
1498 dataset.addSequence(cdsSeqDss);
1502 * add a mapping from CDS to the (unchanged) mapped to range
1504 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1505 cdsSeq.getLength() });
1506 MapList map = new MapList(cdsRange, aMapping.getMap()
1507 .getToRanges(), aMapping.getMap().getFromRatio(),
1508 aMapping.getMap().getToRatio());
1509 AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
1510 cdsToProteinMapping.addMap(cdsSeq, proteinProduct, map);
1513 * guard against duplicating the mapping if repeating this action
1515 if (!mappings.contains(cdsToProteinMapping))
1517 mappings.add(cdsToProteinMapping);
1521 * add another mapping from original 'from' range to CDS
1523 AlignedCodonFrame dnaToProteinMapping = new AlignedCodonFrame();
1524 map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1526 dnaToProteinMapping.addMap(seq.getDatasetSequence(), cdsSeq, map);
1527 if (!mappings.contains(dnaToProteinMapping))
1529 mappings.add(dnaToProteinMapping);
1534 * transfer any features on dna that overlap the CDS
1536 transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1541 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1543 cds.setDataset((Alignment) dataset);
1549 * Helper method that makes a CDS sequence as defined by the mappings from the
1550 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1551 * forward or reverse strand).
1555 * @return CDS sequence (as a dataset sequence)
1557 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1559 char[] seqChars = seq.getSequence();
1560 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1561 int cdsWidth = MappingUtils.getLength(fromRanges);
1562 char[] newSeqChars = new char[cdsWidth];
1565 for (int[] range : fromRanges)
1567 if (range[0] <= range[1])
1569 // forward strand mapping - just copy the range
1570 int length = range[1] - range[0] + 1;
1571 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1577 // reverse strand mapping - copy and complement one by one
1578 for (int i = range[0]; i >= range[1]; i--)
1580 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1585 SequenceI newSeq = new Sequence(seq.getName() + "|"
1586 + mapping.getTo().getName(), newSeqChars, 1, newPos);
1591 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1592 * feature start/end ranges, optionally omitting specified feature types.
1593 * Returns the number of features copied.
1598 * if not null, only features of this type are copied (including
1599 * subtypes in the Sequence Ontology)
1601 * the mapping from 'fromSeq' to 'toSeq'
1604 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1605 MapList mapping, String select, String... omitting)
1607 SequenceI copyTo = toSeq;
1608 while (copyTo.getDatasetSequence() != null)
1610 copyTo = copyTo.getDatasetSequence();
1613 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1615 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1618 for (SequenceFeature sf : sfs)
1620 String type = sf.getType();
1621 if (select != null && !so.isA(type, select))
1625 boolean omit = false;
1626 for (String toOmit : omitting)
1628 if (type.equals(toOmit))
1639 * locate the mapped range - null if either start or end is
1640 * not mapped (no partial overlaps are calculated)
1642 int start = sf.getBegin();
1643 int end = sf.getEnd();
1644 int[] mappedTo = mapping.locateInTo(start, end);
1646 * if whole exon range doesn't map, try interpreting it
1647 * as 5' or 3' exon overlapping the CDS range
1649 if (mappedTo == null)
1651 mappedTo = mapping.locateInTo(end, end);
1652 if (mappedTo != null)
1655 * end of exon is in CDS range - 5' overlap
1656 * to a range from the start of the peptide
1661 if (mappedTo == null)
1663 mappedTo = mapping.locateInTo(start, start);
1664 if (mappedTo != null)
1667 * start of exon is in CDS range - 3' overlap
1668 * to a range up to the end of the peptide
1670 mappedTo[1] = toSeq.getLength();
1673 if (mappedTo != null)
1675 SequenceFeature copy = new SequenceFeature(sf);
1676 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1677 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1678 copyTo.addSequenceFeature(copy);
1687 * Returns a mapping from dna to protein by inspecting sequence features of
1688 * type "CDS" on the dna.
1694 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1695 SequenceI proteinSeq)
1697 List<int[]> ranges = findCdsPositions(dnaSeq);
1698 int mappedDnaLength = MappingUtils.getLength(ranges);
1700 int proteinLength = proteinSeq.getLength();
1701 int proteinStart = proteinSeq.getStart();
1702 int proteinEnd = proteinSeq.getEnd();
1705 * incomplete start codon may mean X at start of peptide
1706 * we ignore both for mapping purposes
1708 if (proteinSeq.getCharAt(0) == 'X')
1710 // todo JAL-2022 support startPhase > 0
1714 List<int[]> proteinRange = new ArrayList<int[]>();
1717 * dna length should map to protein (or protein plus stop codon)
1719 int codesForResidues = mappedDnaLength / 3;
1720 if (codesForResidues == (proteinLength + 1))
1722 // assuming extra codon is for STOP and not in peptide
1725 if (codesForResidues == proteinLength)
1727 proteinRange.add(new int[] { proteinStart, proteinEnd });
1728 return new MapList(ranges, proteinRange, 3, 1);
1734 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1735 * start/end positions of sequence features of type "CDS" (or a sub-type of
1736 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1737 * position order, so this method is only valid for linear CDS in the same
1738 * sense as the protein product.
1743 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1745 List<int[]> result = new ArrayList<int[]>();
1746 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1752 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1755 for (SequenceFeature sf : sfs)
1758 * process a CDS feature (or a sub-type of CDS)
1760 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1765 phase = Integer.parseInt(sf.getPhase());
1766 } catch (NumberFormatException e)
1771 * phase > 0 on first codon means 5' incomplete - skip to the start
1772 * of the next codon; example ENST00000496384
1774 int begin = sf.getBegin();
1775 int end = sf.getEnd();
1776 if (result.isEmpty())
1781 // shouldn't happen!
1783 .println("Error: start phase extends beyond start CDS in "
1784 + dnaSeq.getName());
1787 result.add(new int[] { begin, end });
1792 * remove 'startPhase' positions (usually 0) from the first range
1793 * so we begin at the start of a complete codon
1795 if (!result.isEmpty())
1797 // TODO JAL-2022 correctly model start phase > 0
1798 result.get(0)[0] += startPhase;
1802 * Finally sort ranges by start position. This avoids a dependency on
1803 * keeping features in order on the sequence (if they are in order anyway,
1804 * the sort will have almost no work to do). The implicit assumption is CDS
1805 * ranges are assembled in order. Other cases should not use this method,
1806 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1808 Collections.sort(result, new Comparator<int[]>()
1811 public int compare(int[] o1, int[] o2)
1813 return Integer.compare(o1[0], o2[0]);
1820 * Maps exon features from dna to protein, and computes variants in peptide
1821 * product generated by variants in dna, and adds them as sequence_variant
1822 * features on the protein sequence. Returns the number of variant features
1827 * @param dnaToProtein
1829 public static int computeProteinFeatures(SequenceI dnaSeq,
1830 SequenceI peptide, MapList dnaToProtein)
1832 while (dnaSeq.getDatasetSequence() != null)
1834 dnaSeq = dnaSeq.getDatasetSequence();
1836 while (peptide.getDatasetSequence() != null)
1838 peptide = peptide.getDatasetSequence();
1841 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1844 * compute protein variants from dna variants and codon mappings;
1845 * NB - alternatively we could retrieve this using the REST service e.g.
1846 * http://rest.ensembl.org/overlap/translation
1847 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1848 * which would be a bit slower but possibly more reliable
1852 * build a map with codon variations for each potentially varying peptide
1854 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1855 dnaSeq, dnaToProtein);
1858 * scan codon variations, compute peptide variants and add to peptide sequence
1861 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1863 int peptidePos = variant.getKey();
1864 List<DnaVariant>[] codonVariants = variant.getValue();
1865 count += computePeptideVariants(peptide, peptidePos, codonVariants);
1869 * sort to get sequence features in start position order
1870 * - would be better to store in Sequence as a TreeSet or NCList?
1872 if (peptide.getSequenceFeatures() != null)
1874 Arrays.sort(peptide.getSequenceFeatures(),
1875 new Comparator<SequenceFeature>()
1878 public int compare(SequenceFeature o1, SequenceFeature o2)
1880 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1881 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1890 * Computes non-synonymous peptide variants from codon variants and adds them
1891 * as sequence_variant features on the protein sequence (one feature per
1892 * allele variant). Selected attributes (variant id, clinical significance)
1893 * are copied over to the new features.
1896 * the protein sequence
1898 * the position to compute peptide variants for
1899 * @param codonVariants
1900 * a list of dna variants per codon position
1901 * @return the number of features added
1903 static int computePeptideVariants(SequenceI peptide, int peptidePos,
1904 List<DnaVariant>[] codonVariants)
1906 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1908 String base1 = codonVariants[0].get(0).base;
1909 String base2 = codonVariants[1].get(0).base;
1910 String base3 = codonVariants[2].get(0).base;
1913 * variants in first codon base
1915 for (DnaVariant var : codonVariants[0])
1917 if (var.variant != null)
1919 String alleles = (String) var.variant.getValue("alleles");
1920 if (alleles != null)
1922 for (String base : alleles.split(","))
1924 String codon = base + base2 + base3;
1925 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1935 * variants in second codon base
1937 for (DnaVariant var : codonVariants[1])
1939 if (var.variant != null)
1941 String alleles = (String) var.variant.getValue("alleles");
1942 if (alleles != null)
1944 for (String base : alleles.split(","))
1946 String codon = base1 + base + base3;
1947 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1957 * variants in third codon base
1959 for (DnaVariant var : codonVariants[2])
1961 if (var.variant != null)
1963 String alleles = (String) var.variant.getValue("alleles");
1964 if (alleles != null)
1966 for (String base : alleles.split(","))
1968 String codon = base1 + base2 + base;
1969 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1982 * Helper method that adds a peptide variant feature, provided the given codon
1983 * translates to a value different to the current residue (is a non-synonymous
1984 * variant). ID and clinical_significance attributes of the dna variant (if
1985 * present) are copied to the new feature.
1992 * @return true if a feature was added, else false
1994 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1995 String residue, DnaVariant var, String codon)
1998 * get peptide translation of codon e.g. GAT -> D
1999 * note that variants which are not single alleles,
2000 * e.g. multibase variants or HGMD_MUTATION etc
2001 * are currently ignored here
2003 String trans = codon.contains("-") ? "-"
2004 : (codon.length() > 3 ? null : ResidueProperties
2005 .codonTranslate(codon));
2006 if (trans != null && !trans.equals(residue))
2008 String residue3Char = StringUtils
2009 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
2010 String trans3Char = StringUtils
2011 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
2012 String desc = "p." + residue3Char + peptidePos + trans3Char;
2013 // set score to 0f so 'graduated colour' option is offered! JAL-2060
2014 SequenceFeature sf = new SequenceFeature(
2015 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
2016 peptidePos, 0f, "Jalview");
2017 StringBuilder attributes = new StringBuilder(32);
2018 String id = (String) var.variant.getValue(ID);
2021 if (id.startsWith(SEQUENCE_VARIANT))
2023 id = id.substring(SEQUENCE_VARIANT.length());
2025 sf.setValue(ID, id);
2026 attributes.append(ID).append("=").append(id);
2027 // TODO handle other species variants
2028 StringBuilder link = new StringBuilder(32);
2031 link.append(desc).append(" ").append(id)
2032 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
2033 .append(URLEncoder.encode(id, "UTF-8"));
2034 sf.addLink(link.toString());
2035 } catch (UnsupportedEncodingException e)
2040 String clinSig = (String) var.variant
2041 .getValue(CLINICAL_SIGNIFICANCE);
2042 if (clinSig != null)
2044 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
2045 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
2048 peptide.addSequenceFeature(sf);
2049 if (attributes.length() > 0)
2051 sf.setAttributes(attributes.toString());
2059 * Builds a map whose key is position in the protein sequence, and value is a
2060 * list of the base and all variants for each corresponding codon position
2063 * @param dnaToProtein
2066 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
2067 SequenceI dnaSeq, MapList dnaToProtein)
2070 * map from peptide position to all variants of the codon which codes for it
2071 * LinkedHashMap ensures we keep the peptide features in sequence order
2073 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2074 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2076 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2077 if (dnaFeatures == null)
2082 int dnaStart = dnaSeq.getStart();
2083 int[] lastCodon = null;
2084 int lastPeptidePostion = 0;
2087 * build a map of codon variations for peptides
2089 for (SequenceFeature sf : dnaFeatures)
2091 int dnaCol = sf.getBegin();
2092 if (dnaCol != sf.getEnd())
2094 // not handling multi-locus variant features
2097 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2099 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2102 // feature doesn't lie within coding region
2105 int peptidePosition = mapsTo[0];
2106 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2107 if (codonVariants == null)
2109 codonVariants = new ArrayList[3];
2110 codonVariants[0] = new ArrayList<DnaVariant>();
2111 codonVariants[1] = new ArrayList<DnaVariant>();
2112 codonVariants[2] = new ArrayList<DnaVariant>();
2113 variants.put(peptidePosition, codonVariants);
2117 * extract dna variants to a string array
2119 String alls = (String) sf.getValue("alleles");
2124 String[] alleles = alls.toUpperCase().split(",");
2126 for (String allele : alleles)
2128 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2132 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2134 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2135 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2136 peptidePosition, peptidePosition));
2137 lastPeptidePostion = peptidePosition;
2141 * save nucleotide (and any variant) for each codon position
2143 for (int codonPos = 0; codonPos < 3; codonPos++)
2145 String nucleotide = String.valueOf(
2146 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2148 List<DnaVariant> codonVariant = codonVariants[codonPos];
2149 if (codon[codonPos] == dnaCol)
2151 if (!codonVariant.isEmpty()
2152 && codonVariant.get(0).variant == null)
2155 * already recorded base value, add this variant
2157 codonVariant.get(0).variant = sf;
2162 * add variant with base value
2164 codonVariant.add(new DnaVariant(nucleotide, sf));
2167 else if (codonVariant.isEmpty())
2170 * record (possibly non-varying) base value
2172 codonVariant.add(new DnaVariant(nucleotide));
2181 * Makes an alignment with a copy of the given sequences, adding in any
2182 * non-redundant sequences which are mapped to by the cross-referenced
2189 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2192 AlignmentI copy = new Alignment(new Alignment(seqs));
2195 * add mappings between sequences to the new alignment
2197 AlignedCodonFrame mappings = new AlignedCodonFrame();
2198 copy.addCodonFrame(mappings);
2199 for (int i = 0; i < copy.getHeight(); i++)
2201 SequenceI from = seqs[i];
2202 SequenceI to = copy.getSequenceAt(i);
2203 if (to.getDatasetSequence() != null)
2205 to = to.getDatasetSequence();
2207 int start = from.getStart();
2208 int end = from.getEnd();
2209 MapList map = new MapList(new int[] { start, end }, new int[] {
2210 start, end }, 1, 1);
2211 mappings.addMap(to, from, map);
2214 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2217 for (SequenceI xref : xrefs)
2219 DBRefEntry[] dbrefs = xref.getDBRefs();
2222 for (DBRefEntry dbref : dbrefs)
2224 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2228 SequenceI mappedTo = dbref.getMap().getTo();
2229 SequenceI match = matcher.findIdMatch(mappedTo);
2232 matcher.add(mappedTo);
2233 copy.addSequence(mappedTo);
2243 * Try to align sequences in 'unaligned' to match the alignment of their
2244 * mapped regions in 'aligned'. For example, could use this to align CDS
2245 * sequences which are mapped to their parent cDNA sequences.
2247 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2248 * dna-to-protein or protein-to-dna use alternative methods.
2251 * sequences to be aligned
2253 * holds aligned sequences and their mappings
2256 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2258 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2259 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2260 unaligned, aligned, unmapped);
2261 int width = columnMap.size();
2262 char gap = unaligned.getGapCharacter();
2263 int realignedCount = 0;
2265 for (SequenceI seq : unaligned.getSequences())
2267 if (!unmapped.contains(seq))
2269 char[] newSeq = new char[width];
2270 Arrays.fill(newSeq, gap);
2275 * traverse the map to find columns populated
2278 for (Integer column : columnMap.keySet())
2280 Character c = columnMap.get(column).get(seq);
2284 * sequence has a character at this position
2294 * trim trailing gaps
2296 if (lastCol < width)
2298 char[] tmp = new char[lastCol + 1];
2299 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2302 seq.setSequence(String.valueOf(newSeq));
2306 return realignedCount;
2310 * Returns a map whose key is alignment column number (base 1), and whose
2311 * values are a map of sequence characters in that column.
2318 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2319 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2322 * Map will hold, for each aligned column position, a map of
2323 * {unalignedSequence, sequenceCharacter} at that position.
2324 * TreeMap keeps the entries in ascending column order.
2326 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2329 * r any sequences that have no mapping so can't be realigned
2331 unmapped.addAll(unaligned.getSequences());
2333 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2335 for (SequenceI seq : unaligned.getSequences())
2337 for (AlignedCodonFrame mapping : mappings)
2339 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2340 if (fromSeq != null)
2342 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2343 if (addMappedPositions(seq, fromSeq, seqMap, map))
2345 unmapped.remove(seq);
2354 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2355 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2356 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2360 * the sequence whose column positions we are recording
2362 * a sequence that is mapped to the first sequence
2364 * the mapping from 'fromSeq' to 'seq'
2366 * a map to add the column positions (in fromSeq) of the mapped
2370 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2371 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2378 char[] fromChars = fromSeq.getSequence();
2379 int toStart = seq.getStart();
2380 char[] toChars = seq.getSequence();
2383 * traverse [start, end, start, end...] ranges in fromSeq
2385 for (int[] fromRange : seqMap.getMap().getFromRanges())
2387 for (int i = 0; i < fromRange.length - 1; i += 2)
2389 boolean forward = fromRange[i + 1] >= fromRange[i];
2392 * find the range mapped to (sequence positions base 1)
2394 int[] range = seqMap.locateMappedRange(fromRange[i],
2398 System.err.println("Error in mapping " + seqMap + " from "
2399 + fromSeq.getName());
2402 int fromCol = fromSeq.findIndex(fromRange[i]);
2403 int mappedCharPos = range[0];
2406 * walk over the 'from' aligned sequence in forward or reverse
2407 * direction; when a non-gap is found, record the column position
2408 * of the next character of the mapped-to sequence; stop when all
2409 * the characters of the range have been counted
2411 while (mappedCharPos <= range[1])
2413 if (!Comparison.isGap(fromChars[fromCol - 1]))
2416 * mapped from sequence has a character in this column
2417 * record the column position for the mapped to character
2419 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2420 if (seqsMap == null)
2422 seqsMap = new HashMap<SequenceI, Character>();
2423 map.put(fromCol, seqsMap);
2425 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2428 fromCol += (forward ? 1 : -1);
2435 // strictly temporary hack until proper criteria for aligning protein to cds
2436 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2437 public static boolean looksLikeEnsembl(AlignmentI alignment)
2439 for (SequenceI seq : alignment.getSequences())
2441 String name = seq.getName();
2442 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))