2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.analysis;
23 import static jalview.io.gff.GffConstants.CLINICAL_SIGNIFICANCE;
25 import jalview.datamodel.AlignedCodon;
26 import jalview.datamodel.AlignedCodonFrame;
27 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.DBRefEntry;
32 import jalview.datamodel.IncompleteCodonException;
33 import jalview.datamodel.Mapping;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.gff.SequenceOntologyFactory;
39 import jalview.io.gff.SequenceOntologyI;
40 import jalview.schemes.ResidueProperties;
41 import jalview.util.Comparison;
42 import jalview.util.DBRefUtils;
43 import jalview.util.MapList;
44 import jalview.util.MappingUtils;
45 import jalview.util.StringUtils;
47 import java.io.UnsupportedEncodingException;
48 import java.net.URLEncoder;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.Collection;
52 import java.util.Collections;
53 import java.util.Comparator;
54 import java.util.HashMap;
55 import java.util.HashSet;
56 import java.util.Iterator;
57 import java.util.LinkedHashMap;
58 import java.util.List;
60 import java.util.Map.Entry;
61 import java.util.NoSuchElementException;
63 import java.util.TreeMap;
66 * grab bag of useful alignment manipulation operations Expect these to be
67 * refactored elsewhere at some point.
72 public class AlignmentUtils
75 private static final String SEQUENCE_VARIANT = "sequence_variant:";
76 private static final String ID = "ID";
79 * A data model to hold the 'normal' base value at a position, and an optional
80 * sequence variant feature
82 static class DnaVariant
86 SequenceFeature variant;
88 DnaVariant(String nuc)
93 DnaVariant(String nuc, SequenceFeature var)
101 * given an existing alignment, create a new alignment including all, or up to
102 * flankSize additional symbols from each sequence's dataset sequence
108 public static AlignmentI expandContext(AlignmentI core, int flankSize)
110 List<SequenceI> sq = new ArrayList<SequenceI>();
112 for (SequenceI s : core.getSequences())
114 SequenceI newSeq = s.deriveSequence();
115 final int newSeqStart = newSeq.getStart() - 1;
116 if (newSeqStart > maxoffset
117 && newSeq.getDatasetSequence().getStart() < s.getStart())
119 maxoffset = newSeqStart;
125 maxoffset = Math.min(maxoffset, flankSize);
129 * now add offset left and right to create an expanded alignment
131 for (SequenceI s : sq)
134 while (ds.getDatasetSequence() != null)
136 ds = ds.getDatasetSequence();
138 int s_end = s.findPosition(s.getStart() + s.getLength());
139 // find available flanking residues for sequence
140 int ustream_ds = s.getStart() - ds.getStart();
141 int dstream_ds = ds.getEnd() - s_end;
143 // build new flanked sequence
145 // compute gap padding to start of flanking sequence
146 int offset = maxoffset - ustream_ds;
148 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
151 if (flankSize < ustream_ds)
153 // take up to flankSize residues
154 offset = maxoffset - flankSize;
155 ustream_ds = flankSize;
157 if (flankSize <= dstream_ds)
159 dstream_ds = flankSize - 1;
162 // TODO use Character.toLowerCase to avoid creating String objects?
163 char[] upstream = new String(ds.getSequence(s.getStart() - 1
164 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
165 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
166 + dstream_ds)).toLowerCase().toCharArray();
167 char[] coreseq = s.getSequence();
168 char[] nseq = new char[offset + upstream.length + downstream.length
170 char c = core.getGapCharacter();
173 for (; p < offset; p++)
178 System.arraycopy(upstream, 0, nseq, p, upstream.length);
179 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
181 System.arraycopy(downstream, 0, nseq, p + coreseq.length
182 + upstream.length, downstream.length);
183 s.setSequence(new String(nseq));
184 s.setStart(s.getStart() - ustream_ds);
185 s.setEnd(s_end + downstream.length);
187 AlignmentI newAl = new jalview.datamodel.Alignment(
188 sq.toArray(new SequenceI[0]));
189 for (SequenceI s : sq)
191 if (s.getAnnotation() != null)
193 for (AlignmentAnnotation aa : s.getAnnotation())
195 aa.adjustForAlignment(); // JAL-1712 fix
196 newAl.addAnnotation(aa);
200 newAl.setDataset(core.getDataset());
205 * Returns the index (zero-based position) of a sequence in an alignment, or
212 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
216 for (SequenceI alSeq : al.getSequences())
229 * Returns a map of lists of sequences in the alignment, keyed by sequence
230 * name. For use in mapping between different alignment views of the same
233 * @see jalview.datamodel.AlignmentI#getSequencesByName()
235 public static Map<String, List<SequenceI>> getSequencesByName(
238 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
239 for (SequenceI seq : al.getSequences())
241 String name = seq.getName();
244 List<SequenceI> seqs = theMap.get(name);
247 seqs = new ArrayList<SequenceI>();
248 theMap.put(name, seqs);
257 * Build mapping of protein to cDNA alignment. Mappings are made between
258 * sequences where the cDNA translates to the protein sequence. Any new
259 * mappings are added to the protein alignment. Returns true if any mappings
260 * either already exist or were added, else false.
262 * @param proteinAlignment
263 * @param cdnaAlignment
266 public static boolean mapProteinAlignmentToCdna(
267 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
269 if (proteinAlignment == null || cdnaAlignment == null)
274 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
275 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
278 * First pass - map sequences where cross-references exist. This include
279 * 1-to-many mappings to support, for example, variant cDNA.
281 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
282 cdnaAlignment, mappedDna, mappedProtein, true);
285 * Second pass - map sequences where no cross-references exist. This only
286 * does 1-to-1 mappings and assumes corresponding sequences are in the same
287 * order in the alignments.
289 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
290 mappedDna, mappedProtein, false);
291 return mappingPerformed;
295 * Make mappings between compatible sequences (where the cDNA translation
296 * matches the protein).
298 * @param proteinAlignment
299 * @param cdnaAlignment
301 * a set of mapped DNA sequences (to add to)
302 * @param mappedProtein
303 * a set of mapped Protein sequences (to add to)
305 * if true, only map sequences where xrefs exist
308 protected static boolean mapProteinToCdna(
309 final AlignmentI proteinAlignment,
310 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
311 Set<SequenceI> mappedProtein, boolean xrefsOnly)
313 boolean mappingExistsOrAdded = false;
314 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
315 for (SequenceI aaSeq : thisSeqs)
317 boolean proteinMapped = false;
318 AlignedCodonFrame acf = new AlignedCodonFrame();
320 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
323 * Always try to map if sequences have xref to each other; this supports
324 * variant cDNA or alternative splicing for a protein sequence.
326 * If no xrefs, try to map progressively, assuming that alignments have
327 * mappable sequences in corresponding order. These are not
328 * many-to-many, as that would risk mixing species with similar cDNA
331 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
337 * Don't map non-xrefd sequences more than once each. This heuristic
338 * allows us to pair up similar sequences in ordered alignments.
341 && (mappedProtein.contains(aaSeq) || mappedDna
346 if (mappingExists(proteinAlignment.getCodonFrames(),
347 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
349 mappingExistsOrAdded = true;
353 MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
356 acf.addMap(cdnaSeq, aaSeq, map);
357 mappingExistsOrAdded = true;
358 proteinMapped = true;
359 mappedDna.add(cdnaSeq);
360 mappedProtein.add(aaSeq);
366 proteinAlignment.addCodonFrame(acf);
369 return mappingExistsOrAdded;
373 * Answers true if the mappings include one between the given (dataset)
376 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
377 SequenceI aaSeq, SequenceI cdnaSeq)
379 if (mappings != null)
381 for (AlignedCodonFrame acf : mappings)
383 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
393 * Builds a mapping (if possible) of a cDNA to a protein sequence.
395 * <li>first checks if the cdna translates exactly to the protein sequence</li>
396 * <li>else checks for translation after removing a STOP codon</li>
397 * <li>else checks for translation after removing a START codon</li>
398 * <li>if that fails, inspect CDS features on the cDNA sequence</li>
400 * Returns null if no mapping is determined.
403 * the aligned protein sequence
405 * the aligned cdna sequence
408 public static MapList mapCdnaToProtein(SequenceI proteinSeq,
412 * Here we handle either dataset sequence set (desktop) or absent (applet).
413 * Use only the char[] form of the sequence to avoid creating possibly large
416 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
417 char[] aaSeqChars = proteinDataset != null ? proteinDataset
418 .getSequence() : proteinSeq.getSequence();
419 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
420 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
421 : cdnaSeq.getSequence();
422 if (aaSeqChars == null || cdnaSeqChars == null)
428 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
430 final int mappedLength = 3 * aaSeqChars.length;
431 int cdnaLength = cdnaSeqChars.length;
432 int cdnaStart = cdnaSeq.getStart();
433 int cdnaEnd = cdnaSeq.getEnd();
434 final int proteinStart = proteinSeq.getStart();
435 final int proteinEnd = proteinSeq.getEnd();
438 * If lengths don't match, try ignoring stop codon (if present)
440 if (cdnaLength != mappedLength && cdnaLength > 2)
442 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
444 for (String stop : ResidueProperties.STOP)
446 if (lastCodon.equals(stop))
456 * If lengths still don't match, try ignoring start codon.
459 if (cdnaLength != mappedLength
461 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
462 .equals(ResidueProperties.START))
469 if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
472 * protein is translation of dna (+/- start/stop codons)
474 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
475 { proteinStart, proteinEnd }, 3, 1);
480 * translation failed - try mapping CDS annotated regions of dna
482 return mapCdsToProtein(cdnaSeq, proteinSeq);
486 * Test whether the given cdna sequence, starting at the given offset,
487 * translates to the given amino acid sequence, using the standard translation
488 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
490 * @param cdnaSeqChars
495 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
498 if (cdnaSeqChars == null || aaSeqChars == null)
504 int dnaPos = cdnaStart;
505 for (; dnaPos < cdnaSeqChars.length - 2
506 && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
508 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
509 final String translated = ResidueProperties.codonTranslate(codon);
512 * allow * in protein to match untranslatable in dna
514 final char aaRes = aaSeqChars[aaPos];
515 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
519 if (translated == null || !(aaRes == translated.charAt(0)))
522 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
523 // + codon + "(" + translated + ") != " + aaRes));
529 * check we matched all of the protein sequence
531 if (aaPos != aaSeqChars.length)
537 * check we matched all of the dna except
538 * for optional trailing STOP codon
540 if (dnaPos == cdnaSeqChars.length)
544 if (dnaPos == cdnaSeqChars.length - 3)
546 String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
547 if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
556 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
557 * currently assumes that we are aligning cDNA to match protein.
560 * the sequence to be realigned
562 * the alignment whose sequence alignment is to be 'copied'
564 * character string represent a gap in the realigned sequence
565 * @param preserveUnmappedGaps
566 * @param preserveMappedGaps
567 * @return true if the sequence was realigned, false if it could not be
569 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
570 String gap, boolean preserveMappedGaps,
571 boolean preserveUnmappedGaps)
574 * Get any mappings from the source alignment to the target (dataset)
577 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
578 // all mappings. Would it help to constrain this?
579 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
580 if (mappings == null || mappings.isEmpty())
586 * Locate the aligned source sequence whose dataset sequence is mapped. We
587 * just take the first match here (as we can't align like more than one
590 SequenceI alignFrom = null;
591 AlignedCodonFrame mapping = null;
592 for (AlignedCodonFrame mp : mappings)
594 alignFrom = mp.findAlignedSequence(seq, al);
595 if (alignFrom != null)
602 if (alignFrom == null)
606 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
607 preserveMappedGaps, preserveUnmappedGaps);
612 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
613 * match residues and codons. Flags control whether existing gaps in unmapped
614 * (intron) and mapped (exon) regions are preserved or not. Gaps between
615 * intron and exon are only retained if both flags are set.
622 * @param preserveUnmappedGaps
623 * @param preserveMappedGaps
625 public static void alignSequenceAs(SequenceI alignTo,
626 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
627 char sourceGap, boolean preserveMappedGaps,
628 boolean preserveUnmappedGaps)
630 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
632 // aligned and dataset sequence positions, all base zero
636 int basesWritten = 0;
637 char myGapChar = myGap.charAt(0);
638 int ratio = myGap.length();
640 int fromOffset = alignFrom.getStart() - 1;
641 int toOffset = alignTo.getStart() - 1;
642 int sourceGapMappedLength = 0;
643 boolean inExon = false;
644 final char[] thisSeq = alignTo.getSequence();
645 final char[] thatAligned = alignFrom.getSequence();
646 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
649 * Traverse the 'model' aligned sequence
651 for (char sourceChar : thatAligned)
653 if (sourceChar == sourceGap)
655 sourceGapMappedLength += ratio;
660 * Found a non-gap character. Locate its mapped region if any.
663 // Note mapping positions are base 1, our sequence positions base 0
664 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
665 sourceDsPos + fromOffset);
666 if (mappedPos == null)
669 * unmapped position; treat like a gap
671 sourceGapMappedLength += ratio;
672 // System.err.println("Can't align: no codon mapping to residue "
673 // + sourceDsPos + "(" + sourceChar + ")");
678 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
679 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
680 StringBuilder trailingCopiedGap = new StringBuilder();
683 * Copy dna sequence up to and including this codon. Optionally, include
684 * gaps before the codon starts (in introns) and/or after the codon starts
687 * Note this only works for 'linear' splicing, not reverse or interleaved.
688 * But then 'align dna as protein' doesn't make much sense otherwise.
690 int intronLength = 0;
691 while (basesWritten + toOffset < mappedCodonEnd
692 && thisSeqPos < thisSeq.length)
694 final char c = thisSeq[thisSeqPos++];
698 int sourcePosition = basesWritten + toOffset;
699 if (sourcePosition < mappedCodonStart)
702 * Found an unmapped (intron) base. First add in any preceding gaps
705 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
707 thisAligned.append(trailingCopiedGap.toString());
708 intronLength += trailingCopiedGap.length();
709 trailingCopiedGap = new StringBuilder();
716 final boolean startOfCodon = sourcePosition == mappedCodonStart;
717 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
718 preserveUnmappedGaps, sourceGapMappedLength, inExon,
719 trailingCopiedGap.length(), intronLength, startOfCodon);
720 for (int i = 0; i < gapsToAdd; i++)
722 thisAligned.append(myGapChar);
724 sourceGapMappedLength = 0;
727 thisAligned.append(c);
728 trailingCopiedGap = new StringBuilder();
732 if (inExon && preserveMappedGaps)
734 trailingCopiedGap.append(myGapChar);
736 else if (!inExon && preserveUnmappedGaps)
738 trailingCopiedGap.append(myGapChar);
745 * At end of model aligned sequence. Copy any remaining target sequence, optionally
746 * including (intron) gaps.
748 while (thisSeqPos < thisSeq.length)
750 final char c = thisSeq[thisSeqPos++];
751 if (c != myGapChar || preserveUnmappedGaps)
753 thisAligned.append(c);
755 sourceGapMappedLength--;
759 * finally add gaps to pad for any trailing source gaps or
760 * unmapped characters
762 if (preserveUnmappedGaps)
764 while (sourceGapMappedLength > 0)
766 thisAligned.append(myGapChar);
767 sourceGapMappedLength--;
772 * All done aligning, set the aligned sequence.
774 alignTo.setSequence(new String(thisAligned));
778 * Helper method to work out how many gaps to insert when realigning.
780 * @param preserveMappedGaps
781 * @param preserveUnmappedGaps
782 * @param sourceGapMappedLength
784 * @param trailingCopiedGap
785 * @param intronLength
786 * @param startOfCodon
789 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
790 boolean preserveUnmappedGaps, int sourceGapMappedLength,
791 boolean inExon, int trailingGapLength, int intronLength,
792 final boolean startOfCodon)
798 * Reached start of codon. Ignore trailing gaps in intron unless we are
799 * preserving gaps in both exon and intron. Ignore them anyway if the
800 * protein alignment introduces a gap at least as large as the intronic
803 if (inExon && !preserveMappedGaps)
805 trailingGapLength = 0;
807 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
809 trailingGapLength = 0;
813 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
817 if (intronLength + trailingGapLength <= sourceGapMappedLength)
819 gapsToAdd = sourceGapMappedLength - intronLength;
823 gapsToAdd = Math.min(intronLength + trailingGapLength
824 - sourceGapMappedLength, trailingGapLength);
831 * second or third base of codon; check for any gaps in dna
833 if (!preserveMappedGaps)
835 trailingGapLength = 0;
837 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
843 * Realigns the given protein to match the alignment of the dna, using codon
844 * mappings to translate aligned codon positions to protein residues.
847 * the alignment whose sequences are realigned by this method
849 * the dna alignment whose alignment we are 'copying'
850 * @return the number of sequences that were realigned
852 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
854 if (protein.isNucleotide() || !dna.isNucleotide())
856 System.err.println("Wrong alignment type in alignProteinAsDna");
859 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
860 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
861 protein, dna, unmappedProtein);
862 return alignProteinAs(protein, alignedCodons, unmappedProtein);
866 * Realigns the given dna to match the alignment of the protein, using codon
867 * mappings to translate aligned peptide positions to codons.
869 * Always produces a padded CDS alignment.
872 * the alignment whose sequences are realigned by this method
874 * the protein alignment whose alignment we are 'copying'
875 * @return the number of sequences that were realigned
877 public static int alignCdsAsProtein(AlignmentI dna, AlignmentI protein)
879 if (protein.isNucleotide() || !dna.isNucleotide())
881 System.err.println("Wrong alignment type in alignProteinAsDna");
884 // todo: implement this
885 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
886 int alignedCount = 0;
887 int width = 0; // alignment width for padding CDS
888 for (SequenceI dnaSeq : dna.getSequences())
890 if (alignCdsSequenceAsProtein(dnaSeq, protein, mappings,
891 dna.getGapCharacter()))
895 width = Math.max(dnaSeq.getLength(), width);
898 for (SequenceI dnaSeq : dna.getSequences())
900 oldwidth = dnaSeq.getLength();
901 diff = width - oldwidth;
904 dnaSeq.insertCharAt(oldwidth, diff, dna.getGapCharacter());
911 * Helper method to align (if possible) the dna sequence to match the
912 * alignment of a mapped protein sequence. This is currently limited to
913 * handling coding sequence only.
921 static boolean alignCdsSequenceAsProtein(SequenceI cdsSeq,
922 AlignmentI protein, List<AlignedCodonFrame> mappings, char gapChar)
924 SequenceI cdsDss = cdsSeq.getDatasetSequence();
928 .println("alignCdsSequenceAsProtein needs aligned sequence!");
932 List<AlignedCodonFrame> dnaMappings = MappingUtils
933 .findMappingsForSequence(cdsSeq, mappings);
934 for (AlignedCodonFrame mapping : dnaMappings)
936 SequenceI peptide = mapping.findAlignedSequence(cdsSeq, protein);
937 int peptideLength = peptide.getLength();
940 Mapping map = mapping.getMappingBetween(cdsSeq, peptide);
943 MapList mapList = map.getMap();
944 if (map.getTo() == peptide.getDatasetSequence())
946 mapList = mapList.getInverse();
948 int cdsLength = cdsDss.getLength();
949 int mappedFromLength = MappingUtils.getLength(mapList
951 int mappedToLength = MappingUtils
952 .getLength(mapList.getToRanges());
953 boolean addStopCodon = (cdsLength == mappedFromLength * 3 + 3)
954 || (peptide.getDatasetSequence().getLength() == mappedFromLength - 1);
955 if (cdsLength != mappedToLength && !addStopCodon)
959 .format("Can't align cds as protein (length mismatch %d/%d): %s",
960 cdsLength, mappedToLength,
965 * pre-fill the aligned cds sequence with gaps
967 char[] alignedCds = new char[peptideLength * 3
968 + (addStopCodon ? 3 : 0)];
969 Arrays.fill(alignedCds, gapChar);
972 * walk over the aligned peptide sequence and insert mapped
973 * codons for residues in the aligned cds sequence
975 char[] alignedPeptide = peptide.getSequence();
976 char[] nucleotides = cdsDss.getSequence();
978 int cdsStart = cdsDss.getStart();
979 int proteinPos = peptide.getStart() - 1;
981 for (char residue : alignedPeptide)
983 if (Comparison.isGap(residue))
990 int[] codon = mapList.locateInTo(proteinPos, proteinPos);
993 // e.g. incomplete start codon, X in peptide
998 for (int j = codon[0]; j <= codon[1]; j++)
1000 char mappedBase = nucleotides[j - cdsStart];
1001 alignedCds[cdsCol++] = mappedBase;
1009 * append stop codon if not mapped from protein,
1010 * closing it up to the end of the mapped sequence
1012 if (copiedBases == nucleotides.length - 3)
1014 for (int i = alignedCds.length - 1; i >= 0; i--)
1016 if (!Comparison.isGap(alignedCds[i]))
1018 cdsCol = i + 1; // gap just after end of sequence
1022 for (int i = nucleotides.length - 3; i < nucleotides.length; i++)
1024 alignedCds[cdsCol++] = nucleotides[i];
1027 cdsSeq.setSequence(new String(alignedCds));
1036 * Builds a map whose key is an aligned codon position (3 alignment column
1037 * numbers base 0), and whose value is a map from protein sequence to each
1038 * protein's peptide residue for that codon. The map generates an ordering of
1039 * the codons, and allows us to read off the peptides at each position in
1040 * order to assemble 'aligned' protein sequences.
1043 * the protein alignment
1045 * the coding dna alignment
1046 * @param unmappedProtein
1047 * any unmapped proteins are added to this list
1050 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
1051 AlignmentI protein, AlignmentI dna,
1052 List<SequenceI> unmappedProtein)
1055 * maintain a list of any proteins with no mappings - these will be
1056 * rendered 'as is' in the protein alignment as we can't align them
1058 unmappedProtein.addAll(protein.getSequences());
1060 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1063 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
1064 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
1065 * comparator keeps the codon positions ordered.
1067 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
1068 new CodonComparator());
1070 for (SequenceI dnaSeq : dna.getSequences())
1072 for (AlignedCodonFrame mapping : mappings)
1074 SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
1077 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
1078 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
1079 seqMap, alignedCodons);
1080 unmappedProtein.remove(prot);
1086 * Finally add any unmapped peptide start residues (e.g. for incomplete
1087 * codons) as if at the codon position before the second residue
1089 // TODO resolve JAL-2022 so this fudge can be removed
1090 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
1091 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
1093 return alignedCodons;
1097 * Scans for any protein mapped from position 2 (meaning unmapped start
1098 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
1099 * preceding position in the alignment
1101 * @param alignedCodons
1102 * the codon-to-peptide map
1103 * @param mappedSequenceCount
1104 * the number of distinct sequences in the map
1106 protected static void addUnmappedPeptideStarts(
1107 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1108 int mappedSequenceCount)
1110 // TODO delete this ugly hack once JAL-2022 is resolved
1111 // i.e. we can model startPhase > 0 (incomplete start codon)
1113 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
1114 AlignedCodon lastCodon = null;
1115 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
1117 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
1120 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
1123 SequenceI seq = sequenceCodon.getKey();
1124 if (sequencesChecked.contains(seq))
1128 sequencesChecked.add(seq);
1129 AlignedCodon codon = sequenceCodon.getValue();
1130 if (codon.peptideCol > 1)
1133 .println("Problem mapping protein with >1 unmapped start positions: "
1136 else if (codon.peptideCol == 1)
1139 * first position (peptideCol == 0) was unmapped - add it
1141 if (lastCodon != null)
1143 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
1144 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
1146 toAdd.put(seq, firstPeptide);
1151 * unmapped residue at start of alignment (no prior column) -
1152 * 'insert' at nominal codon [0, 0, 0]
1154 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
1155 String.valueOf(seq.getCharAt(0)), 0);
1156 toAdd.put(seq, firstPeptide);
1159 if (sequencesChecked.size() == mappedSequenceCount)
1161 // no need to check past first mapped position in all sequences
1165 lastCodon = entry.getKey();
1169 * add any new codons safely after iterating over the map
1171 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
1173 addCodonToMap(alignedCodons, startCodon.getValue(),
1174 startCodon.getKey());
1179 * Update the aligned protein sequences to match the codon alignments given in
1183 * @param alignedCodons
1184 * an ordered map of codon positions (columns), with sequence/peptide
1185 * values present in each column
1186 * @param unmappedProtein
1189 protected static int alignProteinAs(AlignmentI protein,
1190 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1191 List<SequenceI> unmappedProtein)
1194 * Prefill aligned sequences with gaps before inserting aligned protein
1197 int alignedWidth = alignedCodons.size();
1198 char[] gaps = new char[alignedWidth];
1199 Arrays.fill(gaps, protein.getGapCharacter());
1200 String allGaps = String.valueOf(gaps);
1201 for (SequenceI seq : protein.getSequences())
1203 if (!unmappedProtein.contains(seq))
1205 seq.setSequence(allGaps);
1210 for (AlignedCodon codon : alignedCodons.keySet())
1212 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1214 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1216 // place translated codon at its column position in sequence
1217 entry.getKey().getSequence()[column] = entry.getValue().product
1226 * Populate the map of aligned codons by traversing the given sequence
1227 * mapping, locating the aligned positions of mapped codons, and adding those
1228 * positions and their translation products to the map.
1231 * the aligned sequence we are mapping from
1233 * the sequence to be aligned to the codons
1235 * the gap character in the dna sequence
1237 * a mapping to a sequence translation
1238 * @param alignedCodons
1239 * the map we are building up
1241 static void addCodonPositions(SequenceI dna, SequenceI protein,
1242 char gapChar, Mapping seqMap,
1243 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1245 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1248 * add codon positions, and their peptide translations, to the alignment
1249 * map, while remembering the first codon mapped
1251 while (codons.hasNext())
1255 AlignedCodon codon = codons.next();
1256 addCodonToMap(alignedCodons, codon, protein);
1257 } catch (IncompleteCodonException e)
1259 // possible incomplete trailing codon - ignore
1260 } catch (NoSuchElementException e)
1262 // possibly peptide lacking STOP
1268 * Helper method to add a codon-to-peptide entry to the aligned codons map
1270 * @param alignedCodons
1274 protected static void addCodonToMap(
1275 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1276 AlignedCodon codon, SequenceI protein)
1278 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1279 if (seqProduct == null)
1281 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1282 alignedCodons.put(codon, seqProduct);
1284 seqProduct.put(protein, codon);
1288 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1289 * between at least one pair of sequences in the two alignments. Currently,
1292 * <li>One alignment must be nucleotide, and the other protein</li>
1293 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1294 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1295 * <li>The translation may ignore start and stop codons if present in the
1303 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1305 if (al1 == null || al2 == null)
1311 * Require one nucleotide and one protein
1313 if (al1.isNucleotide() == al2.isNucleotide())
1317 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1318 AlignmentI protein = dna == al1 ? al2 : al1;
1319 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1320 for (SequenceI dnaSeq : dna.getSequences())
1322 for (SequenceI proteinSeq : protein.getSequences())
1324 if (isMappable(dnaSeq, proteinSeq, mappings))
1334 * Returns true if the dna sequence is mapped, or could be mapped, to the
1342 protected static boolean isMappable(SequenceI dnaSeq,
1343 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1345 if (dnaSeq == null || proteinSeq == null)
1350 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1351 .getDatasetSequence();
1352 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1353 : proteinSeq.getDatasetSequence();
1355 for (AlignedCodonFrame mapping : mappings)
1357 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1367 * Just try to make a mapping (it is not yet stored), test whether
1370 return mapCdnaToProtein(proteinDs, dnaDs) != null;
1374 * Finds any reference annotations associated with the sequences in
1375 * sequenceScope, that are not already added to the alignment, and adds them
1376 * to the 'candidates' map. Also populates a lookup table of annotation
1377 * labels, keyed by calcId, for use in constructing tooltips or the like.
1379 * @param sequenceScope
1380 * the sequences to scan for reference annotations
1381 * @param labelForCalcId
1382 * (optional) map to populate with label for calcId
1384 * map to populate with annotations for sequence
1386 * the alignment to check for presence of annotations
1388 public static void findAddableReferenceAnnotations(
1389 List<SequenceI> sequenceScope,
1390 Map<String, String> labelForCalcId,
1391 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1394 if (sequenceScope == null)
1400 * For each sequence in scope, make a list of any annotations on the
1401 * underlying dataset sequence which are not already on the alignment.
1403 * Add to a map of { alignmentSequence, <List of annotations to add> }
1405 for (SequenceI seq : sequenceScope)
1407 SequenceI dataset = seq.getDatasetSequence();
1408 if (dataset == null)
1412 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1413 if (datasetAnnotations == null)
1417 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1418 for (AlignmentAnnotation dsann : datasetAnnotations)
1421 * Find matching annotations on the alignment. If none is found, then
1422 * add this annotation to the list of 'addable' annotations for this
1425 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1426 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1427 if (!matchedAlignmentAnnotations.iterator().hasNext())
1430 if (labelForCalcId != null)
1432 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1437 * Save any addable annotations for this sequence
1439 if (!result.isEmpty())
1441 candidates.put(seq, result);
1447 * Adds annotations to the top of the alignment annotations, in the same order
1448 * as their related sequences.
1450 * @param annotations
1451 * the annotations to add
1453 * the alignment to add them to
1454 * @param selectionGroup
1455 * current selection group (or null if none)
1457 public static void addReferenceAnnotations(
1458 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1459 final AlignmentI alignment, final SequenceGroup selectionGroup)
1461 for (SequenceI seq : annotations.keySet())
1463 for (AlignmentAnnotation ann : annotations.get(seq))
1465 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1467 int endRes = ann.annotations.length;
1468 if (selectionGroup != null)
1470 startRes = selectionGroup.getStartRes();
1471 endRes = selectionGroup.getEndRes();
1473 copyAnn.restrict(startRes, endRes);
1476 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1477 * original annotation is already on the sequence.
1479 if (!seq.hasAnnotation(ann))
1481 seq.addAlignmentAnnotation(copyAnn);
1484 copyAnn.adjustForAlignment();
1485 // add to the alignment and set visible
1486 alignment.addAnnotation(copyAnn);
1487 copyAnn.visible = true;
1493 * Set visibility of alignment annotations of specified types (labels), for
1494 * specified sequences. This supports controls like
1495 * "Show all secondary structure", "Hide all Temp factor", etc.
1497 * @al the alignment to scan for annotations
1499 * the types (labels) of annotations to be updated
1500 * @param forSequences
1501 * if not null, only annotations linked to one of these sequences are
1502 * in scope for update; if null, acts on all sequence annotations
1504 * if this flag is true, 'types' is ignored (label not checked)
1506 * if true, set visibility on, else set off
1508 public static void showOrHideSequenceAnnotations(AlignmentI al,
1509 Collection<String> types, List<SequenceI> forSequences,
1510 boolean anyType, boolean doShow)
1512 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
1515 for (AlignmentAnnotation aa : anns)
1517 if (anyType || types.contains(aa.label))
1519 if ((aa.sequenceRef != null)
1520 && (forSequences == null || forSequences
1521 .contains(aa.sequenceRef)))
1523 aa.visible = doShow;
1531 * Returns true if either sequence has a cross-reference to the other
1537 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1539 // Note: moved here from class CrossRef as the latter class has dependencies
1540 // not availability to the applet's classpath
1541 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1545 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1546 * that sequence name is structured as Source|AccessionId.
1552 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1554 if (seq1 == null || seq2 == null)
1558 String name = seq2.getName();
1559 final DBRefEntry[] xrefs = seq1.getDBRefs();
1562 for (DBRefEntry xref : xrefs)
1564 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1565 // case-insensitive test, consistent with DBRefEntry.equalRef()
1566 if (xrefName.equalsIgnoreCase(name))
1576 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1577 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1578 * added to the original alignment's dataset, which is shared by the new
1579 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1580 * added to the alignment dataset.
1583 * aligned nucleotide (dna or cds) sequences
1585 * the alignment dataset the sequences belong to
1587 * (optional) to restrict results to CDS that map to specified
1589 * @return an alignment whose sequences are the cds-only parts of the dna
1590 * sequences (or null if no mappings are found)
1592 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1593 AlignmentI dataset, SequenceI[] products)
1595 if (dataset == null || dataset.getDataset() != null)
1597 throw new IllegalArgumentException(
1598 "IMPLEMENTATION ERROR: dataset.getDataset() must be null!");
1600 List<SequenceI> foundSeqs = new ArrayList<SequenceI>();
1601 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1602 List<AlignedCodonFrame> mappings = dataset.getCodonFrames();
1603 HashSet<SequenceI> productSeqs = null;
1604 if (products != null)
1606 productSeqs = new HashSet<SequenceI>();
1607 for (SequenceI seq : products)
1609 productSeqs.add(seq.getDatasetSequence() == null ? seq : seq
1610 .getDatasetSequence());
1615 * Construct CDS sequences from mappings on the alignment dataset.
1617 * - find the protein product(s) mapped to from each dna sequence
1618 * - if the mapping covers the whole dna sequence (give or take start/stop
1619 * codon), take the dna as the CDS sequence
1620 * - else search dataset mappings for a suitable dna sequence, i.e. one
1621 * whose whole sequence is mapped to the protein
1622 * - if no sequence found, construct one from the dna sequence and mapping
1623 * (and add it to dataset so it is found if this is repeated)
1625 for (SequenceI dnaSeq : dna)
1627 SequenceI dnaDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1628 : dnaSeq.getDatasetSequence();
1630 List<AlignedCodonFrame> seqMappings = MappingUtils
1631 .findMappingsForSequence(dnaSeq, mappings);
1632 for (AlignedCodonFrame mapping : seqMappings)
1634 List<Mapping> mappingsFromSequence = mapping
1635 .getMappingsFromSequence(dnaSeq);
1637 for (Mapping aMapping : mappingsFromSequence)
1639 MapList mapList = aMapping.getMap();
1640 if (mapList.getFromRatio() == 1)
1643 * not a dna-to-protein mapping (likely dna-to-cds)
1649 * skip if mapping is not to one of the target set of proteins
1651 SequenceI proteinProduct = aMapping.getTo();
1652 if (productSeqs != null && !productSeqs.contains(proteinProduct))
1658 * try to locate the CDS from the dataset mappings;
1659 * guard against duplicate results (for the case that protein has
1660 * dbrefs to both dna and cds sequences)
1662 SequenceI cdsSeq = findCdsForProtein(mappings, dnaSeq,
1663 seqMappings, aMapping);
1666 if (!foundSeqs.contains(cdsSeq))
1668 foundSeqs.add(cdsSeq);
1669 SequenceI derivedSequence = cdsSeq.deriveSequence();
1670 cdsSeqs.add(derivedSequence);
1671 if (!dataset.getSequences().contains(cdsSeq))
1673 dataset.addSequence(cdsSeq);
1680 * didn't find mapped CDS sequence - construct it and add
1681 * its dataset sequence to the dataset
1683 cdsSeq = makeCdsSequence(dnaSeq.getDatasetSequence(), aMapping);
1684 // cdsSeq has a name constructed as CDS|<dbref>
1685 // <dbref> will be either the accession for the coding sequence,
1686 // marked in the /via/ dbref to the protein product accession
1687 // or it will be the original nucleotide accession.
1688 SequenceI cdsSeqDss = cdsSeq.createDatasetSequence();
1689 cdsSeqs.add(cdsSeq);
1690 if (!dataset.getSequences().contains(cdsSeqDss))
1692 dataset.addSequence(cdsSeqDss);
1696 * add a mapping from CDS to the (unchanged) mapped to range
1698 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1699 cdsSeq.getLength() });
1700 MapList cdsToProteinMap = new MapList(cdsRange, mapList.getToRanges(),
1701 mapList.getFromRatio(), mapList.getToRatio());
1702 AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
1703 cdsToProteinMapping.addMap(cdsSeqDss, proteinProduct,
1707 * guard against duplicating the mapping if repeating this action
1709 if (!mappings.contains(cdsToProteinMapping))
1711 mappings.add(cdsToProteinMapping);
1714 propagateDBRefsToCDS(cdsSeqDss, dnaSeq.getDatasetSequence(),
1715 proteinProduct, aMapping);
1717 * add another mapping from original 'from' range to CDS
1719 AlignedCodonFrame dnaToCdsMapping = new AlignedCodonFrame();
1720 MapList dnaToCdsMap = new MapList(mapList.getFromRanges(),
1723 dnaToCdsMapping.addMap(dnaSeq.getDatasetSequence(), cdsSeqDss,
1725 if (!mappings.contains(dnaToCdsMapping))
1727 mappings.add(dnaToCdsMapping);
1731 * add DBRef with mapping from protein to CDS
1732 * (this enables Get Cross-References from protein alignment)
1733 * This is tricky because we can't have two DBRefs with the
1734 * same source and accession, so need a different accession for
1735 * the CDS from the dna sequence
1737 // specific use case:
1738 // Genomic contig ENSCHR:1, contains coding regions for ENSG01,
1739 // ENSG02, ENSG03, with transcripts and products similarly named.
1740 // cannot add distinct dbrefs mapping location on ENSCHR:1 to ENSG01
1741 // JBPNote: ?? can't actually create an example that demonstrates we
1743 // synthesize an xref.
1744 // TODO: merge conflicts from JAL-2154 branch and use PrimaryDBRefs()
1745 // for (DBRefEntry primRef:dnaDss.getPrimaryDBRefs())
1747 // creates a complementary cross-reference to the source sequence's
1748 // primary reference.
1750 // // problem here is that the cross-reference is synthesized -
1751 // cdsSeq.getName() may be like 'CDS|dnaaccession' or 'CDS|emblcdsacc'
1752 // // assuming cds version same as dna ?!?
1753 // DBRefEntry proteinToCdsRef = new DBRefEntry(dnaRef.getSource(),
1754 // dnaRef.getVersion(), cdsSeq.getName());
1755 // proteinToCdsRef.setMap(new Mapping(cdsSeqDss, cdsToProteinMap
1757 // proteinProduct.addDBRef(proteinToCdsRef);
1761 * transfer any features on dna that overlap the CDS
1763 transferFeatures(dnaSeq, cdsSeq, cdsToProteinMap, null,
1764 SequenceOntologyI.CDS);
1769 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1771 cds.setDataset(dataset);
1777 * A helper method that finds a CDS sequence in the alignment dataset that is
1778 * mapped to the given protein sequence, and either is, or has a mapping from,
1779 * the given dna sequence.
1782 * set of all mappings on the dataset
1784 * a dna (or cds) sequence we are searching from
1785 * @param seqMappings
1786 * the set of mappings involving dnaSeq
1788 * an initial candidate from seqMappings
1791 static SequenceI findCdsForProtein(List<AlignedCodonFrame> mappings,
1792 SequenceI dnaSeq, List<AlignedCodonFrame> seqMappings,
1796 * TODO a better dna-cds-protein mapping data representation to allow easy
1797 * navigation; until then this clunky looping around lists of mappings
1799 SequenceI seqDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1800 : dnaSeq.getDatasetSequence();
1801 SequenceI proteinProduct = aMapping.getTo();
1804 * is this mapping from the whole dna sequence (i.e. CDS)?
1805 * allowing for possible stop codon on dna but not peptide
1807 int mappedFromLength = MappingUtils.getLength(aMapping.getMap()
1809 int dnaLength = seqDss.getLength();
1810 if (mappedFromLength == dnaLength || mappedFromLength == dnaLength - 3)
1816 * looks like we found the dna-to-protein mapping; search for the
1817 * corresponding cds-to-protein mapping
1819 List<AlignedCodonFrame> mappingsToPeptide = MappingUtils
1820 .findMappingsForSequence(proteinProduct, mappings);
1821 for (AlignedCodonFrame acf : mappingsToPeptide)
1823 for (SequenceToSequenceMapping map : acf.getMappings())
1825 Mapping mapping = map.getMapping();
1826 if (mapping != aMapping && mapping.getMap().getFromRatio() == 3
1827 && proteinProduct == mapping.getTo()
1828 && seqDss != map.getFromSeq())
1830 mappedFromLength = MappingUtils.getLength(mapping.getMap()
1832 if (mappedFromLength == map.getFromSeq().getLength())
1835 * found a 3:1 mapping to the protein product which covers
1836 * the whole dna sequence i.e. is from CDS; finally check it
1837 * is from the dna start sequence
1839 SequenceI cdsSeq = map.getFromSeq();
1840 List<AlignedCodonFrame> dnaToCdsMaps = MappingUtils
1841 .findMappingsForSequence(cdsSeq, seqMappings);
1842 if (!dnaToCdsMaps.isEmpty())
1854 * Helper method that makes a CDS sequence as defined by the mappings from the
1855 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1856 * forward or reverse strand).
1860 * @return CDS sequence (as a dataset sequence)
1862 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1864 char[] seqChars = seq.getSequence();
1865 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1866 int cdsWidth = MappingUtils.getLength(fromRanges);
1867 char[] newSeqChars = new char[cdsWidth];
1870 for (int[] range : fromRanges)
1872 if (range[0] <= range[1])
1874 // forward strand mapping - just copy the range
1875 int length = range[1] - range[0] + 1;
1876 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1882 // reverse strand mapping - copy and complement one by one
1883 for (int i = range[0]; i >= range[1]; i--)
1885 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1891 * assign 'from id' held in the mapping if set (e.g. EMBL protein_id),
1892 * else generate a sequence name
1894 String mapFromId = mapping.getMappedFromId();
1895 String seqId = "CDS|" + (mapFromId != null ? mapFromId : seq.getName());
1896 SequenceI newSeq = new Sequence(seqId, newSeqChars, 1, newPos);
1897 // newSeq.setDescription(mapFromId);
1903 * add any DBRefEntrys to cdsSeq from contig that have a Mapping congruent to
1904 * the given mapping.
1909 * @return list of DBRefEntrys added.
1911 public static List<DBRefEntry> propagateDBRefsToCDS(SequenceI cdsSeq,
1912 SequenceI contig, SequenceI proteinProduct, Mapping mapping)
1915 // gather direct refs from contig congrent with mapping
1916 List<DBRefEntry> direct = new ArrayList<DBRefEntry>();
1917 HashSet<String> directSources = new HashSet<String>();
1918 if (contig.getDBRefs() != null)
1920 for (DBRefEntry dbr : contig.getDBRefs())
1922 if (dbr.hasMap() && dbr.getMap().getMap().isTripletMap())
1924 MapList map = dbr.getMap().getMap();
1925 // check if map is the CDS mapping
1926 if (mapping.getMap().equals(map))
1929 directSources.add(dbr.getSource());
1934 DBRefEntry[] onSource = DBRefUtils.selectRefs(
1935 proteinProduct.getDBRefs(),
1936 directSources.toArray(new String[0]));
1937 List<DBRefEntry> propagated = new ArrayList<DBRefEntry>();
1939 // and generate appropriate mappings
1940 for (DBRefEntry cdsref : direct)
1942 // clone maplist and mapping
1943 MapList cdsposmap = new MapList(Arrays.asList(new int[][] { new int[]
1944 { cdsSeq.getStart(), cdsSeq.getEnd() } }), cdsref.getMap().getMap()
1945 .getToRanges(), 3, 1);
1946 Mapping cdsmap = new Mapping(cdsref.getMap().getTo(), cdsref.getMap()
1950 DBRefEntry newref = new DBRefEntry(cdsref.getSource(),
1951 cdsref.getVersion(), cdsref.getAccessionId(), new Mapping(
1952 cdsmap.getTo(), cdsposmap));
1954 // and see if we can map to the protein product for this mapping.
1955 // onSource is the filtered set of accessions on protein that we are
1956 // tranferring, so we assume accession is the same.
1957 if (cdsmap.getTo() == null && onSource != null)
1959 List<DBRefEntry> sourceRefs = DBRefUtils.searchRefs(onSource,
1960 cdsref.getAccessionId());
1961 if (sourceRefs != null)
1963 for (DBRefEntry srcref : sourceRefs)
1965 if (srcref.getSource().equalsIgnoreCase(cdsref.getSource()))
1967 // we have found a complementary dbref on the protein product, so
1968 // update mapping's getTo
1969 newref.getMap().setTo(proteinProduct);
1974 cdsSeq.addDBRef(newref);
1975 propagated.add(newref);
1981 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1982 * feature start/end ranges, optionally omitting specified feature types.
1983 * Returns the number of features copied.
1988 * if not null, only features of this type are copied (including
1989 * subtypes in the Sequence Ontology)
1991 * the mapping from 'fromSeq' to 'toSeq'
1994 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1995 MapList mapping, String select, String... omitting)
1997 SequenceI copyTo = toSeq;
1998 while (copyTo.getDatasetSequence() != null)
2000 copyTo = copyTo.getDatasetSequence();
2003 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2005 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
2008 for (SequenceFeature sf : sfs)
2010 String type = sf.getType();
2011 if (select != null && !so.isA(type, select))
2015 boolean omit = false;
2016 for (String toOmit : omitting)
2018 if (type.equals(toOmit))
2029 * locate the mapped range - null if either start or end is
2030 * not mapped (no partial overlaps are calculated)
2032 int start = sf.getBegin();
2033 int end = sf.getEnd();
2034 int[] mappedTo = mapping.locateInTo(start, end);
2036 * if whole exon range doesn't map, try interpreting it
2037 * as 5' or 3' exon overlapping the CDS range
2039 if (mappedTo == null)
2041 mappedTo = mapping.locateInTo(end, end);
2042 if (mappedTo != null)
2045 * end of exon is in CDS range - 5' overlap
2046 * to a range from the start of the peptide
2051 if (mappedTo == null)
2053 mappedTo = mapping.locateInTo(start, start);
2054 if (mappedTo != null)
2057 * start of exon is in CDS range - 3' overlap
2058 * to a range up to the end of the peptide
2060 mappedTo[1] = toSeq.getLength();
2063 if (mappedTo != null)
2065 SequenceFeature copy = new SequenceFeature(sf);
2066 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
2067 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
2068 copyTo.addSequenceFeature(copy);
2077 * Returns a mapping from dna to protein by inspecting sequence features of
2078 * type "CDS" on the dna.
2084 public static MapList mapCdsToProtein(SequenceI dnaSeq,
2085 SequenceI proteinSeq)
2087 List<int[]> ranges = findCdsPositions(dnaSeq);
2088 int mappedDnaLength = MappingUtils.getLength(ranges);
2090 int proteinLength = proteinSeq.getLength();
2091 int proteinStart = proteinSeq.getStart();
2092 int proteinEnd = proteinSeq.getEnd();
2095 * incomplete start codon may mean X at start of peptide
2096 * we ignore both for mapping purposes
2098 if (proteinSeq.getCharAt(0) == 'X')
2100 // todo JAL-2022 support startPhase > 0
2104 List<int[]> proteinRange = new ArrayList<int[]>();
2107 * dna length should map to protein (or protein plus stop codon)
2109 int codesForResidues = mappedDnaLength / 3;
2110 if (codesForResidues == (proteinLength + 1))
2112 // assuming extra codon is for STOP and not in peptide
2115 if (codesForResidues == proteinLength)
2117 proteinRange.add(new int[] { proteinStart, proteinEnd });
2118 return new MapList(ranges, proteinRange, 3, 1);
2124 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
2125 * start/end positions of sequence features of type "CDS" (or a sub-type of
2126 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
2127 * position order, so this method is only valid for linear CDS in the same
2128 * sense as the protein product.
2133 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
2135 List<int[]> result = new ArrayList<int[]>();
2136 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
2142 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2145 for (SequenceFeature sf : sfs)
2148 * process a CDS feature (or a sub-type of CDS)
2150 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
2155 phase = Integer.parseInt(sf.getPhase());
2156 } catch (NumberFormatException e)
2161 * phase > 0 on first codon means 5' incomplete - skip to the start
2162 * of the next codon; example ENST00000496384
2164 int begin = sf.getBegin();
2165 int end = sf.getEnd();
2166 if (result.isEmpty())
2171 // shouldn't happen!
2173 .println("Error: start phase extends beyond start CDS in "
2174 + dnaSeq.getName());
2177 result.add(new int[] { begin, end });
2182 * remove 'startPhase' positions (usually 0) from the first range
2183 * so we begin at the start of a complete codon
2185 if (!result.isEmpty())
2187 // TODO JAL-2022 correctly model start phase > 0
2188 result.get(0)[0] += startPhase;
2192 * Finally sort ranges by start position. This avoids a dependency on
2193 * keeping features in order on the sequence (if they are in order anyway,
2194 * the sort will have almost no work to do). The implicit assumption is CDS
2195 * ranges are assembled in order. Other cases should not use this method,
2196 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
2198 Collections.sort(result, new Comparator<int[]>()
2201 public int compare(int[] o1, int[] o2)
2203 return Integer.compare(o1[0], o2[0]);
2210 * Maps exon features from dna to protein, and computes variants in peptide
2211 * product generated by variants in dna, and adds them as sequence_variant
2212 * features on the protein sequence. Returns the number of variant features
2217 * @param dnaToProtein
2219 public static int computeProteinFeatures(SequenceI dnaSeq,
2220 SequenceI peptide, MapList dnaToProtein)
2222 while (dnaSeq.getDatasetSequence() != null)
2224 dnaSeq = dnaSeq.getDatasetSequence();
2226 while (peptide.getDatasetSequence() != null)
2228 peptide = peptide.getDatasetSequence();
2231 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
2234 * compute protein variants from dna variants and codon mappings;
2235 * NB - alternatively we could retrieve this using the REST service e.g.
2236 * http://rest.ensembl.org/overlap/translation
2237 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
2238 * which would be a bit slower but possibly more reliable
2242 * build a map with codon variations for each potentially varying peptide
2244 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
2245 dnaSeq, dnaToProtein);
2248 * scan codon variations, compute peptide variants and add to peptide sequence
2251 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
2253 int peptidePos = variant.getKey();
2254 List<DnaVariant>[] codonVariants = variant.getValue();
2255 count += computePeptideVariants(peptide, peptidePos, codonVariants);
2259 * sort to get sequence features in start position order
2260 * - would be better to store in Sequence as a TreeSet or NCList?
2262 if (peptide.getSequenceFeatures() != null)
2264 Arrays.sort(peptide.getSequenceFeatures(),
2265 new Comparator<SequenceFeature>()
2268 public int compare(SequenceFeature o1, SequenceFeature o2)
2270 int c = Integer.compare(o1.getBegin(), o2.getBegin());
2271 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
2280 * Computes non-synonymous peptide variants from codon variants and adds them
2281 * as sequence_variant features on the protein sequence (one feature per
2282 * allele variant). Selected attributes (variant id, clinical significance)
2283 * are copied over to the new features.
2286 * the protein sequence
2288 * the position to compute peptide variants for
2289 * @param codonVariants
2290 * a list of dna variants per codon position
2291 * @return the number of features added
2293 static int computePeptideVariants(SequenceI peptide, int peptidePos,
2294 List<DnaVariant>[] codonVariants)
2296 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
2298 String base1 = codonVariants[0].get(0).base;
2299 String base2 = codonVariants[1].get(0).base;
2300 String base3 = codonVariants[2].get(0).base;
2303 * variants in first codon base
2305 for (DnaVariant var : codonVariants[0])
2307 if (var.variant != null)
2309 String alleles = (String) var.variant.getValue("alleles");
2310 if (alleles != null)
2312 for (String base : alleles.split(","))
2314 String codon = base + base2 + base3;
2315 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2325 * variants in second codon base
2327 for (DnaVariant var : codonVariants[1])
2329 if (var.variant != null)
2331 String alleles = (String) var.variant.getValue("alleles");
2332 if (alleles != null)
2334 for (String base : alleles.split(","))
2336 String codon = base1 + base + base3;
2337 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2347 * variants in third codon base
2349 for (DnaVariant var : codonVariants[2])
2351 if (var.variant != null)
2353 String alleles = (String) var.variant.getValue("alleles");
2354 if (alleles != null)
2356 for (String base : alleles.split(","))
2358 String codon = base1 + base2 + base;
2359 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2372 * Helper method that adds a peptide variant feature, provided the given codon
2373 * translates to a value different to the current residue (is a non-synonymous
2374 * variant). ID and clinical_significance attributes of the dna variant (if
2375 * present) are copied to the new feature.
2382 * @return true if a feature was added, else false
2384 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
2385 String residue, DnaVariant var, String codon)
2388 * get peptide translation of codon e.g. GAT -> D
2389 * note that variants which are not single alleles,
2390 * e.g. multibase variants or HGMD_MUTATION etc
2391 * are currently ignored here
2393 String trans = codon.contains("-") ? "-"
2394 : (codon.length() > 3 ? null : ResidueProperties
2395 .codonTranslate(codon));
2396 if (trans != null && !trans.equals(residue))
2398 String residue3Char = StringUtils
2399 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
2400 String trans3Char = StringUtils
2401 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
2402 String desc = "p." + residue3Char + peptidePos + trans3Char;
2403 // set score to 0f so 'graduated colour' option is offered! JAL-2060
2404 SequenceFeature sf = new SequenceFeature(
2405 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
2406 peptidePos, 0f, "Jalview");
2407 StringBuilder attributes = new StringBuilder(32);
2408 String id = (String) var.variant.getValue(ID);
2411 if (id.startsWith(SEQUENCE_VARIANT))
2413 id = id.substring(SEQUENCE_VARIANT.length());
2415 sf.setValue(ID, id);
2416 attributes.append(ID).append("=").append(id);
2417 // TODO handle other species variants
2418 StringBuilder link = new StringBuilder(32);
2421 link.append(desc).append(" ").append(id)
2422 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
2423 .append(URLEncoder.encode(id, "UTF-8"));
2424 sf.addLink(link.toString());
2425 } catch (UnsupportedEncodingException e)
2430 String clinSig = (String) var.variant
2431 .getValue(CLINICAL_SIGNIFICANCE);
2432 if (clinSig != null)
2434 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
2435 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
2438 peptide.addSequenceFeature(sf);
2439 if (attributes.length() > 0)
2441 sf.setAttributes(attributes.toString());
2449 * Builds a map whose key is position in the protein sequence, and value is a
2450 * list of the base and all variants for each corresponding codon position
2453 * @param dnaToProtein
2456 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
2457 SequenceI dnaSeq, MapList dnaToProtein)
2460 * map from peptide position to all variants of the codon which codes for it
2461 * LinkedHashMap ensures we keep the peptide features in sequence order
2463 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2464 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2466 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2467 if (dnaFeatures == null)
2472 int dnaStart = dnaSeq.getStart();
2473 int[] lastCodon = null;
2474 int lastPeptidePostion = 0;
2477 * build a map of codon variations for peptides
2479 for (SequenceFeature sf : dnaFeatures)
2481 int dnaCol = sf.getBegin();
2482 if (dnaCol != sf.getEnd())
2484 // not handling multi-locus variant features
2487 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2489 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2492 // feature doesn't lie within coding region
2495 int peptidePosition = mapsTo[0];
2496 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2497 if (codonVariants == null)
2499 codonVariants = new ArrayList[3];
2500 codonVariants[0] = new ArrayList<DnaVariant>();
2501 codonVariants[1] = new ArrayList<DnaVariant>();
2502 codonVariants[2] = new ArrayList<DnaVariant>();
2503 variants.put(peptidePosition, codonVariants);
2507 * extract dna variants to a string array
2509 String alls = (String) sf.getValue("alleles");
2514 String[] alleles = alls.toUpperCase().split(",");
2516 for (String allele : alleles)
2518 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2522 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2524 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2525 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2526 peptidePosition, peptidePosition));
2527 lastPeptidePostion = peptidePosition;
2531 * save nucleotide (and any variant) for each codon position
2533 for (int codonPos = 0; codonPos < 3; codonPos++)
2535 String nucleotide = String.valueOf(
2536 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2538 List<DnaVariant> codonVariant = codonVariants[codonPos];
2539 if (codon[codonPos] == dnaCol)
2541 if (!codonVariant.isEmpty()
2542 && codonVariant.get(0).variant == null)
2545 * already recorded base value, add this variant
2547 codonVariant.get(0).variant = sf;
2552 * add variant with base value
2554 codonVariant.add(new DnaVariant(nucleotide, sf));
2557 else if (codonVariant.isEmpty())
2560 * record (possibly non-varying) base value
2562 codonVariant.add(new DnaVariant(nucleotide));
2571 * Makes an alignment with a copy of the given sequences, adding in any
2572 * non-redundant sequences which are mapped to by the cross-referenced
2578 * the alignment dataset shared by the new copy
2581 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2582 SequenceI[] xrefs, AlignmentI dataset)
2584 AlignmentI copy = new Alignment(new Alignment(seqs));
2585 copy.setDataset(dataset);
2587 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2590 for (SequenceI xref : xrefs)
2592 DBRefEntry[] dbrefs = xref.getDBRefs();
2595 for (DBRefEntry dbref : dbrefs)
2597 if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2601 SequenceI mappedTo = dbref.getMap().getTo();
2602 SequenceI match = matcher.findIdMatch(mappedTo);
2605 matcher.add(mappedTo);
2606 copy.addSequence(mappedTo);
2616 * Try to align sequences in 'unaligned' to match the alignment of their
2617 * mapped regions in 'aligned'. For example, could use this to align CDS
2618 * sequences which are mapped to their parent cDNA sequences.
2620 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2621 * dna-to-protein or protein-to-dna use alternative methods.
2624 * sequences to be aligned
2626 * holds aligned sequences and their mappings
2629 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2632 * easy case - aligning a copy of aligned sequences
2634 if (alignAsSameSequences(unaligned, aligned))
2636 return unaligned.getHeight();
2640 * fancy case - aligning via mappings between sequences
2642 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2643 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2644 unaligned, aligned, unmapped);
2645 int width = columnMap.size();
2646 char gap = unaligned.getGapCharacter();
2647 int realignedCount = 0;
2648 // TODO: verify this loop scales sensibly for very wide/high alignments
2650 for (SequenceI seq : unaligned.getSequences())
2652 if (!unmapped.contains(seq))
2654 char[] newSeq = new char[width];
2655 Arrays.fill(newSeq, gap); // JBPComment - doubt this is faster than the
2656 // Integer iteration below
2661 * traverse the map to find columns populated
2664 for (Integer column : columnMap.keySet())
2666 Character c = columnMap.get(column).get(seq);
2670 * sequence has a character at this position
2680 * trim trailing gaps
2682 if (lastCol < width)
2684 char[] tmp = new char[lastCol + 1];
2685 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2688 // TODO: optimise SequenceI to avoid char[]->String->char[]
2689 seq.setSequence(String.valueOf(newSeq));
2693 return realignedCount;
2697 * If unaligned and aligned sequences share the same dataset sequences, then
2698 * simply copies the aligned sequences to the unaligned sequences and returns
2699 * true; else returns false
2702 * - sequences to be aligned based on aligned
2704 * - 'guide' alignment containing sequences derived from same dataset
2708 static boolean alignAsSameSequences(AlignmentI unaligned,
2711 if (aligned.getDataset() == null || unaligned.getDataset() == null)
2713 return false; // should only pass alignments with datasets here
2716 // map from dataset sequence to alignment sequence(s)
2717 Map<SequenceI, List<SequenceI>> alignedDatasets = new HashMap<SequenceI, List<SequenceI>>();
2718 for (SequenceI seq : aligned.getSequences())
2720 SequenceI ds = seq.getDatasetSequence();
2721 if (alignedDatasets.get(ds) == null)
2723 alignedDatasets.put(ds, new ArrayList<SequenceI>());
2725 alignedDatasets.get(ds).add(seq);
2729 * first pass - check whether all sequences to be aligned share a dataset
2730 * sequence with an aligned sequence
2732 for (SequenceI seq : unaligned.getSequences())
2734 if (!alignedDatasets.containsKey(seq.getDatasetSequence()))
2741 * second pass - copy aligned sequences;
2742 * heuristic rule: pair off sequences in order for the case where
2743 * more than one shares the same dataset sequence
2745 for (SequenceI seq : unaligned.getSequences())
2747 List<SequenceI> alignedSequences = alignedDatasets.get(seq
2748 .getDatasetSequence());
2749 // TODO: getSequenceAsString() will be deprecated in the future
2750 // TODO: need to leave to SequenceI implementor to update gaps
2751 seq.setSequence(alignedSequences.get(0).getSequenceAsString());
2752 if (alignedSequences.size() > 0)
2754 // pop off aligned sequences (except the last one)
2755 alignedSequences.remove(0);
2763 * Returns a map whose key is alignment column number (base 1), and whose
2764 * values are a map of sequence characters in that column.
2771 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2772 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2775 * Map will hold, for each aligned column position, a map of
2776 * {unalignedSequence, characterPerSequence} at that position.
2777 * TreeMap keeps the entries in ascending column order.
2779 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2782 * record any sequences that have no mapping so can't be realigned
2784 unmapped.addAll(unaligned.getSequences());
2786 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2788 for (SequenceI seq : unaligned.getSequences())
2790 for (AlignedCodonFrame mapping : mappings)
2792 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2793 if (fromSeq != null)
2795 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2796 if (addMappedPositions(seq, fromSeq, seqMap, map))
2798 unmapped.remove(seq);
2807 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2808 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2809 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2813 * the sequence whose column positions we are recording
2815 * a sequence that is mapped to the first sequence
2817 * the mapping from 'fromSeq' to 'seq'
2819 * a map to add the column positions (in fromSeq) of the mapped
2823 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2824 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2832 * invert mapping if it is from unaligned to aligned sequence
2834 if (seqMap.getTo() == fromSeq.getDatasetSequence())
2836 seqMap = new Mapping(seq.getDatasetSequence(), seqMap.getMap()
2840 char[] fromChars = fromSeq.getSequence();
2841 int toStart = seq.getStart();
2842 char[] toChars = seq.getSequence();
2845 * traverse [start, end, start, end...] ranges in fromSeq
2847 for (int[] fromRange : seqMap.getMap().getFromRanges())
2849 for (int i = 0; i < fromRange.length - 1; i += 2)
2851 boolean forward = fromRange[i + 1] >= fromRange[i];
2854 * find the range mapped to (sequence positions base 1)
2856 int[] range = seqMap.locateMappedRange(fromRange[i],
2860 System.err.println("Error in mapping " + seqMap + " from "
2861 + fromSeq.getName());
2864 int fromCol = fromSeq.findIndex(fromRange[i]);
2865 int mappedCharPos = range[0];
2868 * walk over the 'from' aligned sequence in forward or reverse
2869 * direction; when a non-gap is found, record the column position
2870 * of the next character of the mapped-to sequence; stop when all
2871 * the characters of the range have been counted
2873 while (mappedCharPos <= range[1] && fromCol <= fromChars.length
2876 if (!Comparison.isGap(fromChars[fromCol - 1]))
2879 * mapped from sequence has a character in this column
2880 * record the column position for the mapped to character
2882 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2883 if (seqsMap == null)
2885 seqsMap = new HashMap<SequenceI, Character>();
2886 map.put(fromCol, seqsMap);
2888 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2891 fromCol += (forward ? 1 : -1);
2898 // strictly temporary hack until proper criteria for aligning protein to cds
2899 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2900 public static boolean looksLikeEnsembl(AlignmentI alignment)
2902 for (SequenceI seq : alignment.getSequences())
2904 String name = seq.getName();
2905 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))