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 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
1338 for (AlignmentAnnotation aa : anns)
1340 if (anyType || types.contains(aa.label))
1342 if ((aa.sequenceRef != null)
1343 && (forSequences == null || forSequences
1344 .contains(aa.sequenceRef)))
1346 aa.visible = doShow;
1354 * Returns true if either sequence has a cross-reference to the other
1360 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1362 // Note: moved here from class CrossRef as the latter class has dependencies
1363 // not availability to the applet's classpath
1364 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1368 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1369 * that sequence name is structured as Source|AccessionId.
1375 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1377 if (seq1 == null || seq2 == null)
1381 String name = seq2.getName();
1382 final DBRefEntry[] xrefs = seq1.getDBRefs();
1385 for (DBRefEntry xref : xrefs)
1387 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1388 // case-insensitive test, consistent with DBRefEntry.equalRef()
1389 if (xrefName.equalsIgnoreCase(name))
1399 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1400 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1401 * added to the original alignment's dataset, which is shared by the new
1402 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1403 * added to the alignment dataset.
1406 * aligned dna sequences
1408 * from dna to protein
1410 * @return an alignment whose sequences are the cds-only parts of the dna
1411 * sequences (or null if no mappings are found)
1413 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1414 List<AlignedCodonFrame> mappings, AlignmentI al)
1416 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1418 for (SequenceI seq : dna)
1420 AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1421 List<AlignedCodonFrame> seqMappings = MappingUtils
1422 .findMappingsForSequence(seq, mappings);
1423 List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1424 for (AlignedCodonFrame mapping : seqMappings)
1426 for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1428 SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1430 cdsSeqs.add(cdsSeq);
1433 * add a mapping from CDS to the (unchanged) mapped to range
1435 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1436 cdsSeq.getLength() });
1437 MapList map = new MapList(cdsRange, aMapping.getMap()
1438 .getToRanges(), aMapping.getMap().getFromRatio(),
1439 aMapping.getMap().getToRatio());
1440 cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1443 * add another mapping from original 'from' range to CDS
1445 map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1447 cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1449 alignmentMappings.add(cdsMappings);
1452 * transfer any features on dna that overlap the CDS
1454 transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1460 * add CDS seqs to shared dataset
1462 Alignment dataset = al.getDataset();
1463 for (SequenceI seq : cdsSeqs)
1465 if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1467 dataset.addSequence(seq.getDatasetSequence());
1470 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1472 cds.setDataset(dataset);
1478 * Helper method that makes a CDS sequence as defined by the mappings from the
1479 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1480 * forward or reverse strand).
1486 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1488 char[] seqChars = seq.getSequence();
1489 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1490 int cdsWidth = MappingUtils.getLength(fromRanges);
1491 char[] newSeqChars = new char[cdsWidth];
1494 for (int[] range : fromRanges)
1496 if (range[0] <= range[1])
1498 // forward strand mapping - just copy the range
1499 int length = range[1] - range[0] + 1;
1500 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1506 // reverse strand mapping - copy and complement one by one
1507 for (int i = range[0]; i >= range[1]; i--)
1509 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1514 SequenceI newSeq = new Sequence(seq.getName() + "|"
1515 + mapping.getTo().getName(), newSeqChars, 1, newPos);
1516 newSeq.createDatasetSequence();
1521 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1522 * feature start/end ranges, optionally omitting specified feature types.
1523 * Returns the number of features copied.
1528 * if not null, only features of this type are copied (including
1529 * subtypes in the Sequence Ontology)
1531 * the mapping from 'fromSeq' to 'toSeq'
1534 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1535 MapList mapping, String select, String... omitting)
1537 SequenceI copyTo = toSeq;
1538 while (copyTo.getDatasetSequence() != null)
1540 copyTo = copyTo.getDatasetSequence();
1543 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1545 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1548 for (SequenceFeature sf : sfs)
1550 String type = sf.getType();
1551 if (select != null && !so.isA(type, select))
1555 boolean omit = false;
1556 for (String toOmit : omitting)
1558 if (type.equals(toOmit))
1569 * locate the mapped range - null if either start or end is
1570 * not mapped (no partial overlaps are calculated)
1572 int start = sf.getBegin();
1573 int end = sf.getEnd();
1574 int[] mappedTo = mapping.locateInTo(start, end);
1576 * if whole exon range doesn't map, try interpreting it
1577 * as 5' or 3' exon overlapping the CDS range
1579 if (mappedTo == null)
1581 mappedTo = mapping.locateInTo(end, end);
1582 if (mappedTo != null)
1585 * end of exon is in CDS range - 5' overlap
1586 * to a range from the start of the peptide
1591 if (mappedTo == null)
1593 mappedTo = mapping.locateInTo(start, start);
1594 if (mappedTo != null)
1597 * start of exon is in CDS range - 3' overlap
1598 * to a range up to the end of the peptide
1600 mappedTo[1] = toSeq.getLength();
1603 if (mappedTo != null)
1605 SequenceFeature copy = new SequenceFeature(sf);
1606 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1607 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1608 copyTo.addSequenceFeature(copy);
1617 * Returns a mapping from dna to protein by inspecting sequence features of
1618 * type "CDS" on the dna.
1624 public static MapList mapCdsToProtein(SequenceI dnaSeq,
1625 SequenceI proteinSeq)
1627 List<int[]> ranges = findCdsPositions(dnaSeq);
1628 int mappedDnaLength = MappingUtils.getLength(ranges);
1630 int proteinLength = proteinSeq.getLength();
1631 int proteinStart = proteinSeq.getStart();
1632 int proteinEnd = proteinSeq.getEnd();
1635 * incomplete start codon may mean X at start of peptide
1636 * we ignore both for mapping purposes
1638 if (proteinSeq.getCharAt(0) == 'X')
1640 // todo JAL-2022 support startPhase > 0
1644 List<int[]> proteinRange = new ArrayList<int[]>();
1647 * dna length should map to protein (or protein plus stop codon)
1649 int codesForResidues = mappedDnaLength / 3;
1650 if (codesForResidues == (proteinLength + 1))
1652 // assuming extra codon is for STOP and not in peptide
1655 if (codesForResidues == proteinLength)
1657 proteinRange.add(new int[] { proteinStart, proteinEnd });
1658 return new MapList(ranges, proteinRange, 3, 1);
1664 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1665 * start/end positions of sequence features of type "CDS" (or a sub-type of
1666 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1667 * position order, so this method is only valid for linear CDS in the same
1668 * sense as the protein product.
1673 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1675 List<int[]> result = new ArrayList<int[]>();
1676 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1682 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1685 for (SequenceFeature sf : sfs)
1688 * process a CDS feature (or a sub-type of CDS)
1690 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1695 phase = Integer.parseInt(sf.getPhase());
1696 } catch (NumberFormatException e)
1701 * phase > 0 on first codon means 5' incomplete - skip to the start
1702 * of the next codon; example ENST00000496384
1704 int begin = sf.getBegin();
1705 int end = sf.getEnd();
1706 if (result.isEmpty())
1711 // shouldn't happen!
1713 .println("Error: start phase extends beyond start CDS in "
1714 + dnaSeq.getName());
1717 result.add(new int[] { begin, end });
1722 * remove 'startPhase' positions (usually 0) from the first range
1723 * so we begin at the start of a complete codon
1725 if (!result.isEmpty())
1727 // TODO JAL-2022 correctly model start phase > 0
1728 result.get(0)[0] += startPhase;
1732 * Finally sort ranges by start position. This avoids a dependency on
1733 * keeping features in order on the sequence (if they are in order anyway,
1734 * the sort will have almost no work to do). The implicit assumption is CDS
1735 * ranges are assembled in order. Other cases should not use this method,
1736 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1738 Collections.sort(result, new Comparator<int[]>()
1741 public int compare(int[] o1, int[] o2)
1743 return Integer.compare(o1[0], o2[0]);
1750 * Maps exon features from dna to protein, and computes variants in peptide
1751 * product generated by variants in dna, and adds them as sequence_variant
1752 * features on the protein sequence. Returns the number of variant features
1757 * @param dnaToProtein
1759 public static int computeProteinFeatures(SequenceI dnaSeq,
1760 SequenceI peptide, MapList dnaToProtein)
1762 while (dnaSeq.getDatasetSequence() != null)
1764 dnaSeq = dnaSeq.getDatasetSequence();
1766 while (peptide.getDatasetSequence() != null)
1768 peptide = peptide.getDatasetSequence();
1771 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1774 * compute protein variants from dna variants and codon mappings;
1775 * NB - alternatively we could retrieve this using the REST service e.g.
1776 * http://rest.ensembl.org/overlap/translation
1777 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1778 * which would be a bit slower but possibly more reliable
1782 * build a map with codon variations for each potentially varying peptide
1784 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1785 dnaSeq, dnaToProtein);
1788 * scan codon variations, compute peptide variants and add to peptide sequence
1791 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1793 int peptidePos = variant.getKey();
1794 List<DnaVariant>[] codonVariants = variant.getValue();
1795 count += computePeptideVariants(peptide, peptidePos, codonVariants);
1799 * sort to get sequence features in start position order
1800 * - would be better to store in Sequence as a TreeSet or NCList?
1802 Arrays.sort(peptide.getSequenceFeatures(),
1803 new Comparator<SequenceFeature>()
1806 public int compare(SequenceFeature o1, SequenceFeature o2)
1808 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1809 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1817 * Computes non-synonymous peptide variants from codon variants and adds them
1818 * as sequence_variant features on the protein sequence (one feature per
1819 * allele variant). Selected attributes (variant id, clinical significance)
1820 * are copied over to the new features.
1823 * the protein sequence
1825 * the position to compute peptide variants for
1826 * @param codonVariants
1827 * a list of dna variants per codon position
1828 * @return the number of features added
1830 static int computePeptideVariants(SequenceI peptide, int peptidePos,
1831 List<DnaVariant>[] codonVariants)
1833 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1835 String base1 = codonVariants[0].get(0).base;
1836 String base2 = codonVariants[1].get(0).base;
1837 String base3 = codonVariants[2].get(0).base;
1840 * variants in first codon base
1842 for (DnaVariant var : codonVariants[0])
1844 if (var.variant != null)
1846 String alleles = (String) var.variant.getValue("alleles");
1847 if (alleles != null)
1849 for (String base : alleles.split(","))
1851 String codon = base + base2 + base3;
1852 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1862 * variants in second codon base
1864 for (DnaVariant var : codonVariants[1])
1866 if (var.variant != null)
1868 String alleles = (String) var.variant.getValue("alleles");
1869 if (alleles != null)
1871 for (String base : alleles.split(","))
1873 String codon = base1 + base + base3;
1874 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1884 * variants in third codon base
1886 for (DnaVariant var : codonVariants[2])
1888 if (var.variant != null)
1890 String alleles = (String) var.variant.getValue("alleles");
1891 if (alleles != null)
1893 for (String base : alleles.split(","))
1895 String codon = base1 + base2 + base;
1896 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1909 * Helper method that adds a peptide variant feature, provided the given codon
1910 * translates to a value different to the current residue (is a non-synonymous
1911 * variant). ID and clinical_significance attributes of the dna variant (if
1912 * present) are copied to the new feature.
1919 * @return true if a feature was added, else false
1921 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1922 String residue, DnaVariant var, String codon)
1925 * get peptide translation of codon e.g. GAT -> D
1926 * note that variants which are not single alleles,
1927 * e.g. multibase variants or HGMD_MUTATION etc
1928 * are currently ignored here
1930 String trans = codon.contains("-") ? "-"
1931 : (codon.length() > 3 ? null : ResidueProperties
1932 .codonTranslate(codon));
1933 if (trans != null && !trans.equals(residue))
1935 String residue3Char = StringUtils
1936 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
1937 String trans3Char = StringUtils
1938 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
1939 String desc = "p." + residue3Char + peptidePos + trans3Char;
1940 // set score to 0f so 'graduated colour' option is offered! JAL-2060
1941 SequenceFeature sf = new SequenceFeature(
1942 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1943 peptidePos, 0f, "Jalview");
1944 StringBuilder attributes = new StringBuilder(32);
1945 String id = (String) var.variant.getValue(ID);
1948 if (id.startsWith(SEQUENCE_VARIANT))
1950 id = id.substring(SEQUENCE_VARIANT.length());
1952 sf.setValue(ID, id);
1953 attributes.append(ID).append("=").append(id);
1954 // TODO handle other species variants
1955 StringBuilder link = new StringBuilder(32);
1958 link.append(desc).append(" ").append(id)
1959 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
1960 .append(URLEncoder.encode(id, "UTF-8"));
1961 sf.addLink(link.toString());
1962 } catch (UnsupportedEncodingException e)
1967 String clinSig = (String) var.variant
1968 .getValue(CLINICAL_SIGNIFICANCE);
1969 if (clinSig != null)
1971 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
1972 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
1975 peptide.addSequenceFeature(sf);
1976 if (attributes.length() > 0)
1978 sf.setAttributes(attributes.toString());
1986 * Builds a map whose key is position in the protein sequence, and value is a
1987 * list of the base and all variants for each corresponding codon position
1990 * @param dnaToProtein
1993 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
1994 SequenceI dnaSeq, MapList dnaToProtein)
1997 * map from peptide position to all variants of the codon which codes for it
1998 * LinkedHashMap ensures we keep the peptide features in sequence order
2000 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2001 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2003 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2004 if (dnaFeatures == null)
2009 int dnaStart = dnaSeq.getStart();
2010 int[] lastCodon = null;
2011 int lastPeptidePostion = 0;
2014 * build a map of codon variations for peptides
2016 for (SequenceFeature sf : dnaFeatures)
2018 int dnaCol = sf.getBegin();
2019 if (dnaCol != sf.getEnd())
2021 // not handling multi-locus variant features
2024 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2026 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2029 // feature doesn't lie within coding region
2032 int peptidePosition = mapsTo[0];
2033 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2034 if (codonVariants == null)
2036 codonVariants = new ArrayList[3];
2037 codonVariants[0] = new ArrayList<DnaVariant>();
2038 codonVariants[1] = new ArrayList<DnaVariant>();
2039 codonVariants[2] = new ArrayList<DnaVariant>();
2040 variants.put(peptidePosition, codonVariants);
2044 * extract dna variants to a string array
2046 String alls = (String) sf.getValue("alleles");
2051 String[] alleles = alls.toUpperCase().split(",");
2053 for (String allele : alleles)
2055 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2059 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2061 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2062 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2063 peptidePosition, peptidePosition));
2064 lastPeptidePostion = peptidePosition;
2068 * save nucleotide (and any variant) for each codon position
2070 for (int codonPos = 0; codonPos < 3; codonPos++)
2072 String nucleotide = String.valueOf(
2073 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2075 List<DnaVariant> codonVariant = codonVariants[codonPos];
2076 if (codon[codonPos] == dnaCol)
2078 if (!codonVariant.isEmpty()
2079 && codonVariant.get(0).variant == null)
2082 * already recorded base value, add this variant
2084 codonVariant.get(0).variant = sf;
2089 * add variant with base value
2091 codonVariant.add(new DnaVariant(nucleotide, sf));
2094 else if (codonVariant.isEmpty())
2097 * record (possibly non-varying) base value
2099 codonVariant.add(new DnaVariant(nucleotide));
2108 * Makes an alignment with a copy of the given sequences, adding in any
2109 * non-redundant sequences which are mapped to by the cross-referenced
2116 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2119 AlignmentI copy = new Alignment(new Alignment(seqs));
2122 * add mappings between sequences to the new alignment
2124 AlignedCodonFrame mappings = new AlignedCodonFrame();
2125 copy.addCodonFrame(mappings);
2126 for (int i = 0; i < copy.getHeight(); i++)
2128 SequenceI from = seqs[i];
2129 SequenceI to = copy.getSequenceAt(i);
2130 if (to.getDatasetSequence() != null)
2132 to = to.getDatasetSequence();
2134 int start = from.getStart();
2135 int end = from.getEnd();
2136 MapList map = new MapList(new int[] { start, end }, new int[] {
2137 start, end }, 1, 1);
2138 mappings.addMap(to, from, map);
2141 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2144 for (SequenceI xref : xrefs)
2146 DBRefEntry[] dbrefs = xref.getDBRefs();
2149 for (DBRefEntry dbref : dbrefs)
2151 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2155 SequenceI mappedTo = dbref.getMap().getTo();
2156 SequenceI match = matcher.findIdMatch(mappedTo);
2159 matcher.add(mappedTo);
2160 copy.addSequence(mappedTo);
2170 * Try to align sequences in 'unaligned' to match the alignment of their
2171 * mapped regions in 'aligned'. For example, could use this to align CDS
2172 * sequences which are mapped to their parent cDNA sequences.
2174 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2175 * dna-to-protein or protein-to-dna use alternative methods.
2178 * sequences to be aligned
2180 * holds aligned sequences and their mappings
2183 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2185 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2186 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2187 unaligned, aligned, unmapped);
2188 int width = columnMap.size();
2189 char gap = unaligned.getGapCharacter();
2190 int realignedCount = 0;
2192 for (SequenceI seq : unaligned.getSequences())
2194 if (!unmapped.contains(seq))
2196 char[] newSeq = new char[width];
2197 Arrays.fill(newSeq, gap);
2202 * traverse the map to find columns populated
2205 for (Integer column : columnMap.keySet())
2207 Character c = columnMap.get(column).get(seq);
2211 * sequence has a character at this position
2221 * trim trailing gaps
2223 if (lastCol < width)
2225 char[] tmp = new char[lastCol + 1];
2226 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2229 seq.setSequence(String.valueOf(newSeq));
2233 return realignedCount;
2237 * Returns a map whose key is alignment column number (base 1), and whose
2238 * values are a map of sequence characters in that column.
2245 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2246 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2249 * Map will hold, for each aligned column position, a map of
2250 * {unalignedSequence, sequenceCharacter} at that position.
2251 * TreeMap keeps the entries in ascending column order.
2253 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2256 * r any sequences that have no mapping so can't be realigned
2258 unmapped.addAll(unaligned.getSequences());
2260 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2262 for (SequenceI seq : unaligned.getSequences())
2264 for (AlignedCodonFrame mapping : mappings)
2266 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2267 if (fromSeq != null)
2269 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2270 if (addMappedPositions(seq, fromSeq, seqMap, map))
2272 unmapped.remove(seq);
2281 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2282 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2283 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2287 * the sequence whose column positions we are recording
2289 * a sequence that is mapped to the first sequence
2291 * the mapping from 'fromSeq' to 'seq'
2293 * a map to add the column positions (in fromSeq) of the mapped
2297 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2298 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2305 char[] fromChars = fromSeq.getSequence();
2306 int toStart = seq.getStart();
2307 char[] toChars = seq.getSequence();
2310 * traverse [start, end, start, end...] ranges in fromSeq
2312 for (int[] fromRange : seqMap.getMap().getFromRanges())
2314 for (int i = 0; i < fromRange.length - 1; i += 2)
2316 boolean forward = fromRange[i + 1] >= fromRange[i];
2319 * find the range mapped to (sequence positions base 1)
2321 int[] range = seqMap.locateMappedRange(fromRange[i],
2325 System.err.println("Error in mapping " + seqMap + " from "
2326 + fromSeq.getName());
2329 int fromCol = fromSeq.findIndex(fromRange[i]);
2330 int mappedCharPos = range[0];
2333 * walk over the 'from' aligned sequence in forward or reverse
2334 * direction; when a non-gap is found, record the column position
2335 * of the next character of the mapped-to sequence; stop when all
2336 * the characters of the range have been counted
2338 while (mappedCharPos <= range[1])
2340 if (!Comparison.isGap(fromChars[fromCol - 1]))
2343 * mapped from sequence has a character in this column
2344 * record the column position for the mapped to character
2346 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2347 if (seqsMap == null)
2349 seqsMap = new HashMap<SequenceI, Character>();
2350 map.put(fromCol, seqsMap);
2352 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2355 fromCol += (forward ? 1 : -1);
2362 // strictly temporary hack until proper criteria for aligning protein to cds
2363 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2364 public static boolean looksLikeEnsembl(AlignmentI alignment)
2366 for (SequenceI seq : alignment.getSequences())
2368 String name = seq.getName();
2369 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))