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.Alignment;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.IncompleteCodonException;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.gff.SequenceOntologyFactory;
38 import jalview.io.gff.SequenceOntologyI;
39 import jalview.schemes.ResidueProperties;
40 import jalview.util.Comparison;
41 import jalview.util.MapList;
42 import jalview.util.MappingUtils;
43 import jalview.util.StringUtils;
45 import java.io.UnsupportedEncodingException;
46 import java.net.URLEncoder;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.HashMap;
53 import java.util.HashSet;
54 import java.util.Iterator;
55 import java.util.LinkedHashMap;
56 import java.util.List;
58 import java.util.Map.Entry;
59 import java.util.NoSuchElementException;
61 import java.util.TreeMap;
64 * grab bag of useful alignment manipulation operations Expect these to be
65 * refactored elsewhere at some point.
70 public class AlignmentUtils
73 private static final String SEQUENCE_VARIANT = "sequence_variant:";
74 private static final String ID = "ID";
77 * A data model to hold the 'normal' base value at a position, and an optional
78 * sequence variant feature
80 static class DnaVariant
84 SequenceFeature variant;
86 DnaVariant(String nuc)
91 DnaVariant(String nuc, SequenceFeature var)
99 * given an existing alignment, create a new alignment including all, or up to
100 * flankSize additional symbols from each sequence's dataset sequence
106 public static AlignmentI expandContext(AlignmentI core, int flankSize)
108 List<SequenceI> sq = new ArrayList<SequenceI>();
110 for (SequenceI s : core.getSequences())
112 SequenceI newSeq = s.deriveSequence();
113 final int newSeqStart = newSeq.getStart() - 1;
114 if (newSeqStart > maxoffset
115 && newSeq.getDatasetSequence().getStart() < s.getStart())
117 maxoffset = newSeqStart;
123 maxoffset = Math.min(maxoffset, flankSize);
127 * now add offset left and right to create an expanded alignment
129 for (SequenceI s : sq)
132 while (ds.getDatasetSequence() != null)
134 ds = ds.getDatasetSequence();
136 int s_end = s.findPosition(s.getStart() + s.getLength());
137 // find available flanking residues for sequence
138 int ustream_ds = s.getStart() - ds.getStart();
139 int dstream_ds = ds.getEnd() - s_end;
141 // build new flanked sequence
143 // compute gap padding to start of flanking sequence
144 int offset = maxoffset - ustream_ds;
146 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
149 if (flankSize < ustream_ds)
151 // take up to flankSize residues
152 offset = maxoffset - flankSize;
153 ustream_ds = flankSize;
155 if (flankSize <= dstream_ds)
157 dstream_ds = flankSize - 1;
160 // TODO use Character.toLowerCase to avoid creating String objects?
161 char[] upstream = new String(ds.getSequence(s.getStart() - 1
162 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
163 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
164 + dstream_ds)).toLowerCase().toCharArray();
165 char[] coreseq = s.getSequence();
166 char[] nseq = new char[offset + upstream.length + downstream.length
168 char c = core.getGapCharacter();
171 for (; p < offset; p++)
176 System.arraycopy(upstream, 0, nseq, p, upstream.length);
177 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
179 System.arraycopy(downstream, 0, nseq, p + coreseq.length
180 + upstream.length, downstream.length);
181 s.setSequence(new String(nseq));
182 s.setStart(s.getStart() - ustream_ds);
183 s.setEnd(s_end + downstream.length);
185 AlignmentI newAl = new jalview.datamodel.Alignment(
186 sq.toArray(new SequenceI[0]));
187 for (SequenceI s : sq)
189 if (s.getAnnotation() != null)
191 for (AlignmentAnnotation aa : s.getAnnotation())
193 aa.adjustForAlignment(); // JAL-1712 fix
194 newAl.addAnnotation(aa);
198 newAl.setDataset(core.getDataset());
203 * Returns the index (zero-based position) of a sequence in an alignment, or
210 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
214 for (SequenceI alSeq : al.getSequences())
227 * Returns a map of lists of sequences in the alignment, keyed by sequence
228 * name. For use in mapping between different alignment views of the same
231 * @see jalview.datamodel.AlignmentI#getSequencesByName()
233 public static Map<String, List<SequenceI>> getSequencesByName(
236 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
237 for (SequenceI seq : al.getSequences())
239 String name = seq.getName();
242 List<SequenceI> seqs = theMap.get(name);
245 seqs = new ArrayList<SequenceI>();
246 theMap.put(name, seqs);
255 * Build mapping of protein to cDNA alignment. Mappings are made between
256 * sequences where the cDNA translates to the protein sequence. Any new
257 * mappings are added to the protein alignment. Returns true if any mappings
258 * either already exist or were added, else false.
260 * @param proteinAlignment
261 * @param cdnaAlignment
264 public static boolean mapProteinAlignmentToCdna(
265 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
267 if (proteinAlignment == null || cdnaAlignment == null)
272 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
273 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
276 * First pass - map sequences where cross-references exist. This include
277 * 1-to-many mappings to support, for example, variant cDNA.
279 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
280 cdnaAlignment, mappedDna, mappedProtein, true);
283 * Second pass - map sequences where no cross-references exist. This only
284 * does 1-to-1 mappings and assumes corresponding sequences are in the same
285 * order in the alignments.
287 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
288 mappedDna, mappedProtein, false);
289 return mappingPerformed;
293 * Make mappings between compatible sequences (where the cDNA translation
294 * matches the protein).
296 * @param proteinAlignment
297 * @param cdnaAlignment
299 * a set of mapped DNA sequences (to add to)
300 * @param mappedProtein
301 * a set of mapped Protein sequences (to add to)
303 * if true, only map sequences where xrefs exist
306 protected static boolean mapProteinToCdna(
307 final AlignmentI proteinAlignment,
308 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
309 Set<SequenceI> mappedProtein, boolean xrefsOnly)
311 boolean mappingExistsOrAdded = false;
312 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
313 for (SequenceI aaSeq : thisSeqs)
315 boolean proteinMapped = false;
316 AlignedCodonFrame acf = new AlignedCodonFrame();
318 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
321 * Always try to map if sequences have xref to each other; this supports
322 * variant cDNA or alternative splicing for a protein sequence.
324 * If no xrefs, try to map progressively, assuming that alignments have
325 * mappable sequences in corresponding order. These are not
326 * many-to-many, as that would risk mixing species with similar cDNA
329 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
335 * Don't map non-xrefd sequences more than once each. This heuristic
336 * allows us to pair up similar sequences in ordered alignments.
339 && (mappedProtein.contains(aaSeq) || mappedDna
344 if (mappingExists(proteinAlignment.getCodonFrames(),
345 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
347 mappingExistsOrAdded = true;
351 MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
354 acf.addMap(cdnaSeq, aaSeq, map);
355 mappingExistsOrAdded = true;
356 proteinMapped = true;
357 mappedDna.add(cdnaSeq);
358 mappedProtein.add(aaSeq);
364 proteinAlignment.addCodonFrame(acf);
367 return mappingExistsOrAdded;
371 * Answers true if the mappings include one between the given (dataset)
374 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
375 SequenceI aaSeq, SequenceI cdnaSeq)
377 if (mappings != null)
379 for (AlignedCodonFrame acf : mappings)
381 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
391 * Builds a mapping (if possible) of a cDNA to a protein sequence.
393 * <li>first checks if the cdna translates exactly to the protein sequence</li>
394 * <li>else checks for translation after removing a STOP codon</li>
395 * <li>else checks for translation after removing a START codon</li>
396 * <li>if that fails, inspect CDS features on the cDNA sequence</li>
398 * Returns null if no mapping is determined.
401 * the aligned protein sequence
403 * the aligned cdna sequence
406 public static MapList mapCdnaToProtein(SequenceI proteinSeq,
410 * Here we handle either dataset sequence set (desktop) or absent (applet).
411 * Use only the char[] form of the sequence to avoid creating possibly large
414 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
415 char[] aaSeqChars = proteinDataset != null ? proteinDataset
416 .getSequence() : proteinSeq.getSequence();
417 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
418 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
419 : cdnaSeq.getSequence();
420 if (aaSeqChars == null || cdnaSeqChars == null)
426 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
428 final int mappedLength = 3 * aaSeqChars.length;
429 int cdnaLength = cdnaSeqChars.length;
430 int cdnaStart = cdnaSeq.getStart();
431 int cdnaEnd = cdnaSeq.getEnd();
432 final int proteinStart = proteinSeq.getStart();
433 final int proteinEnd = proteinSeq.getEnd();
436 * If lengths don't match, try ignoring stop codon (if present)
438 if (cdnaLength != mappedLength && cdnaLength > 2)
440 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
442 for (String stop : ResidueProperties.STOP)
444 if (lastCodon.equals(stop))
454 * If lengths still don't match, try ignoring start codon.
457 if (cdnaLength != mappedLength
459 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
460 .equals(ResidueProperties.START))
467 if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
470 * protein is translation of dna (+/- start/stop codons)
472 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
473 { proteinStart, proteinEnd }, 3, 1);
478 * translation failed - try mapping CDS annotated regions of dna
480 return mapCdsToProtein(cdnaSeq, proteinSeq);
484 * Test whether the given cdna sequence, starting at the given offset,
485 * translates to the given amino acid sequence, using the standard translation
486 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
488 * @param cdnaSeqChars
493 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
496 if (cdnaSeqChars == null || aaSeqChars == null)
502 int dnaPos = cdnaStart;
503 for (; dnaPos < cdnaSeqChars.length - 2
504 && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
506 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
507 final String translated = ResidueProperties.codonTranslate(codon);
510 * allow * in protein to match untranslatable in dna
512 final char aaRes = aaSeqChars[aaPos];
513 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
517 if (translated == null || !(aaRes == translated.charAt(0)))
520 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
521 // + codon + "(" + translated + ") != " + aaRes));
527 * check we matched all of the protein sequence
529 if (aaPos != aaSeqChars.length)
535 * check we matched all of the dna except
536 * for optional trailing STOP codon
538 if (dnaPos == cdnaSeqChars.length)
542 if (dnaPos == cdnaSeqChars.length - 3)
544 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
545 if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
554 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
555 * currently assumes that we are aligning cDNA to match protein.
558 * the sequence to be realigned
560 * the alignment whose sequence alignment is to be 'copied'
562 * character string represent a gap in the realigned sequence
563 * @param preserveUnmappedGaps
564 * @param preserveMappedGaps
565 * @return true if the sequence was realigned, false if it could not be
567 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
568 String gap, boolean preserveMappedGaps,
569 boolean preserveUnmappedGaps)
572 * Get any mappings from the source alignment to the target (dataset)
575 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
576 // all mappings. Would it help to constrain this?
577 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
578 if (mappings == null || mappings.isEmpty())
584 * Locate the aligned source sequence whose dataset sequence is mapped. We
585 * just take the first match here (as we can't align like more than one
588 SequenceI alignFrom = null;
589 AlignedCodonFrame mapping = null;
590 for (AlignedCodonFrame mp : mappings)
592 alignFrom = mp.findAlignedSequence(seq, al);
593 if (alignFrom != null)
600 if (alignFrom == null)
604 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
605 preserveMappedGaps, preserveUnmappedGaps);
610 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
611 * match residues and codons. Flags control whether existing gaps in unmapped
612 * (intron) and mapped (exon) regions are preserved or not. Gaps between
613 * intron and exon are only retained if both flags are set.
620 * @param preserveUnmappedGaps
621 * @param preserveMappedGaps
623 public static void alignSequenceAs(SequenceI alignTo,
624 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
625 char sourceGap, boolean preserveMappedGaps,
626 boolean preserveUnmappedGaps)
628 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
630 // aligned and dataset sequence positions, all base zero
634 int basesWritten = 0;
635 char myGapChar = myGap.charAt(0);
636 int ratio = myGap.length();
638 int fromOffset = alignFrom.getStart() - 1;
639 int toOffset = alignTo.getStart() - 1;
640 int sourceGapMappedLength = 0;
641 boolean inExon = false;
642 final char[] thisSeq = alignTo.getSequence();
643 final char[] thatAligned = alignFrom.getSequence();
644 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
647 * Traverse the 'model' aligned sequence
649 for (char sourceChar : thatAligned)
651 if (sourceChar == sourceGap)
653 sourceGapMappedLength += ratio;
658 * Found a non-gap character. Locate its mapped region if any.
661 // Note mapping positions are base 1, our sequence positions base 0
662 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
663 sourceDsPos + fromOffset);
664 if (mappedPos == null)
667 * unmapped position; treat like a gap
669 sourceGapMappedLength += ratio;
670 // System.err.println("Can't align: no codon mapping to residue "
671 // + sourceDsPos + "(" + sourceChar + ")");
676 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
677 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
678 StringBuilder trailingCopiedGap = new StringBuilder();
681 * Copy dna sequence up to and including this codon. Optionally, include
682 * gaps before the codon starts (in introns) and/or after the codon starts
685 * Note this only works for 'linear' splicing, not reverse or interleaved.
686 * But then 'align dna as protein' doesn't make much sense otherwise.
688 int intronLength = 0;
689 while (basesWritten + toOffset < mappedCodonEnd
690 && thisSeqPos < thisSeq.length)
692 final char c = thisSeq[thisSeqPos++];
696 int sourcePosition = basesWritten + toOffset;
697 if (sourcePosition < mappedCodonStart)
700 * Found an unmapped (intron) base. First add in any preceding gaps
703 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
705 thisAligned.append(trailingCopiedGap.toString());
706 intronLength += trailingCopiedGap.length();
707 trailingCopiedGap = new StringBuilder();
714 final boolean startOfCodon = sourcePosition == mappedCodonStart;
715 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
716 preserveUnmappedGaps, sourceGapMappedLength, inExon,
717 trailingCopiedGap.length(), intronLength, startOfCodon);
718 for (int i = 0; i < gapsToAdd; i++)
720 thisAligned.append(myGapChar);
722 sourceGapMappedLength = 0;
725 thisAligned.append(c);
726 trailingCopiedGap = new StringBuilder();
730 if (inExon && preserveMappedGaps)
732 trailingCopiedGap.append(myGapChar);
734 else if (!inExon && preserveUnmappedGaps)
736 trailingCopiedGap.append(myGapChar);
743 * At end of model aligned sequence. Copy any remaining target sequence, optionally
744 * including (intron) gaps.
746 while (thisSeqPos < thisSeq.length)
748 final char c = thisSeq[thisSeqPos++];
749 if (c != myGapChar || preserveUnmappedGaps)
751 thisAligned.append(c);
753 sourceGapMappedLength--;
757 * finally add gaps to pad for any trailing source gaps or
758 * unmapped characters
760 if (preserveUnmappedGaps)
762 while (sourceGapMappedLength > 0)
764 thisAligned.append(myGapChar);
765 sourceGapMappedLength--;
770 * All done aligning, set the aligned sequence.
772 alignTo.setSequence(new String(thisAligned));
776 * Helper method to work out how many gaps to insert when realigning.
778 * @param preserveMappedGaps
779 * @param preserveUnmappedGaps
780 * @param sourceGapMappedLength
782 * @param trailingCopiedGap
783 * @param intronLength
784 * @param startOfCodon
787 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
788 boolean preserveUnmappedGaps, int sourceGapMappedLength,
789 boolean inExon, int trailingGapLength, int intronLength,
790 final boolean startOfCodon)
796 * Reached start of codon. Ignore trailing gaps in intron unless we are
797 * preserving gaps in both exon and intron. Ignore them anyway if the
798 * protein alignment introduces a gap at least as large as the intronic
801 if (inExon && !preserveMappedGaps)
803 trailingGapLength = 0;
805 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
807 trailingGapLength = 0;
811 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
815 if (intronLength + trailingGapLength <= sourceGapMappedLength)
817 gapsToAdd = sourceGapMappedLength - intronLength;
821 gapsToAdd = Math.min(intronLength + trailingGapLength
822 - sourceGapMappedLength, trailingGapLength);
829 * second or third base of codon; check for any gaps in dna
831 if (!preserveMappedGaps)
833 trailingGapLength = 0;
835 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
841 * Realigns the given protein to match the alignment of the dna, using codon
842 * mappings to translate aligned codon positions to protein residues.
845 * the alignment whose sequences are realigned by this method
847 * the dna alignment whose alignment we are 'copying'
848 * @return the number of sequences that were realigned
850 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
852 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
853 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
854 protein, dna, unmappedProtein);
855 return alignProteinAs(protein, alignedCodons, unmappedProtein);
859 * Builds a map whose key is an aligned codon position (3 alignment column
860 * numbers base 0), and whose value is a map from protein sequence to each
861 * protein's peptide residue for that codon. The map generates an ordering of
862 * the codons, and allows us to read off the peptides at each position in
863 * order to assemble 'aligned' protein sequences.
866 * the protein alignment
868 * the coding dna alignment
869 * @param unmappedProtein
870 * any unmapped proteins are added to this list
873 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
874 AlignmentI protein, AlignmentI dna,
875 List<SequenceI> unmappedProtein)
878 * maintain a list of any proteins with no mappings - these will be
879 * rendered 'as is' in the protein alignment as we can't align them
881 unmappedProtein.addAll(protein.getSequences());
883 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
886 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
887 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
888 * comparator keeps the codon positions ordered.
890 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
891 new CodonComparator());
893 for (SequenceI dnaSeq : dna.getSequences())
895 for (AlignedCodonFrame mapping : mappings)
897 SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
900 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
901 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
902 seqMap, alignedCodons);
903 unmappedProtein.remove(prot);
909 * Finally add any unmapped peptide start residues (e.g. for incomplete
910 * codons) as if at the codon position before the second residue
912 // TODO resolve JAL-2022 so this fudge can be removed
913 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
914 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
916 return alignedCodons;
920 * Scans for any protein mapped from position 2 (meaning unmapped start
921 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
922 * preceding position in the alignment
924 * @param alignedCodons
925 * the codon-to-peptide map
926 * @param mappedSequenceCount
927 * the number of distinct sequences in the map
929 protected static void addUnmappedPeptideStarts(
930 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
931 int mappedSequenceCount)
933 // TODO delete this ugly hack once JAL-2022 is resolved
934 // i.e. we can model startPhase > 0 (incomplete start codon)
936 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
937 AlignedCodon lastCodon = null;
938 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
940 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
943 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
946 SequenceI seq = sequenceCodon.getKey();
947 if (sequencesChecked.contains(seq))
951 sequencesChecked.add(seq);
952 AlignedCodon codon = sequenceCodon.getValue();
953 if (codon.peptideCol > 1)
956 .println("Problem mapping protein with >1 unmapped start positions: "
959 else if (codon.peptideCol == 1)
962 * first position (peptideCol == 0) was unmapped - add it
964 if (lastCodon != null)
966 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
967 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
969 toAdd.put(seq, firstPeptide);
974 * unmapped residue at start of alignment (no prior column) -
975 * 'insert' at nominal codon [0, 0, 0]
977 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
978 String.valueOf(seq.getCharAt(0)), 0);
979 toAdd.put(seq, firstPeptide);
982 if (sequencesChecked.size() == mappedSequenceCount)
984 // no need to check past first mapped position in all sequences
988 lastCodon = entry.getKey();
992 * add any new codons safely after iterating over the map
994 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
996 addCodonToMap(alignedCodons, startCodon.getValue(),
997 startCodon.getKey());
1002 * Update the aligned protein sequences to match the codon alignments given in
1006 * @param alignedCodons
1007 * an ordered map of codon positions (columns), with sequence/peptide
1008 * values present in each column
1009 * @param unmappedProtein
1012 protected static int alignProteinAs(AlignmentI protein,
1013 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1014 List<SequenceI> unmappedProtein)
1017 * Prefill aligned sequences with gaps before inserting aligned protein
1020 int alignedWidth = alignedCodons.size();
1021 char[] gaps = new char[alignedWidth];
1022 Arrays.fill(gaps, protein.getGapCharacter());
1023 String allGaps = String.valueOf(gaps);
1024 for (SequenceI seq : protein.getSequences())
1026 if (!unmappedProtein.contains(seq))
1028 seq.setSequence(allGaps);
1033 for (AlignedCodon codon : alignedCodons.keySet())
1035 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1037 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1039 // place translated codon at its column position in sequence
1040 entry.getKey().getSequence()[column] = entry.getValue().product
1049 * Populate the map of aligned codons by traversing the given sequence
1050 * mapping, locating the aligned positions of mapped codons, and adding those
1051 * positions and their translation products to the map.
1054 * the aligned sequence we are mapping from
1056 * the sequence to be aligned to the codons
1058 * the gap character in the dna sequence
1060 * a mapping to a sequence translation
1061 * @param alignedCodons
1062 * the map we are building up
1064 static void addCodonPositions(SequenceI dna, SequenceI protein,
1065 char gapChar, Mapping seqMap,
1066 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1068 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1071 * add codon positions, and their peptide translations, to the alignment
1072 * map, while remembering the first codon mapped
1074 while (codons.hasNext())
1078 AlignedCodon codon = codons.next();
1079 addCodonToMap(alignedCodons, codon, protein);
1080 } catch (IncompleteCodonException e)
1082 // possible incomplete trailing codon - ignore
1083 } catch (NoSuchElementException e)
1085 // possibly peptide lacking STOP
1091 * Helper method to add a codon-to-peptide entry to the aligned codons map
1093 * @param alignedCodons
1097 protected static void addCodonToMap(
1098 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1099 AlignedCodon codon, SequenceI protein)
1101 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1102 if (seqProduct == null)
1104 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1105 alignedCodons.put(codon, seqProduct);
1107 seqProduct.put(protein, codon);
1111 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1112 * between at least one pair of sequences in the two alignments. Currently,
1115 * <li>One alignment must be nucleotide, and the other protein</li>
1116 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1117 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1118 * <li>The translation may ignore start and stop codons if present in the
1126 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1128 if (al1 == null || al2 == null)
1134 * Require one nucleotide and one protein
1136 if (al1.isNucleotide() == al2.isNucleotide())
1140 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1141 AlignmentI protein = dna == al1 ? al2 : al1;
1142 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1143 for (SequenceI dnaSeq : dna.getSequences())
1145 for (SequenceI proteinSeq : protein.getSequences())
1147 if (isMappable(dnaSeq, proteinSeq, mappings))
1157 * Returns true if the dna sequence is mapped, or could be mapped, to the
1165 protected static boolean isMappable(SequenceI dnaSeq,
1166 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1168 if (dnaSeq == null || proteinSeq == null)
1173 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1174 .getDatasetSequence();
1175 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1176 : proteinSeq.getDatasetSequence();
1178 for (AlignedCodonFrame mapping : mappings)
1180 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1190 * Just try to make a mapping (it is not yet stored), test whether
1193 return mapCdnaToProtein(proteinDs, dnaDs) != null;
1197 * Finds any reference annotations associated with the sequences in
1198 * sequenceScope, that are not already added to the alignment, and adds them
1199 * to the 'candidates' map. Also populates a lookup table of annotation
1200 * labels, keyed by calcId, for use in constructing tooltips or the like.
1202 * @param sequenceScope
1203 * the sequences to scan for reference annotations
1204 * @param labelForCalcId
1205 * (optional) map to populate with label for calcId
1207 * map to populate with annotations for sequence
1209 * the alignment to check for presence of annotations
1211 public static void findAddableReferenceAnnotations(
1212 List<SequenceI> sequenceScope,
1213 Map<String, String> labelForCalcId,
1214 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1217 if (sequenceScope == null)
1223 * For each sequence in scope, make a list of any annotations on the
1224 * underlying dataset sequence which are not already on the alignment.
1226 * Add to a map of { alignmentSequence, <List of annotations to add> }
1228 for (SequenceI seq : sequenceScope)
1230 SequenceI dataset = seq.getDatasetSequence();
1231 if (dataset == null)
1235 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1236 if (datasetAnnotations == null)
1240 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1241 for (AlignmentAnnotation dsann : datasetAnnotations)
1244 * Find matching annotations on the alignment. If none is found, then
1245 * add this annotation to the list of 'addable' annotations for this
1248 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1249 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1250 if (!matchedAlignmentAnnotations.iterator().hasNext())
1253 if (labelForCalcId != null)
1255 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1260 * Save any addable annotations for this sequence
1262 if (!result.isEmpty())
1264 candidates.put(seq, result);
1270 * Adds annotations to the top of the alignment annotations, in the same order
1271 * as their related sequences.
1273 * @param annotations
1274 * the annotations to add
1276 * the alignment to add them to
1277 * @param selectionGroup
1278 * current selection group (or null if none)
1280 public static void addReferenceAnnotations(
1281 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1282 final AlignmentI alignment, final SequenceGroup selectionGroup)
1284 for (SequenceI seq : annotations.keySet())
1286 for (AlignmentAnnotation ann : annotations.get(seq))
1288 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1290 int endRes = ann.annotations.length;
1291 if (selectionGroup != null)
1293 startRes = selectionGroup.getStartRes();
1294 endRes = selectionGroup.getEndRes();
1296 copyAnn.restrict(startRes, endRes);
1299 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1300 * original annotation is already on the sequence.
1302 if (!seq.hasAnnotation(ann))
1304 seq.addAlignmentAnnotation(copyAnn);
1307 copyAnn.adjustForAlignment();
1308 // add to the alignment and set visible
1309 alignment.addAnnotation(copyAnn);
1310 copyAnn.visible = true;
1316 * Set visibility of alignment annotations of specified types (labels), for
1317 * specified sequences. This supports controls like
1318 * "Show all secondary structure", "Hide all Temp factor", etc.
1320 * @al the alignment to scan for annotations
1322 * the types (labels) of annotations to be updated
1323 * @param forSequences
1324 * if not null, only annotations linked to one of these sequences are
1325 * in scope for update; if null, acts on all sequence annotations
1327 * if this flag is true, 'types' is ignored (label not checked)
1329 * if true, set visibility on, else set off
1331 public static void showOrHideSequenceAnnotations(AlignmentI al,
1332 Collection<String> types, List<SequenceI> forSequences,
1333 boolean anyType, boolean doShow)
1335 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1337 if (anyType || types.contains(aa.label))
1339 if ((aa.sequenceRef != null)
1340 && (forSequences == null || forSequences
1341 .contains(aa.sequenceRef)))
1343 aa.visible = doShow;
1350 * Returns true if either sequence has a cross-reference to the other
1356 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1358 // Note: moved here from class CrossRef as the latter class has dependencies
1359 // not availability to the applet's classpath
1360 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1364 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1365 * that sequence name is structured as Source|AccessionId.
1371 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1373 if (seq1 == null || seq2 == null)
1377 String name = seq2.getName();
1378 final DBRefEntry[] xrefs = seq1.getDBRefs();
1381 for (DBRefEntry xref : xrefs)
1383 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1384 // case-insensitive test, consistent with DBRefEntry.equalRef()
1385 if (xrefName.equalsIgnoreCase(name))
1395 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1396 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1397 * added to the original alignment's dataset, which is shared by the new
1398 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1399 * added to the alignment dataset.
1402 * aligned dna sequences
1404 * from dna to protein
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,
1410 List<AlignedCodonFrame> mappings, AlignmentI al)
1412 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1414 for (SequenceI seq : dna)
1416 AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1417 List<AlignedCodonFrame> seqMappings = MappingUtils
1418 .findMappingsForSequence(seq, mappings);
1419 List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1420 for (AlignedCodonFrame mapping : seqMappings)
1422 for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1424 SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1426 cdsSeqs.add(cdsSeq);
1429 * add a mapping from CDS to the (unchanged) mapped to range
1431 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1432 cdsSeq.getLength() });
1433 MapList map = new MapList(cdsRange, aMapping.getMap()
1434 .getToRanges(), aMapping.getMap().getFromRatio(),
1435 aMapping.getMap().getToRatio());
1436 cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1439 * add another mapping from original 'from' range to CDS
1441 map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1443 cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1445 alignmentMappings.add(cdsMappings);
1448 * transfer any features on dna that overlap the CDS
1450 transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1456 * add CDS seqs to shared dataset
1458 Alignment dataset = al.getDataset();
1459 for (SequenceI seq : cdsSeqs)
1461 if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1463 dataset.addSequence(seq.getDatasetSequence());
1466 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1468 cds.setDataset(dataset);
1474 * Helper method that makes a CDS sequence as defined by the mappings from the
1475 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1476 * forward or reverse strand).
1482 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1484 char[] seqChars = seq.getSequence();
1485 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1486 int cdsWidth = MappingUtils.getLength(fromRanges);
1487 char[] newSeqChars = new char[cdsWidth];
1490 for (int[] range : fromRanges)
1492 if (range[0] <= range[1])
1494 // forward strand mapping - just copy the range
1495 int length = range[1] - range[0] + 1;
1496 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1502 // reverse strand mapping - copy and complement one by one
1503 for (int i = range[0]; i >= range[1]; i--)
1505 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1510 SequenceI newSeq = new Sequence(seq.getName() + "|"
1511 + mapping.getTo().getName(), newSeqChars, 1, newPos);
1512 newSeq.createDatasetSequence();
1517 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1518 * feature start/end ranges, optionally omitting specified feature types.
1519 * Returns the number of features copied.
1524 * if not null, only features of this type are copied (including
1525 * subtypes in the Sequence Ontology)
1527 * the mapping from 'fromSeq' to 'toSeq'
1530 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1531 MapList mapping, String select, String... omitting)
1533 SequenceI copyTo = toSeq;
1534 while (copyTo.getDatasetSequence() != null)
1536 copyTo = copyTo.getDatasetSequence();
1539 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1541 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1544 for (SequenceFeature sf : sfs)
1546 String type = sf.getType();
1547 if (select != null && !so.isA(type, select))
1551 boolean omit = false;
1552 for (String toOmit : omitting)
1554 if (type.equals(toOmit))
1565 * locate the mapped range - null if either start or end is
1566 * not mapped (no partial overlaps are calculated)
1568 int start = sf.getBegin();
1569 int end = sf.getEnd();
1570 int[] mappedTo = mapping.locateInTo(start, end);
1572 * if whole exon range doesn't map, try interpreting it
1573 * as 5' or 3' exon overlapping the CDS range
1575 if (mappedTo == null)
1577 mappedTo = mapping.locateInTo(end, end);
1578 if (mappedTo != null)
1581 * end of exon is in CDS range - 5' overlap
1582 * to a range from the start of the peptide
1587 if (mappedTo == null)
1589 mappedTo = mapping.locateInTo(start, start);
1590 if (mappedTo != null)
1593 * start of exon is in CDS range - 3' overlap
1594 * to a range up to the end of the peptide
1596 mappedTo[1] = toSeq.getLength();
1599 if (mappedTo != null)
1601 SequenceFeature copy = new SequenceFeature(sf);
1602 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1603 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1604 copyTo.addSequenceFeature(copy);
1613 * Returns a mapping from dna to protein by inspecting sequence features of
1614 * type "CDS" on the dna.
1620 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1621 SequenceI proteinSeq)
1623 List<int[]> ranges = findCdsPositions(dnaSeq);
1624 int mappedDnaLength = MappingUtils.getLength(ranges);
1626 int proteinLength = proteinSeq.getLength();
1627 int proteinStart = proteinSeq.getStart();
1628 int proteinEnd = proteinSeq.getEnd();
1631 * incomplete start codon may mean X at start of peptide
1632 * we ignore both for mapping purposes
1634 if (proteinSeq.getCharAt(0) == 'X')
1636 // todo JAL-2022 support startPhase > 0
1640 List<int[]> proteinRange = new ArrayList<int[]>();
1643 * dna length should map to protein (or protein plus stop codon)
1645 int codesForResidues = mappedDnaLength / 3;
1646 if (codesForResidues == (proteinLength + 1))
1648 // assuming extra codon is for STOP and not in peptide
1651 if (codesForResidues == proteinLength)
1653 proteinRange.add(new int[] { proteinStart, proteinEnd });
1654 return new MapList(ranges, proteinRange, 3, 1);
1660 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1661 * start/end positions of sequence features of type "CDS" (or a sub-type of
1662 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1663 * position order, so this method is only valid for linear CDS in the same
1664 * sense as the protein product.
1669 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1671 List<int[]> result = new ArrayList<int[]>();
1672 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1678 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1681 for (SequenceFeature sf : sfs)
1684 * process a CDS feature (or a sub-type of CDS)
1686 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1691 phase = Integer.parseInt(sf.getPhase());
1692 } catch (NumberFormatException e)
1697 * phase > 0 on first codon means 5' incomplete - skip to the start
1698 * of the next codon; example ENST00000496384
1700 int begin = sf.getBegin();
1701 int end = sf.getEnd();
1702 if (result.isEmpty())
1707 // shouldn't happen!
1709 .println("Error: start phase extends beyond start CDS in "
1710 + dnaSeq.getName());
1713 result.add(new int[] { begin, end });
1718 * remove 'startPhase' positions (usually 0) from the first range
1719 * so we begin at the start of a complete codon
1721 if (!result.isEmpty())
1723 // TODO JAL-2022 correctly model start phase > 0
1724 result.get(0)[0] += startPhase;
1728 * Finally sort ranges by start position. This avoids a dependency on
1729 * keeping features in order on the sequence (if they are in order anyway,
1730 * the sort will have almost no work to do). The implicit assumption is CDS
1731 * ranges are assembled in order. Other cases should not use this method,
1732 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1734 Collections.sort(result, new Comparator<int[]>()
1737 public int compare(int[] o1, int[] o2)
1739 return Integer.compare(o1[0], o2[0]);
1746 * Maps exon features from dna to protein, and computes variants in peptide
1747 * product generated by variants in dna, and adds them as sequence_variant
1748 * features on the protein sequence. Returns the number of variant features
1753 * @param dnaToProtein
1755 public static int computeProteinFeatures(SequenceI dnaSeq,
1756 SequenceI peptide, MapList dnaToProtein)
1758 while (dnaSeq.getDatasetSequence() != null)
1760 dnaSeq = dnaSeq.getDatasetSequence();
1762 while (peptide.getDatasetSequence() != null)
1764 peptide = peptide.getDatasetSequence();
1767 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1770 * compute protein variants from dna variants and codon mappings;
1771 * NB - alternatively we could retrieve this using the REST service e.g.
1772 * http://rest.ensembl.org/overlap/translation
1773 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1774 * which would be a bit slower but possibly more reliable
1778 * build a map with codon variations for each potentially varying peptide
1780 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1781 dnaSeq, dnaToProtein);
1784 * scan codon variations, compute peptide variants and add to peptide sequence
1787 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1789 int peptidePos = variant.getKey();
1790 List<DnaVariant>[] codonVariants = variant.getValue();
1791 count += computePeptideVariants(peptide, peptidePos, codonVariants);
1795 * sort to get sequence features in start position order
1796 * - would be better to store in Sequence as a TreeSet or NCList?
1798 Arrays.sort(peptide.getSequenceFeatures(),
1799 new Comparator<SequenceFeature>()
1802 public int compare(SequenceFeature o1, SequenceFeature o2)
1804 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1805 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1813 * Computes non-synonymous peptide variants from codon variants and adds them
1814 * as sequence_variant features on the protein sequence (one feature per
1815 * allele variant). Selected attributes (variant id, clinical significance)
1816 * are copied over to the new features.
1819 * the protein sequence
1821 * the position to compute peptide variants for
1822 * @param codonVariants
1823 * a list of dna variants per codon position
1824 * @return the number of features added
1826 static int computePeptideVariants(SequenceI peptide, int peptidePos,
1827 List<DnaVariant>[] codonVariants)
1829 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1831 String base1 = codonVariants[0].get(0).base;
1832 String base2 = codonVariants[1].get(0).base;
1833 String base3 = codonVariants[2].get(0).base;
1836 * variants in first codon base
1838 for (DnaVariant var : codonVariants[0])
1840 if (var.variant != null)
1842 String alleles = (String) var.variant.getValue("alleles");
1843 if (alleles != null)
1845 for (String base : alleles.split(","))
1847 String codon = base + base2 + base3;
1848 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1858 * variants in second codon base
1860 for (DnaVariant var : codonVariants[1])
1862 if (var.variant != null)
1864 String alleles = (String) var.variant.getValue("alleles");
1865 if (alleles != null)
1867 for (String base : alleles.split(","))
1869 String codon = base1 + base + base3;
1870 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1880 * variants in third codon base
1882 for (DnaVariant var : codonVariants[2])
1884 if (var.variant != null)
1886 String alleles = (String) var.variant.getValue("alleles");
1887 if (alleles != null)
1889 for (String base : alleles.split(","))
1891 String codon = base1 + base2 + base;
1892 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1905 * Helper method that adds a peptide variant feature, provided the given codon
1906 * translates to a value different to the current residue (is a non-synonymous
1907 * variant). ID and clinical_significance attributes of the dna variant (if
1908 * present) are copied to the new feature.
1915 * @return true if a feature was added, else false
1917 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1918 String residue, DnaVariant var, String codon)
1921 * get peptide translation of codon e.g. GAT -> D
1922 * note that variants which are not single alleles,
1923 * e.g. multibase variants or HGMD_MUTATION etc
1924 * are currently ignored here
1926 String trans = codon.contains("-") ? "-"
1927 : (codon.length() > 3 ? null : ResidueProperties
1928 .codonTranslate(codon));
1929 if (trans != null && !trans.equals(residue))
1931 String residue3Char = StringUtils
1932 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
1933 String trans3Char = StringUtils
1934 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
1935 String desc = "p." + residue3Char + peptidePos + trans3Char;
1936 // set score to 0f so 'graduated colour' option is offered! JAL-2060
1937 SequenceFeature sf = new SequenceFeature(
1938 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1939 peptidePos, 0f, "Jalview");
1940 StringBuilder attributes = new StringBuilder(32);
1941 String id = (String) var.variant.getValue(ID);
1944 if (id.startsWith(SEQUENCE_VARIANT))
1946 id = id.substring(SEQUENCE_VARIANT.length());
1948 sf.setValue(ID, id);
1949 attributes.append(ID).append("=").append(id);
1950 // TODO handle other species variants
1951 StringBuilder link = new StringBuilder(32);
1954 link.append(desc).append(" ").append(id)
1955 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
1956 .append(URLEncoder.encode(id, "UTF-8"));
1957 sf.addLink(link.toString());
1958 } catch (UnsupportedEncodingException e)
1963 String clinSig = (String) var.variant
1964 .getValue(CLINICAL_SIGNIFICANCE);
1965 if (clinSig != null)
1967 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
1968 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
1971 peptide.addSequenceFeature(sf);
1972 if (attributes.length() > 0)
1974 sf.setAttributes(attributes.toString());
1982 * Builds a map whose key is position in the protein sequence, and value is a
1983 * list of the base and all variants for each corresponding codon position
1986 * @param dnaToProtein
1989 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
1990 SequenceI dnaSeq, MapList dnaToProtein)
1993 * map from peptide position to all variants of the codon which codes for it
1994 * LinkedHashMap ensures we keep the peptide features in sequence order
1996 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
1997 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1999 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2000 if (dnaFeatures == null)
2005 int dnaStart = dnaSeq.getStart();
2006 int[] lastCodon = null;
2007 int lastPeptidePostion = 0;
2010 * build a map of codon variations for peptides
2012 for (SequenceFeature sf : dnaFeatures)
2014 int dnaCol = sf.getBegin();
2015 if (dnaCol != sf.getEnd())
2017 // not handling multi-locus variant features
2020 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2022 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2025 // feature doesn't lie within coding region
2028 int peptidePosition = mapsTo[0];
2029 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2030 if (codonVariants == null)
2032 codonVariants = new ArrayList[3];
2033 codonVariants[0] = new ArrayList<DnaVariant>();
2034 codonVariants[1] = new ArrayList<DnaVariant>();
2035 codonVariants[2] = new ArrayList<DnaVariant>();
2036 variants.put(peptidePosition, codonVariants);
2040 * extract dna variants to a string array
2042 String alls = (String) sf.getValue("alleles");
2047 String[] alleles = alls.toUpperCase().split(",");
2049 for (String allele : alleles)
2051 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2055 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2057 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2058 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2059 peptidePosition, peptidePosition));
2060 lastPeptidePostion = peptidePosition;
2064 * save nucleotide (and any variant) for each codon position
2066 for (int codonPos = 0; codonPos < 3; codonPos++)
2068 String nucleotide = String.valueOf(
2069 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2071 List<DnaVariant> codonVariant = codonVariants[codonPos];
2072 if (codon[codonPos] == dnaCol)
2074 if (!codonVariant.isEmpty()
2075 && codonVariant.get(0).variant == null)
2078 * already recorded base value, add this variant
2080 codonVariant.get(0).variant = sf;
2085 * add variant with base value
2087 codonVariant.add(new DnaVariant(nucleotide, sf));
2090 else if (codonVariant.isEmpty())
2093 * record (possibly non-varying) base value
2095 codonVariant.add(new DnaVariant(nucleotide));
2104 * Makes an alignment with a copy of the given sequences, adding in any
2105 * non-redundant sequences which are mapped to by the cross-referenced
2112 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2115 AlignmentI copy = new Alignment(new Alignment(seqs));
2117 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2120 for (SequenceI xref : xrefs)
2122 DBRefEntry[] dbrefs = xref.getDBRefs();
2125 for (DBRefEntry dbref : dbrefs)
2127 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2131 SequenceI mappedTo = dbref.getMap().getTo();
2132 SequenceI match = matcher.findIdMatch(mappedTo);
2135 matcher.add(mappedTo);
2136 copy.addSequence(mappedTo);
2146 * Try to align sequences in 'unaligned' to match the alignment of their
2147 * mapped regions in 'aligned'. For example, could use this to align CDS
2148 * sequences which are mapped to their parent cDNA sequences.
2150 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2151 * dna-to-protein or protein-to-dna use alternative methods.
2154 * sequences to be aligned
2156 * holds aligned sequences and their mappings
2159 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2161 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2162 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2163 unaligned, aligned, unmapped);
2164 int width = columnMap.size();
2165 char gap = unaligned.getGapCharacter();
2166 int realignedCount = 0;
2168 for (SequenceI seq : unaligned.getSequences())
2170 if (!unmapped.contains(seq))
2172 char[] newSeq = new char[width];
2173 Arrays.fill(newSeq, gap);
2178 * traverse the map to find columns populated
2181 for (Integer column : columnMap.keySet())
2183 Character c = columnMap.get(column).get(seq);
2187 * sequence has a character at this position
2197 * trim trailing gaps
2199 if (lastCol < width)
2201 char[] tmp = new char[lastCol + 1];
2202 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2205 seq.setSequence(String.valueOf(newSeq));
2209 return realignedCount;
2213 * Returns a map whose key is alignment column number (base 1), and whose
2214 * values are a map of sequence characters in that column.
2221 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2222 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2225 * Map will hold, for each aligned column position, a map of
2226 * {unalignedSequence, sequenceCharacter} at that position.
2227 * TreeMap keeps the entries in ascending column order.
2229 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2232 * r any sequences that have no mapping so can't be realigned
2234 unmapped.addAll(unaligned.getSequences());
2236 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2238 for (SequenceI seq : unaligned.getSequences())
2240 for (AlignedCodonFrame mapping : mappings)
2242 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2243 if (fromSeq != null)
2245 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2246 if (addMappedPositions(seq, fromSeq, seqMap, map))
2248 unmapped.remove(seq);
2257 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2258 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2259 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2263 * the sequence whose column positions we are recording
2265 * a sequence that is mapped to the first sequence
2267 * the mapping from 'fromSeq' to 'seq'
2269 * a map to add the column positions (in fromSeq) of the mapped
2273 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2274 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2281 char[] fromChars = fromSeq.getSequence();
2282 int toStart = seq.getStart();
2283 char[] toChars = seq.getSequence();
2286 * traverse [start, end, start, end...] ranges in fromSeq
2288 for (int[] fromRange : seqMap.getMap().getFromRanges())
2290 for (int i = 0; i < fromRange.length - 1; i += 2)
2292 boolean forward = fromRange[i + 1] >= fromRange[i];
2295 * find the range mapped to (sequence positions base 1)
2297 int[] range = seqMap.locateMappedRange(fromRange[i],
2301 System.err.println("Error in mapping " + seqMap + " from "
2302 + fromSeq.getName());
2305 int fromCol = fromSeq.findIndex(fromRange[i]);
2306 int mappedCharPos = range[0];
2309 * walk over the 'from' aligned sequence in forward or reverse
2310 * direction; when a non-gap is found, record the column position
2311 * of the next character of the mapped-to sequence; stop when all
2312 * the characters of the range have been counted
2314 while (mappedCharPos <= range[1])
2316 if (!Comparison.isGap(fromChars[fromCol - 1]))
2319 * mapped from sequence has a character in this column
2320 * record the column position for the mapped to character
2322 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2323 if (seqsMap == null)
2325 seqsMap = new HashMap<SequenceI, Character>();
2326 map.put(fromCol, seqsMap);
2328 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2331 fromCol += (forward ? 1 : -1);
2338 // strictly temporary hack until proper criteria for aligning protein to cds
2339 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2340 public static boolean looksLikeEnsembl(AlignmentI alignment)
2342 for (SequenceI seq : alignment.getSequences())
2344 String name = seq.getName();
2345 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))