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>();
1415 * construct CDS sequences from the (cds-to-protein) mappings made earlier;
1416 * this makes it possible to model multiple products from dna (e.g. EMBL);
1417 * however it does mean we don't have the EMBL protein_id (a property on
1418 * the CDS features) in order to make the CDS sequence name :-(
1420 for (SequenceI seq : dna)
1422 AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1423 List<AlignedCodonFrame> seqMappings = MappingUtils
1424 .findMappingsForSequence(seq, mappings);
1425 List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1426 for (AlignedCodonFrame mapping : seqMappings)
1428 for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1430 SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1432 cdsSeqs.add(cdsSeq);
1435 * add a mapping from CDS to the (unchanged) mapped to range
1437 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1438 cdsSeq.getLength() });
1439 MapList map = new MapList(cdsRange, aMapping.getMap()
1440 .getToRanges(), aMapping.getMap().getFromRatio(),
1441 aMapping.getMap().getToRatio());
1442 cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1445 * add another mapping from original 'from' range to CDS
1447 map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1449 cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1451 alignmentMappings.add(cdsMappings);
1454 * transfer any features on dna that overlap the CDS
1456 transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1462 * add CDS seqs to shared dataset
1464 Alignment dataset = al.getDataset();
1465 for (SequenceI seq : cdsSeqs)
1467 if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1469 dataset.addSequence(seq.getDatasetSequence());
1472 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1474 cds.setDataset(dataset);
1480 * Helper method that makes a CDS sequence as defined by the mappings from the
1481 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1482 * forward or reverse strand).
1488 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1490 char[] seqChars = seq.getSequence();
1491 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1492 int cdsWidth = MappingUtils.getLength(fromRanges);
1493 char[] newSeqChars = new char[cdsWidth];
1496 for (int[] range : fromRanges)
1498 if (range[0] <= range[1])
1500 // forward strand mapping - just copy the range
1501 int length = range[1] - range[0] + 1;
1502 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1508 // reverse strand mapping - copy and complement one by one
1509 for (int i = range[0]; i >= range[1]; i--)
1511 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1516 SequenceI newSeq = new Sequence(seq.getName() + "|"
1517 + mapping.getTo().getName(), newSeqChars, 1, newPos);
1518 newSeq.createDatasetSequence();
1523 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1524 * feature start/end ranges, optionally omitting specified feature types.
1525 * Returns the number of features copied.
1530 * if not null, only features of this type are copied (including
1531 * subtypes in the Sequence Ontology)
1533 * the mapping from 'fromSeq' to 'toSeq'
1536 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1537 MapList mapping, String select, String... omitting)
1539 SequenceI copyTo = toSeq;
1540 while (copyTo.getDatasetSequence() != null)
1542 copyTo = copyTo.getDatasetSequence();
1545 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1547 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1550 for (SequenceFeature sf : sfs)
1552 String type = sf.getType();
1553 if (select != null && !so.isA(type, select))
1557 boolean omit = false;
1558 for (String toOmit : omitting)
1560 if (type.equals(toOmit))
1571 * locate the mapped range - null if either start or end is
1572 * not mapped (no partial overlaps are calculated)
1574 int start = sf.getBegin();
1575 int end = sf.getEnd();
1576 int[] mappedTo = mapping.locateInTo(start, end);
1578 * if whole exon range doesn't map, try interpreting it
1579 * as 5' or 3' exon overlapping the CDS range
1581 if (mappedTo == null)
1583 mappedTo = mapping.locateInTo(end, end);
1584 if (mappedTo != null)
1587 * end of exon is in CDS range - 5' overlap
1588 * to a range from the start of the peptide
1593 if (mappedTo == null)
1595 mappedTo = mapping.locateInTo(start, start);
1596 if (mappedTo != null)
1599 * start of exon is in CDS range - 3' overlap
1600 * to a range up to the end of the peptide
1602 mappedTo[1] = toSeq.getLength();
1605 if (mappedTo != null)
1607 SequenceFeature copy = new SequenceFeature(sf);
1608 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1609 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1610 copyTo.addSequenceFeature(copy);
1619 * Returns a mapping from dna to protein by inspecting sequence features of
1620 * type "CDS" on the dna.
1626 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1627 SequenceI proteinSeq)
1629 List<int[]> ranges = findCdsPositions(dnaSeq);
1630 int mappedDnaLength = MappingUtils.getLength(ranges);
1632 int proteinLength = proteinSeq.getLength();
1633 int proteinStart = proteinSeq.getStart();
1634 int proteinEnd = proteinSeq.getEnd();
1637 * incomplete start codon may mean X at start of peptide
1638 * we ignore both for mapping purposes
1640 if (proteinSeq.getCharAt(0) == 'X')
1642 // todo JAL-2022 support startPhase > 0
1646 List<int[]> proteinRange = new ArrayList<int[]>();
1649 * dna length should map to protein (or protein plus stop codon)
1651 int codesForResidues = mappedDnaLength / 3;
1652 if (codesForResidues == (proteinLength + 1))
1654 // assuming extra codon is for STOP and not in peptide
1657 if (codesForResidues == proteinLength)
1659 proteinRange.add(new int[] { proteinStart, proteinEnd });
1660 return new MapList(ranges, proteinRange, 3, 1);
1666 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1667 * start/end positions of sequence features of type "CDS" (or a sub-type of
1668 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1669 * position order, so this method is only valid for linear CDS in the same
1670 * sense as the protein product.
1675 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1677 List<int[]> result = new ArrayList<int[]>();
1678 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1684 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1687 for (SequenceFeature sf : sfs)
1690 * process a CDS feature (or a sub-type of CDS)
1692 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1697 phase = Integer.parseInt(sf.getPhase());
1698 } catch (NumberFormatException e)
1703 * phase > 0 on first codon means 5' incomplete - skip to the start
1704 * of the next codon; example ENST00000496384
1706 int begin = sf.getBegin();
1707 int end = sf.getEnd();
1708 if (result.isEmpty())
1713 // shouldn't happen!
1715 .println("Error: start phase extends beyond start CDS in "
1716 + dnaSeq.getName());
1719 result.add(new int[] { begin, end });
1724 * remove 'startPhase' positions (usually 0) from the first range
1725 * so we begin at the start of a complete codon
1727 if (!result.isEmpty())
1729 // TODO JAL-2022 correctly model start phase > 0
1730 result.get(0)[0] += startPhase;
1734 * Finally sort ranges by start position. This avoids a dependency on
1735 * keeping features in order on the sequence (if they are in order anyway,
1736 * the sort will have almost no work to do). The implicit assumption is CDS
1737 * ranges are assembled in order. Other cases should not use this method,
1738 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1740 Collections.sort(result, new Comparator<int[]>()
1743 public int compare(int[] o1, int[] o2)
1745 return Integer.compare(o1[0], o2[0]);
1752 * Maps exon features from dna to protein, and computes variants in peptide
1753 * product generated by variants in dna, and adds them as sequence_variant
1754 * features on the protein sequence. Returns the number of variant features
1759 * @param dnaToProtein
1761 public static int computeProteinFeatures(SequenceI dnaSeq,
1762 SequenceI peptide, MapList dnaToProtein)
1764 while (dnaSeq.getDatasetSequence() != null)
1766 dnaSeq = dnaSeq.getDatasetSequence();
1768 while (peptide.getDatasetSequence() != null)
1770 peptide = peptide.getDatasetSequence();
1773 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1776 * compute protein variants from dna variants and codon mappings;
1777 * NB - alternatively we could retrieve this using the REST service e.g.
1778 * http://rest.ensembl.org/overlap/translation
1779 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1780 * which would be a bit slower but possibly more reliable
1784 * build a map with codon variations for each potentially varying peptide
1786 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1787 dnaSeq, dnaToProtein);
1790 * scan codon variations, compute peptide variants and add to peptide sequence
1793 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1795 int peptidePos = variant.getKey();
1796 List<DnaVariant>[] codonVariants = variant.getValue();
1797 count += computePeptideVariants(peptide, peptidePos, codonVariants);
1801 * sort to get sequence features in start position order
1802 * - would be better to store in Sequence as a TreeSet or NCList?
1804 if (peptide.getSequenceFeatures() != null)
1806 Arrays.sort(peptide.getSequenceFeatures(),
1807 new Comparator<SequenceFeature>()
1810 public int compare(SequenceFeature o1, SequenceFeature o2)
1812 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1813 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1822 * Computes non-synonymous peptide variants from codon variants and adds them
1823 * as sequence_variant features on the protein sequence (one feature per
1824 * allele variant). Selected attributes (variant id, clinical significance)
1825 * are copied over to the new features.
1828 * the protein sequence
1830 * the position to compute peptide variants for
1831 * @param codonVariants
1832 * a list of dna variants per codon position
1833 * @return the number of features added
1835 static int computePeptideVariants(SequenceI peptide, int peptidePos,
1836 List<DnaVariant>[] codonVariants)
1838 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1840 String base1 = codonVariants[0].get(0).base;
1841 String base2 = codonVariants[1].get(0).base;
1842 String base3 = codonVariants[2].get(0).base;
1845 * variants in first codon base
1847 for (DnaVariant var : codonVariants[0])
1849 if (var.variant != null)
1851 String alleles = (String) var.variant.getValue("alleles");
1852 if (alleles != null)
1854 for (String base : alleles.split(","))
1856 String codon = base + base2 + base3;
1857 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1867 * variants in second codon base
1869 for (DnaVariant var : codonVariants[1])
1871 if (var.variant != null)
1873 String alleles = (String) var.variant.getValue("alleles");
1874 if (alleles != null)
1876 for (String base : alleles.split(","))
1878 String codon = base1 + base + base3;
1879 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1889 * variants in third codon base
1891 for (DnaVariant var : codonVariants[2])
1893 if (var.variant != null)
1895 String alleles = (String) var.variant.getValue("alleles");
1896 if (alleles != null)
1898 for (String base : alleles.split(","))
1900 String codon = base1 + base2 + base;
1901 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1914 * Helper method that adds a peptide variant feature, provided the given codon
1915 * translates to a value different to the current residue (is a non-synonymous
1916 * variant). ID and clinical_significance attributes of the dna variant (if
1917 * present) are copied to the new feature.
1924 * @return true if a feature was added, else false
1926 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1927 String residue, DnaVariant var, String codon)
1930 * get peptide translation of codon e.g. GAT -> D
1931 * note that variants which are not single alleles,
1932 * e.g. multibase variants or HGMD_MUTATION etc
1933 * are currently ignored here
1935 String trans = codon.contains("-") ? "-"
1936 : (codon.length() > 3 ? null : ResidueProperties
1937 .codonTranslate(codon));
1938 if (trans != null && !trans.equals(residue))
1940 String residue3Char = StringUtils
1941 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
1942 String trans3Char = StringUtils
1943 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
1944 String desc = "p." + residue3Char + peptidePos + trans3Char;
1945 // set score to 0f so 'graduated colour' option is offered! JAL-2060
1946 SequenceFeature sf = new SequenceFeature(
1947 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1948 peptidePos, 0f, "Jalview");
1949 StringBuilder attributes = new StringBuilder(32);
1950 String id = (String) var.variant.getValue(ID);
1953 if (id.startsWith(SEQUENCE_VARIANT))
1955 id = id.substring(SEQUENCE_VARIANT.length());
1957 sf.setValue(ID, id);
1958 attributes.append(ID).append("=").append(id);
1959 // TODO handle other species variants
1960 StringBuilder link = new StringBuilder(32);
1963 link.append(desc).append(" ").append(id)
1964 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
1965 .append(URLEncoder.encode(id, "UTF-8"));
1966 sf.addLink(link.toString());
1967 } catch (UnsupportedEncodingException e)
1972 String clinSig = (String) var.variant
1973 .getValue(CLINICAL_SIGNIFICANCE);
1974 if (clinSig != null)
1976 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
1977 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
1980 peptide.addSequenceFeature(sf);
1981 if (attributes.length() > 0)
1983 sf.setAttributes(attributes.toString());
1991 * Builds a map whose key is position in the protein sequence, and value is a
1992 * list of the base and all variants for each corresponding codon position
1995 * @param dnaToProtein
1998 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
1999 SequenceI dnaSeq, MapList dnaToProtein)
2002 * map from peptide position to all variants of the codon which codes for it
2003 * LinkedHashMap ensures we keep the peptide features in sequence order
2005 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2006 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2008 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2009 if (dnaFeatures == null)
2014 int dnaStart = dnaSeq.getStart();
2015 int[] lastCodon = null;
2016 int lastPeptidePostion = 0;
2019 * build a map of codon variations for peptides
2021 for (SequenceFeature sf : dnaFeatures)
2023 int dnaCol = sf.getBegin();
2024 if (dnaCol != sf.getEnd())
2026 // not handling multi-locus variant features
2029 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2031 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2034 // feature doesn't lie within coding region
2037 int peptidePosition = mapsTo[0];
2038 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2039 if (codonVariants == null)
2041 codonVariants = new ArrayList[3];
2042 codonVariants[0] = new ArrayList<DnaVariant>();
2043 codonVariants[1] = new ArrayList<DnaVariant>();
2044 codonVariants[2] = new ArrayList<DnaVariant>();
2045 variants.put(peptidePosition, codonVariants);
2049 * extract dna variants to a string array
2051 String alls = (String) sf.getValue("alleles");
2056 String[] alleles = alls.toUpperCase().split(",");
2058 for (String allele : alleles)
2060 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2064 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2066 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2067 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2068 peptidePosition, peptidePosition));
2069 lastPeptidePostion = peptidePosition;
2073 * save nucleotide (and any variant) for each codon position
2075 for (int codonPos = 0; codonPos < 3; codonPos++)
2077 String nucleotide = String.valueOf(
2078 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2080 List<DnaVariant> codonVariant = codonVariants[codonPos];
2081 if (codon[codonPos] == dnaCol)
2083 if (!codonVariant.isEmpty()
2084 && codonVariant.get(0).variant == null)
2087 * already recorded base value, add this variant
2089 codonVariant.get(0).variant = sf;
2094 * add variant with base value
2096 codonVariant.add(new DnaVariant(nucleotide, sf));
2099 else if (codonVariant.isEmpty())
2102 * record (possibly non-varying) base value
2104 codonVariant.add(new DnaVariant(nucleotide));
2113 * Makes an alignment with a copy of the given sequences, adding in any
2114 * non-redundant sequences which are mapped to by the cross-referenced
2121 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2124 AlignmentI copy = new Alignment(new Alignment(seqs));
2127 * add mappings between sequences to the new alignment
2129 AlignedCodonFrame mappings = new AlignedCodonFrame();
2130 copy.addCodonFrame(mappings);
2131 for (int i = 0; i < copy.getHeight(); i++)
2133 SequenceI from = seqs[i];
2134 SequenceI to = copy.getSequenceAt(i);
2135 if (to.getDatasetSequence() != null)
2137 to = to.getDatasetSequence();
2139 int start = from.getStart();
2140 int end = from.getEnd();
2141 MapList map = new MapList(new int[] { start, end }, new int[] {
2142 start, end }, 1, 1);
2143 mappings.addMap(to, from, map);
2146 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2149 for (SequenceI xref : xrefs)
2151 DBRefEntry[] dbrefs = xref.getDBRefs();
2154 for (DBRefEntry dbref : dbrefs)
2156 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2160 SequenceI mappedTo = dbref.getMap().getTo();
2161 SequenceI match = matcher.findIdMatch(mappedTo);
2164 matcher.add(mappedTo);
2165 copy.addSequence(mappedTo);
2175 * Try to align sequences in 'unaligned' to match the alignment of their
2176 * mapped regions in 'aligned'. For example, could use this to align CDS
2177 * sequences which are mapped to their parent cDNA sequences.
2179 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2180 * dna-to-protein or protein-to-dna use alternative methods.
2183 * sequences to be aligned
2185 * holds aligned sequences and their mappings
2188 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2190 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2191 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2192 unaligned, aligned, unmapped);
2193 int width = columnMap.size();
2194 char gap = unaligned.getGapCharacter();
2195 int realignedCount = 0;
2197 for (SequenceI seq : unaligned.getSequences())
2199 if (!unmapped.contains(seq))
2201 char[] newSeq = new char[width];
2202 Arrays.fill(newSeq, gap);
2207 * traverse the map to find columns populated
2210 for (Integer column : columnMap.keySet())
2212 Character c = columnMap.get(column).get(seq);
2216 * sequence has a character at this position
2226 * trim trailing gaps
2228 if (lastCol < width)
2230 char[] tmp = new char[lastCol + 1];
2231 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2234 seq.setSequence(String.valueOf(newSeq));
2238 return realignedCount;
2242 * Returns a map whose key is alignment column number (base 1), and whose
2243 * values are a map of sequence characters in that column.
2250 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2251 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2254 * Map will hold, for each aligned column position, a map of
2255 * {unalignedSequence, sequenceCharacter} at that position.
2256 * TreeMap keeps the entries in ascending column order.
2258 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2261 * r any sequences that have no mapping so can't be realigned
2263 unmapped.addAll(unaligned.getSequences());
2265 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2267 for (SequenceI seq : unaligned.getSequences())
2269 for (AlignedCodonFrame mapping : mappings)
2271 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2272 if (fromSeq != null)
2274 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2275 if (addMappedPositions(seq, fromSeq, seqMap, map))
2277 unmapped.remove(seq);
2286 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2287 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2288 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2292 * the sequence whose column positions we are recording
2294 * a sequence that is mapped to the first sequence
2296 * the mapping from 'fromSeq' to 'seq'
2298 * a map to add the column positions (in fromSeq) of the mapped
2302 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2303 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2310 char[] fromChars = fromSeq.getSequence();
2311 int toStart = seq.getStart();
2312 char[] toChars = seq.getSequence();
2315 * traverse [start, end, start, end...] ranges in fromSeq
2317 for (int[] fromRange : seqMap.getMap().getFromRanges())
2319 for (int i = 0; i < fromRange.length - 1; i += 2)
2321 boolean forward = fromRange[i + 1] >= fromRange[i];
2324 * find the range mapped to (sequence positions base 1)
2326 int[] range = seqMap.locateMappedRange(fromRange[i],
2330 System.err.println("Error in mapping " + seqMap + " from "
2331 + fromSeq.getName());
2334 int fromCol = fromSeq.findIndex(fromRange[i]);
2335 int mappedCharPos = range[0];
2338 * walk over the 'from' aligned sequence in forward or reverse
2339 * direction; when a non-gap is found, record the column position
2340 * of the next character of the mapped-to sequence; stop when all
2341 * the characters of the range have been counted
2343 while (mappedCharPos <= range[1])
2345 if (!Comparison.isGap(fromChars[fromCol - 1]))
2348 * mapped from sequence has a character in this column
2349 * record the column position for the mapped to character
2351 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2352 if (seqsMap == null)
2354 seqsMap = new HashMap<SequenceI, Character>();
2355 map.put(fromCol, seqsMap);
2357 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2360 fromCol += (forward ? 1 : -1);
2367 // strictly temporary hack until proper criteria for aligning protein to cds
2368 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2369 public static boolean looksLikeEnsembl(AlignmentI alignment)
2371 for (SequenceI seq : alignment.getSequences())
2373 String name = seq.getName();
2374 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))