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 int CODON_LENGTH = 3;
77 private static final String SEQUENCE_VARIANT = "sequence_variant:";
79 private static final String ID = "ID";
82 * A data model to hold the 'normal' base value at a position, and an optional
83 * sequence variant feature
85 static final class DnaVariant
89 SequenceFeature variant;
91 DnaVariant(String nuc)
97 DnaVariant(String nuc, SequenceFeature var)
103 public String getSource()
105 return variant == null ? null : variant.getFeatureGroup();
110 * given an existing alignment, create a new alignment including all, or up to
111 * flankSize additional symbols from each sequence's dataset sequence
117 public static AlignmentI expandContext(AlignmentI core, int flankSize)
119 List<SequenceI> sq = new ArrayList<SequenceI>();
121 for (SequenceI s : core.getSequences())
123 SequenceI newSeq = s.deriveSequence();
124 final int newSeqStart = newSeq.getStart() - 1;
125 if (newSeqStart > maxoffset
126 && newSeq.getDatasetSequence().getStart() < s.getStart())
128 maxoffset = newSeqStart;
134 maxoffset = Math.min(maxoffset, flankSize);
138 * now add offset left and right to create an expanded alignment
140 for (SequenceI s : sq)
143 while (ds.getDatasetSequence() != null)
145 ds = ds.getDatasetSequence();
147 int s_end = s.findPosition(s.getStart() + s.getLength());
148 // find available flanking residues for sequence
149 int ustream_ds = s.getStart() - ds.getStart();
150 int dstream_ds = ds.getEnd() - s_end;
152 // build new flanked sequence
154 // compute gap padding to start of flanking sequence
155 int offset = maxoffset - ustream_ds;
157 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
160 if (flankSize < ustream_ds)
162 // take up to flankSize residues
163 offset = maxoffset - flankSize;
164 ustream_ds = flankSize;
166 if (flankSize <= dstream_ds)
168 dstream_ds = flankSize - 1;
171 // TODO use Character.toLowerCase to avoid creating String objects?
172 char[] upstream = new String(ds.getSequence(s.getStart() - 1
173 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
174 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
175 + dstream_ds)).toLowerCase().toCharArray();
176 char[] coreseq = s.getSequence();
177 char[] nseq = new char[offset + upstream.length + downstream.length
179 char c = core.getGapCharacter();
182 for (; p < offset; p++)
187 System.arraycopy(upstream, 0, nseq, p, upstream.length);
188 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
190 System.arraycopy(downstream, 0, nseq, p + coreseq.length
191 + upstream.length, downstream.length);
192 s.setSequence(new String(nseq));
193 s.setStart(s.getStart() - ustream_ds);
194 s.setEnd(s_end + downstream.length);
196 AlignmentI newAl = new jalview.datamodel.Alignment(
197 sq.toArray(new SequenceI[0]));
198 for (SequenceI s : sq)
200 if (s.getAnnotation() != null)
202 for (AlignmentAnnotation aa : s.getAnnotation())
204 aa.adjustForAlignment(); // JAL-1712 fix
205 newAl.addAnnotation(aa);
209 newAl.setDataset(core.getDataset());
214 * Returns the index (zero-based position) of a sequence in an alignment, or
221 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
225 for (SequenceI alSeq : al.getSequences())
238 * Returns a map of lists of sequences in the alignment, keyed by sequence
239 * name. For use in mapping between different alignment views of the same
242 * @see jalview.datamodel.AlignmentI#getSequencesByName()
244 public static Map<String, List<SequenceI>> getSequencesByName(
247 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
248 for (SequenceI seq : al.getSequences())
250 String name = seq.getName();
253 List<SequenceI> seqs = theMap.get(name);
256 seqs = new ArrayList<SequenceI>();
257 theMap.put(name, seqs);
266 * Build mapping of protein to cDNA alignment. Mappings are made between
267 * sequences where the cDNA translates to the protein sequence. Any new
268 * mappings are added to the protein alignment. Returns true if any mappings
269 * either already exist or were added, else false.
271 * @param proteinAlignment
272 * @param cdnaAlignment
275 public static boolean mapProteinAlignmentToCdna(
276 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
278 if (proteinAlignment == null || cdnaAlignment == null)
283 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
284 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
287 * First pass - map sequences where cross-references exist. This include
288 * 1-to-many mappings to support, for example, variant cDNA.
290 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
291 cdnaAlignment, mappedDna, mappedProtein, true);
294 * Second pass - map sequences where no cross-references exist. This only
295 * does 1-to-1 mappings and assumes corresponding sequences are in the same
296 * order in the alignments.
298 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
299 mappedDna, mappedProtein, false);
300 return mappingPerformed;
304 * Make mappings between compatible sequences (where the cDNA translation
305 * matches the protein).
307 * @param proteinAlignment
308 * @param cdnaAlignment
310 * a set of mapped DNA sequences (to add to)
311 * @param mappedProtein
312 * a set of mapped Protein sequences (to add to)
314 * if true, only map sequences where xrefs exist
317 protected static boolean mapProteinToCdna(
318 final AlignmentI proteinAlignment,
319 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
320 Set<SequenceI> mappedProtein, boolean xrefsOnly)
322 boolean mappingExistsOrAdded = false;
323 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
324 for (SequenceI aaSeq : thisSeqs)
326 boolean proteinMapped = false;
327 AlignedCodonFrame acf = new AlignedCodonFrame();
329 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
332 * Always try to map if sequences have xref to each other; this supports
333 * variant cDNA or alternative splicing for a protein sequence.
335 * If no xrefs, try to map progressively, assuming that alignments have
336 * mappable sequences in corresponding order. These are not
337 * many-to-many, as that would risk mixing species with similar cDNA
340 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
346 * Don't map non-xrefd sequences more than once each. This heuristic
347 * allows us to pair up similar sequences in ordered alignments.
350 && (mappedProtein.contains(aaSeq) || mappedDna
355 if (mappingExists(proteinAlignment.getCodonFrames(),
356 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
358 mappingExistsOrAdded = true;
362 MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
365 acf.addMap(cdnaSeq, aaSeq, map);
366 mappingExistsOrAdded = true;
367 proteinMapped = true;
368 mappedDna.add(cdnaSeq);
369 mappedProtein.add(aaSeq);
375 proteinAlignment.addCodonFrame(acf);
378 return mappingExistsOrAdded;
382 * Answers true if the mappings include one between the given (dataset)
385 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
386 SequenceI aaSeq, SequenceI cdnaSeq)
388 if (mappings != null)
390 for (AlignedCodonFrame acf : mappings)
392 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
402 * Builds a mapping (if possible) of a cDNA to a protein sequence.
404 * <li>first checks if the cdna translates exactly to the protein sequence</li>
405 * <li>else checks for translation after removing a STOP codon</li>
406 * <li>else checks for translation after removing a START codon</li>
407 * <li>if that fails, inspect CDS features on the cDNA sequence</li>
409 * Returns null if no mapping is determined.
412 * the aligned protein sequence
414 * the aligned cdna sequence
417 public static MapList mapCdnaToProtein(SequenceI proteinSeq,
421 * Here we handle either dataset sequence set (desktop) or absent (applet).
422 * Use only the char[] form of the sequence to avoid creating possibly large
425 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
426 char[] aaSeqChars = proteinDataset != null ? proteinDataset
427 .getSequence() : proteinSeq.getSequence();
428 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
429 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
430 : cdnaSeq.getSequence();
431 if (aaSeqChars == null || cdnaSeqChars == null)
437 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
439 final int mappedLength = CODON_LENGTH * aaSeqChars.length;
440 int cdnaLength = cdnaSeqChars.length;
441 int cdnaStart = cdnaSeq.getStart();
442 int cdnaEnd = cdnaSeq.getEnd();
443 final int proteinStart = proteinSeq.getStart();
444 final int proteinEnd = proteinSeq.getEnd();
447 * If lengths don't match, try ignoring stop codon (if present)
449 if (cdnaLength != mappedLength && cdnaLength > 2)
451 String lastCodon = String.valueOf(cdnaSeqChars,
452 cdnaLength - CODON_LENGTH, CODON_LENGTH).toUpperCase();
453 for (String stop : ResidueProperties.STOP)
455 if (lastCodon.equals(stop))
457 cdnaEnd -= CODON_LENGTH;
458 cdnaLength -= CODON_LENGTH;
465 * If lengths still don't match, try ignoring start codon.
468 if (cdnaLength != mappedLength
470 && String.valueOf(cdnaSeqChars, 0, CODON_LENGTH).toUpperCase()
471 .equals(ResidueProperties.START))
473 startOffset += CODON_LENGTH;
474 cdnaStart += CODON_LENGTH;
475 cdnaLength -= CODON_LENGTH;
478 if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
481 * protein is translation of dna (+/- start/stop codons)
483 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
484 { proteinStart, proteinEnd }, CODON_LENGTH, 1);
489 * translation failed - try mapping CDS annotated regions of dna
491 return mapCdsToProtein(cdnaSeq, proteinSeq);
495 * Test whether the given cdna sequence, starting at the given offset,
496 * translates to the given amino acid sequence, using the standard translation
497 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
499 * @param cdnaSeqChars
504 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
507 if (cdnaSeqChars == null || aaSeqChars == null)
513 int dnaPos = cdnaStart;
514 for (; dnaPos < cdnaSeqChars.length - 2 && aaPos < aaSeqChars.length; dnaPos += CODON_LENGTH, aaPos++)
516 String codon = String.valueOf(cdnaSeqChars, dnaPos, CODON_LENGTH);
517 final String translated = ResidueProperties.codonTranslate(codon);
520 * allow * in protein to match untranslatable in dna
522 final char aaRes = aaSeqChars[aaPos];
523 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
527 if (translated == null || !(aaRes == translated.charAt(0)))
530 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
531 // + codon + "(" + translated + ") != " + aaRes));
537 * check we matched all of the protein sequence
539 if (aaPos != aaSeqChars.length)
545 * check we matched all of the dna except
546 * for optional trailing STOP codon
548 if (dnaPos == cdnaSeqChars.length)
552 if (dnaPos == cdnaSeqChars.length - CODON_LENGTH)
554 String codon = String.valueOf(cdnaSeqChars, dnaPos, CODON_LENGTH);
555 if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
564 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
565 * currently assumes that we are aligning cDNA to match protein.
568 * the sequence to be realigned
570 * the alignment whose sequence alignment is to be 'copied'
572 * character string represent a gap in the realigned sequence
573 * @param preserveUnmappedGaps
574 * @param preserveMappedGaps
575 * @return true if the sequence was realigned, false if it could not be
577 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
578 String gap, boolean preserveMappedGaps,
579 boolean preserveUnmappedGaps)
582 * Get any mappings from the source alignment to the target (dataset)
585 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
586 // all mappings. Would it help to constrain this?
587 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
588 if (mappings == null || mappings.isEmpty())
594 * Locate the aligned source sequence whose dataset sequence is mapped. We
595 * just take the first match here (as we can't align like more than one
598 SequenceI alignFrom = null;
599 AlignedCodonFrame mapping = null;
600 for (AlignedCodonFrame mp : mappings)
602 alignFrom = mp.findAlignedSequence(seq, al);
603 if (alignFrom != null)
610 if (alignFrom == null)
614 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
615 preserveMappedGaps, preserveUnmappedGaps);
620 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
621 * match residues and codons. Flags control whether existing gaps in unmapped
622 * (intron) and mapped (exon) regions are preserved or not. Gaps between
623 * intron and exon are only retained if both flags are set.
630 * @param preserveUnmappedGaps
631 * @param preserveMappedGaps
633 public static void alignSequenceAs(SequenceI alignTo,
634 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
635 char sourceGap, boolean preserveMappedGaps,
636 boolean preserveUnmappedGaps)
638 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
640 // aligned and dataset sequence positions, all base zero
644 int basesWritten = 0;
645 char myGapChar = myGap.charAt(0);
646 int ratio = myGap.length();
648 int fromOffset = alignFrom.getStart() - 1;
649 int toOffset = alignTo.getStart() - 1;
650 int sourceGapMappedLength = 0;
651 boolean inExon = false;
652 final char[] thisSeq = alignTo.getSequence();
653 final char[] thatAligned = alignFrom.getSequence();
654 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
657 * Traverse the 'model' aligned sequence
659 for (char sourceChar : thatAligned)
661 if (sourceChar == sourceGap)
663 sourceGapMappedLength += ratio;
668 * Found a non-gap character. Locate its mapped region if any.
671 // Note mapping positions are base 1, our sequence positions base 0
672 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
673 sourceDsPos + fromOffset);
674 if (mappedPos == null)
677 * unmapped position; treat like a gap
679 sourceGapMappedLength += ratio;
680 // System.err.println("Can't align: no codon mapping to residue "
681 // + sourceDsPos + "(" + sourceChar + ")");
686 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
687 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
688 StringBuilder trailingCopiedGap = new StringBuilder();
691 * Copy dna sequence up to and including this codon. Optionally, include
692 * gaps before the codon starts (in introns) and/or after the codon starts
695 * Note this only works for 'linear' splicing, not reverse or interleaved.
696 * But then 'align dna as protein' doesn't make much sense otherwise.
698 int intronLength = 0;
699 while (basesWritten + toOffset < mappedCodonEnd
700 && thisSeqPos < thisSeq.length)
702 final char c = thisSeq[thisSeqPos++];
706 int sourcePosition = basesWritten + toOffset;
707 if (sourcePosition < mappedCodonStart)
710 * Found an unmapped (intron) base. First add in any preceding gaps
713 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
715 thisAligned.append(trailingCopiedGap.toString());
716 intronLength += trailingCopiedGap.length();
717 trailingCopiedGap = new StringBuilder();
724 final boolean startOfCodon = sourcePosition == mappedCodonStart;
725 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
726 preserveUnmappedGaps, sourceGapMappedLength, inExon,
727 trailingCopiedGap.length(), intronLength, startOfCodon);
728 for (int i = 0; i < gapsToAdd; i++)
730 thisAligned.append(myGapChar);
732 sourceGapMappedLength = 0;
735 thisAligned.append(c);
736 trailingCopiedGap = new StringBuilder();
740 if (inExon && preserveMappedGaps)
742 trailingCopiedGap.append(myGapChar);
744 else if (!inExon && preserveUnmappedGaps)
746 trailingCopiedGap.append(myGapChar);
753 * At end of model aligned sequence. Copy any remaining target sequence, optionally
754 * including (intron) gaps.
756 while (thisSeqPos < thisSeq.length)
758 final char c = thisSeq[thisSeqPos++];
759 if (c != myGapChar || preserveUnmappedGaps)
761 thisAligned.append(c);
763 sourceGapMappedLength--;
767 * finally add gaps to pad for any trailing source gaps or
768 * unmapped characters
770 if (preserveUnmappedGaps)
772 while (sourceGapMappedLength > 0)
774 thisAligned.append(myGapChar);
775 sourceGapMappedLength--;
780 * All done aligning, set the aligned sequence.
782 alignTo.setSequence(new String(thisAligned));
786 * Helper method to work out how many gaps to insert when realigning.
788 * @param preserveMappedGaps
789 * @param preserveUnmappedGaps
790 * @param sourceGapMappedLength
792 * @param trailingCopiedGap
793 * @param intronLength
794 * @param startOfCodon
797 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
798 boolean preserveUnmappedGaps, int sourceGapMappedLength,
799 boolean inExon, int trailingGapLength, int intronLength,
800 final boolean startOfCodon)
806 * Reached start of codon. Ignore trailing gaps in intron unless we are
807 * preserving gaps in both exon and intron. Ignore them anyway if the
808 * protein alignment introduces a gap at least as large as the intronic
811 if (inExon && !preserveMappedGaps)
813 trailingGapLength = 0;
815 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
817 trailingGapLength = 0;
821 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
825 if (intronLength + trailingGapLength <= sourceGapMappedLength)
827 gapsToAdd = sourceGapMappedLength - intronLength;
831 gapsToAdd = Math.min(intronLength + trailingGapLength
832 - sourceGapMappedLength, trailingGapLength);
839 * second or third base of codon; check for any gaps in dna
841 if (!preserveMappedGaps)
843 trailingGapLength = 0;
845 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
851 * Realigns the given protein to match the alignment of the dna, using codon
852 * mappings to translate aligned codon positions to protein residues.
855 * the alignment whose sequences are realigned by this method
857 * the dna alignment whose alignment we are 'copying'
858 * @return the number of sequences that were realigned
860 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
862 if (protein.isNucleotide() || !dna.isNucleotide())
864 System.err.println("Wrong alignment type in alignProteinAsDna");
867 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
868 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
869 protein, dna, unmappedProtein);
870 return alignProteinAs(protein, alignedCodons, unmappedProtein);
874 * Realigns the given dna to match the alignment of the protein, using codon
875 * mappings to translate aligned peptide positions to codons.
877 * Always produces a padded CDS alignment.
880 * the alignment whose sequences are realigned by this method
882 * the protein alignment whose alignment we are 'copying'
883 * @return the number of sequences that were realigned
885 public static int alignCdsAsProtein(AlignmentI dna, AlignmentI protein)
887 if (protein.isNucleotide() || !dna.isNucleotide())
889 System.err.println("Wrong alignment type in alignProteinAsDna");
892 // todo: implement this
893 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
894 int alignedCount = 0;
895 int width = 0; // alignment width for padding CDS
896 for (SequenceI dnaSeq : dna.getSequences())
898 if (alignCdsSequenceAsProtein(dnaSeq, protein, mappings,
899 dna.getGapCharacter()))
903 width = Math.max(dnaSeq.getLength(), width);
907 for (SequenceI dnaSeq : dna.getSequences())
909 oldwidth = dnaSeq.getLength();
910 diff = width - oldwidth;
913 dnaSeq.insertCharAt(oldwidth, diff, dna.getGapCharacter());
920 * Helper method to align (if possible) the dna sequence to match the
921 * alignment of a mapped protein sequence. This is currently limited to
922 * handling coding sequence only.
930 static boolean alignCdsSequenceAsProtein(SequenceI cdsSeq,
931 AlignmentI protein, List<AlignedCodonFrame> mappings, char gapChar)
933 SequenceI cdsDss = cdsSeq.getDatasetSequence();
937 .println("alignCdsSequenceAsProtein needs aligned sequence!");
941 List<AlignedCodonFrame> dnaMappings = MappingUtils
942 .findMappingsForSequence(cdsSeq, mappings);
943 for (AlignedCodonFrame mapping : dnaMappings)
945 SequenceI peptide = mapping.findAlignedSequence(cdsSeq, protein);
948 int peptideLength = peptide.getLength();
949 Mapping map = mapping.getMappingBetween(cdsSeq, peptide);
952 MapList mapList = map.getMap();
953 if (map.getTo() == peptide.getDatasetSequence())
955 mapList = mapList.getInverse();
957 int cdsLength = cdsDss.getLength();
958 int mappedFromLength = MappingUtils.getLength(mapList
960 int mappedToLength = MappingUtils
961 .getLength(mapList.getToRanges());
962 boolean addStopCodon = (cdsLength == mappedFromLength
963 * CODON_LENGTH + CODON_LENGTH)
964 || (peptide.getDatasetSequence().getLength() == mappedFromLength - 1);
965 if (cdsLength != mappedToLength && !addStopCodon)
969 .format("Can't align cds as protein (length mismatch %d/%d): %s",
970 cdsLength, mappedToLength,
975 * pre-fill the aligned cds sequence with gaps
977 char[] alignedCds = new char[peptideLength * CODON_LENGTH
978 + (addStopCodon ? CODON_LENGTH : 0)];
979 Arrays.fill(alignedCds, gapChar);
982 * walk over the aligned peptide sequence and insert mapped
983 * codons for residues in the aligned cds sequence
985 char[] alignedPeptide = peptide.getSequence();
986 char[] nucleotides = cdsDss.getSequence();
988 int cdsStart = cdsDss.getStart();
989 int proteinPos = peptide.getStart() - 1;
991 for (char residue : alignedPeptide)
993 if (Comparison.isGap(residue))
995 cdsCol += CODON_LENGTH;
1000 int[] codon = mapList.locateInTo(proteinPos, proteinPos);
1003 // e.g. incomplete start codon, X in peptide
1004 cdsCol += CODON_LENGTH;
1008 for (int j = codon[0]; j <= codon[1]; j++)
1010 char mappedBase = nucleotides[j - cdsStart];
1011 alignedCds[cdsCol++] = mappedBase;
1019 * append stop codon if not mapped from protein,
1020 * closing it up to the end of the mapped sequence
1022 if (copiedBases == nucleotides.length - CODON_LENGTH)
1024 for (int i = alignedCds.length - 1; i >= 0; i--)
1026 if (!Comparison.isGap(alignedCds[i]))
1028 cdsCol = i + 1; // gap just after end of sequence
1032 for (int i = nucleotides.length - CODON_LENGTH; i < nucleotides.length; i++)
1034 alignedCds[cdsCol++] = nucleotides[i];
1037 cdsSeq.setSequence(new String(alignedCds));
1046 * Builds a map whose key is an aligned codon position (3 alignment column
1047 * numbers base 0), and whose value is a map from protein sequence to each
1048 * protein's peptide residue for that codon. The map generates an ordering of
1049 * the codons, and allows us to read off the peptides at each position in
1050 * order to assemble 'aligned' protein sequences.
1053 * the protein alignment
1055 * the coding dna alignment
1056 * @param unmappedProtein
1057 * any unmapped proteins are added to this list
1060 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
1061 AlignmentI protein, AlignmentI dna,
1062 List<SequenceI> unmappedProtein)
1065 * maintain a list of any proteins with no mappings - these will be
1066 * rendered 'as is' in the protein alignment as we can't align them
1068 unmappedProtein.addAll(protein.getSequences());
1070 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1073 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
1074 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
1075 * comparator keeps the codon positions ordered.
1077 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
1078 new CodonComparator());
1080 for (SequenceI dnaSeq : dna.getSequences())
1082 for (AlignedCodonFrame mapping : mappings)
1084 SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
1087 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
1088 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
1089 seqMap, alignedCodons);
1090 unmappedProtein.remove(prot);
1096 * Finally add any unmapped peptide start residues (e.g. for incomplete
1097 * codons) as if at the codon position before the second residue
1099 // TODO resolve JAL-2022 so this fudge can be removed
1100 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
1101 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
1103 return alignedCodons;
1107 * Scans for any protein mapped from position 2 (meaning unmapped start
1108 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
1109 * preceding position in the alignment
1111 * @param alignedCodons
1112 * the codon-to-peptide map
1113 * @param mappedSequenceCount
1114 * the number of distinct sequences in the map
1116 protected static void addUnmappedPeptideStarts(
1117 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1118 int mappedSequenceCount)
1120 // TODO delete this ugly hack once JAL-2022 is resolved
1121 // i.e. we can model startPhase > 0 (incomplete start codon)
1123 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
1124 AlignedCodon lastCodon = null;
1125 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
1127 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
1130 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
1133 SequenceI seq = sequenceCodon.getKey();
1134 if (sequencesChecked.contains(seq))
1138 sequencesChecked.add(seq);
1139 AlignedCodon codon = sequenceCodon.getValue();
1140 if (codon.peptideCol > 1)
1143 .println("Problem mapping protein with >1 unmapped start positions: "
1146 else if (codon.peptideCol == 1)
1149 * first position (peptideCol == 0) was unmapped - add it
1151 if (lastCodon != null)
1153 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
1154 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
1156 toAdd.put(seq, firstPeptide);
1161 * unmapped residue at start of alignment (no prior column) -
1162 * 'insert' at nominal codon [0, 0, 0]
1164 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
1165 String.valueOf(seq.getCharAt(0)), 0);
1166 toAdd.put(seq, firstPeptide);
1169 if (sequencesChecked.size() == mappedSequenceCount)
1171 // no need to check past first mapped position in all sequences
1175 lastCodon = entry.getKey();
1179 * add any new codons safely after iterating over the map
1181 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
1183 addCodonToMap(alignedCodons, startCodon.getValue(),
1184 startCodon.getKey());
1189 * Update the aligned protein sequences to match the codon alignments given in
1193 * @param alignedCodons
1194 * an ordered map of codon positions (columns), with sequence/peptide
1195 * values present in each column
1196 * @param unmappedProtein
1199 protected static int alignProteinAs(AlignmentI protein,
1200 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1201 List<SequenceI> unmappedProtein)
1204 * Prefill aligned sequences with gaps before inserting aligned protein
1207 int alignedWidth = alignedCodons.size();
1208 char[] gaps = new char[alignedWidth];
1209 Arrays.fill(gaps, protein.getGapCharacter());
1210 String allGaps = String.valueOf(gaps);
1211 for (SequenceI seq : protein.getSequences())
1213 if (!unmappedProtein.contains(seq))
1215 seq.setSequence(allGaps);
1220 for (AlignedCodon codon : alignedCodons.keySet())
1222 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1224 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1226 // place translated codon at its column position in sequence
1227 entry.getKey().getSequence()[column] = entry.getValue().product
1236 * Populate the map of aligned codons by traversing the given sequence
1237 * mapping, locating the aligned positions of mapped codons, and adding those
1238 * positions and their translation products to the map.
1241 * the aligned sequence we are mapping from
1243 * the sequence to be aligned to the codons
1245 * the gap character in the dna sequence
1247 * a mapping to a sequence translation
1248 * @param alignedCodons
1249 * the map we are building up
1251 static void addCodonPositions(SequenceI dna, SequenceI protein,
1252 char gapChar, Mapping seqMap,
1253 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1255 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1258 * add codon positions, and their peptide translations, to the alignment
1259 * map, while remembering the first codon mapped
1261 while (codons.hasNext())
1265 AlignedCodon codon = codons.next();
1266 addCodonToMap(alignedCodons, codon, protein);
1267 } catch (IncompleteCodonException e)
1269 // possible incomplete trailing codon - ignore
1270 } catch (NoSuchElementException e)
1272 // possibly peptide lacking STOP
1278 * Helper method to add a codon-to-peptide entry to the aligned codons map
1280 * @param alignedCodons
1284 protected static void addCodonToMap(
1285 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1286 AlignedCodon codon, SequenceI protein)
1288 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1289 if (seqProduct == null)
1291 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1292 alignedCodons.put(codon, seqProduct);
1294 seqProduct.put(protein, codon);
1298 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1299 * between at least one pair of sequences in the two alignments. Currently,
1302 * <li>One alignment must be nucleotide, and the other protein</li>
1303 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1304 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1305 * <li>The translation may ignore start and stop codons if present in the
1313 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1315 if (al1 == null || al2 == null)
1321 * Require one nucleotide and one protein
1323 if (al1.isNucleotide() == al2.isNucleotide())
1327 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1328 AlignmentI protein = dna == al1 ? al2 : al1;
1329 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1330 for (SequenceI dnaSeq : dna.getSequences())
1332 for (SequenceI proteinSeq : protein.getSequences())
1334 if (isMappable(dnaSeq, proteinSeq, mappings))
1344 * Returns true if the dna sequence is mapped, or could be mapped, to the
1352 protected static boolean isMappable(SequenceI dnaSeq,
1353 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1355 if (dnaSeq == null || proteinSeq == null)
1360 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1361 .getDatasetSequence();
1362 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1363 : proteinSeq.getDatasetSequence();
1365 for (AlignedCodonFrame mapping : mappings)
1367 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1377 * Just try to make a mapping (it is not yet stored), test whether
1380 return mapCdnaToProtein(proteinDs, dnaDs) != null;
1384 * Finds any reference annotations associated with the sequences in
1385 * sequenceScope, that are not already added to the alignment, and adds them
1386 * to the 'candidates' map. Also populates a lookup table of annotation
1387 * labels, keyed by calcId, for use in constructing tooltips or the like.
1389 * @param sequenceScope
1390 * the sequences to scan for reference annotations
1391 * @param labelForCalcId
1392 * (optional) map to populate with label for calcId
1394 * map to populate with annotations for sequence
1396 * the alignment to check for presence of annotations
1398 public static void findAddableReferenceAnnotations(
1399 List<SequenceI> sequenceScope,
1400 Map<String, String> labelForCalcId,
1401 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1404 if (sequenceScope == null)
1410 * For each sequence in scope, make a list of any annotations on the
1411 * underlying dataset sequence which are not already on the alignment.
1413 * Add to a map of { alignmentSequence, <List of annotations to add> }
1415 for (SequenceI seq : sequenceScope)
1417 SequenceI dataset = seq.getDatasetSequence();
1418 if (dataset == null)
1422 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1423 if (datasetAnnotations == null)
1427 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1428 for (AlignmentAnnotation dsann : datasetAnnotations)
1431 * Find matching annotations on the alignment. If none is found, then
1432 * add this annotation to the list of 'addable' annotations for this
1435 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1436 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1437 if (!matchedAlignmentAnnotations.iterator().hasNext())
1440 if (labelForCalcId != null)
1442 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1447 * Save any addable annotations for this sequence
1449 if (!result.isEmpty())
1451 candidates.put(seq, result);
1457 * Adds annotations to the top of the alignment annotations, in the same order
1458 * as their related sequences.
1460 * @param annotations
1461 * the annotations to add
1463 * the alignment to add them to
1464 * @param selectionGroup
1465 * current selection group (or null if none)
1467 public static void addReferenceAnnotations(
1468 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1469 final AlignmentI alignment, final SequenceGroup selectionGroup)
1471 for (SequenceI seq : annotations.keySet())
1473 for (AlignmentAnnotation ann : annotations.get(seq))
1475 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1477 int endRes = ann.annotations.length;
1478 if (selectionGroup != null)
1480 startRes = selectionGroup.getStartRes();
1481 endRes = selectionGroup.getEndRes();
1483 copyAnn.restrict(startRes, endRes);
1486 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1487 * original annotation is already on the sequence.
1489 if (!seq.hasAnnotation(ann))
1491 seq.addAlignmentAnnotation(copyAnn);
1494 copyAnn.adjustForAlignment();
1495 // add to the alignment and set visible
1496 alignment.addAnnotation(copyAnn);
1497 copyAnn.visible = true;
1503 * Set visibility of alignment annotations of specified types (labels), for
1504 * specified sequences. This supports controls like
1505 * "Show all secondary structure", "Hide all Temp factor", etc.
1507 * @al the alignment to scan for annotations
1509 * the types (labels) of annotations to be updated
1510 * @param forSequences
1511 * if not null, only annotations linked to one of these sequences are
1512 * in scope for update; if null, acts on all sequence annotations
1514 * if this flag is true, 'types' is ignored (label not checked)
1516 * if true, set visibility on, else set off
1518 public static void showOrHideSequenceAnnotations(AlignmentI al,
1519 Collection<String> types, List<SequenceI> forSequences,
1520 boolean anyType, boolean doShow)
1522 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
1525 for (AlignmentAnnotation aa : anns)
1527 if (anyType || types.contains(aa.label))
1529 if ((aa.sequenceRef != null)
1530 && (forSequences == null || forSequences
1531 .contains(aa.sequenceRef)))
1533 aa.visible = doShow;
1541 * Returns true if either sequence has a cross-reference to the other
1547 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1549 // Note: moved here from class CrossRef as the latter class has dependencies
1550 // not availability to the applet's classpath
1551 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1555 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1556 * that sequence name is structured as Source|AccessionId.
1562 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1564 if (seq1 == null || seq2 == null)
1568 String name = seq2.getName();
1569 final DBRefEntry[] xrefs = seq1.getDBRefs();
1572 for (DBRefEntry xref : xrefs)
1574 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1575 // case-insensitive test, consistent with DBRefEntry.equalRef()
1576 if (xrefName.equalsIgnoreCase(name))
1586 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1587 * nucleotide sequences, and updates mappings to match. The CDS sequences are
1588 * added to the original alignment's dataset, which is shared by the new
1589 * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1590 * added to the alignment dataset.
1593 * aligned nucleotide (dna or cds) sequences
1595 * the alignment dataset the sequences belong to
1597 * (optional) to restrict results to CDS that map to specified
1599 * @return an alignment whose sequences are the cds-only parts of the dna
1600 * sequences (or null if no mappings are found)
1602 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1603 AlignmentI dataset, SequenceI[] products)
1605 if (dataset == null || dataset.getDataset() != null)
1607 throw new IllegalArgumentException(
1608 "IMPLEMENTATION ERROR: dataset.getDataset() must be null!");
1610 List<SequenceI> foundSeqs = new ArrayList<SequenceI>();
1611 List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1612 List<AlignedCodonFrame> mappings = dataset.getCodonFrames();
1613 HashSet<SequenceI> productSeqs = null;
1614 if (products != null)
1616 productSeqs = new HashSet<SequenceI>();
1617 for (SequenceI seq : products)
1619 productSeqs.add(seq.getDatasetSequence() == null ? seq : seq
1620 .getDatasetSequence());
1625 * Construct CDS sequences from mappings on the alignment dataset.
1627 * - find the protein product(s) mapped to from each dna sequence
1628 * - if the mapping covers the whole dna sequence (give or take start/stop
1629 * codon), take the dna as the CDS sequence
1630 * - else search dataset mappings for a suitable dna sequence, i.e. one
1631 * whose whole sequence is mapped to the protein
1632 * - if no sequence found, construct one from the dna sequence and mapping
1633 * (and add it to dataset so it is found if this is repeated)
1635 for (SequenceI dnaSeq : dna)
1637 SequenceI dnaDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1638 : dnaSeq.getDatasetSequence();
1640 List<AlignedCodonFrame> seqMappings = MappingUtils
1641 .findMappingsForSequence(dnaSeq, mappings);
1642 for (AlignedCodonFrame mapping : seqMappings)
1644 List<Mapping> mappingsFromSequence = mapping
1645 .getMappingsFromSequence(dnaSeq);
1647 for (Mapping aMapping : mappingsFromSequence)
1649 MapList mapList = aMapping.getMap();
1650 if (mapList.getFromRatio() == 1)
1653 * not a dna-to-protein mapping (likely dna-to-cds)
1659 * skip if mapping is not to one of the target set of proteins
1661 SequenceI proteinProduct = aMapping.getTo();
1662 if (productSeqs != null && !productSeqs.contains(proteinProduct))
1668 * try to locate the CDS from the dataset mappings;
1669 * guard against duplicate results (for the case that protein has
1670 * dbrefs to both dna and cds sequences)
1672 SequenceI cdsSeq = findCdsForProtein(mappings, dnaSeq,
1673 seqMappings, aMapping);
1676 if (!foundSeqs.contains(cdsSeq))
1678 foundSeqs.add(cdsSeq);
1679 SequenceI derivedSequence = cdsSeq.deriveSequence();
1680 cdsSeqs.add(derivedSequence);
1681 if (!dataset.getSequences().contains(cdsSeq))
1683 dataset.addSequence(cdsSeq);
1690 * didn't find mapped CDS sequence - construct it and add
1691 * its dataset sequence to the dataset
1693 cdsSeq = makeCdsSequence(dnaSeq.getDatasetSequence(), aMapping,
1694 dataset).deriveSequence();
1695 // cdsSeq has a name constructed as CDS|<dbref>
1696 // <dbref> will be either the accession for the coding sequence,
1697 // marked in the /via/ dbref to the protein product accession
1698 // or it will be the original nucleotide accession.
1699 SequenceI cdsSeqDss = cdsSeq.getDatasetSequence();
1701 cdsSeqs.add(cdsSeq);
1703 if (!dataset.getSequences().contains(cdsSeqDss))
1705 // check if this sequence is a newly created one
1706 // so needs adding to the dataset
1707 dataset.addSequence(cdsSeqDss);
1711 * add a mapping from CDS to the (unchanged) mapped to range
1713 List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1714 cdsSeq.getLength() });
1715 MapList cdsToProteinMap = new MapList(cdsRange,
1716 mapList.getToRanges(), mapList.getFromRatio(),
1717 mapList.getToRatio());
1718 AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
1719 cdsToProteinMapping.addMap(cdsSeqDss, proteinProduct,
1723 * guard against duplicating the mapping if repeating this action
1725 if (!mappings.contains(cdsToProteinMapping))
1727 mappings.add(cdsToProteinMapping);
1730 propagateDBRefsToCDS(cdsSeqDss, dnaSeq.getDatasetSequence(),
1731 proteinProduct, aMapping);
1733 * add another mapping from original 'from' range to CDS
1735 AlignedCodonFrame dnaToCdsMapping = new AlignedCodonFrame();
1736 MapList dnaToCdsMap = new MapList(mapList.getFromRanges(),
1738 dnaToCdsMapping.addMap(dnaSeq.getDatasetSequence(), cdsSeqDss,
1740 if (!mappings.contains(dnaToCdsMapping))
1742 mappings.add(dnaToCdsMapping);
1746 * add DBRef with mapping from protein to CDS
1747 * (this enables Get Cross-References from protein alignment)
1748 * This is tricky because we can't have two DBRefs with the
1749 * same source and accession, so need a different accession for
1750 * the CDS from the dna sequence
1753 // specific use case:
1754 // Genomic contig ENSCHR:1, contains coding regions for ENSG01,
1755 // ENSG02, ENSG03, with transcripts and products similarly named.
1756 // cannot add distinct dbrefs mapping location on ENSCHR:1 to ENSG01
1758 // JBPNote: ?? can't actually create an example that demonstrates we
1760 // synthesize an xref.
1762 for (DBRefEntry primRef : dnaDss.getPrimaryDBRefs())
1764 // creates a complementary cross-reference to the source sequence's
1765 // primary reference.
1767 DBRefEntry cdsCrossRef = new DBRefEntry(primRef.getSource(),
1768 primRef.getSource() + ":" + primRef.getVersion(),
1769 primRef.getAccessionId());
1771 .setMap(new Mapping(dnaDss, new MapList(dnaToCdsMap)));
1772 cdsSeqDss.addDBRef(cdsCrossRef);
1774 // problem here is that the cross-reference is synthesized -
1775 // cdsSeq.getName() may be like 'CDS|dnaaccession' or
1777 // assuming cds version same as dna ?!?
1779 DBRefEntry proteinToCdsRef = new DBRefEntry(
1780 primRef.getSource(), primRef.getVersion(),
1783 proteinToCdsRef.setMap(new Mapping(cdsSeqDss, cdsToProteinMap
1785 proteinProduct.addDBRef(proteinToCdsRef);
1789 * transfer any features on dna that overlap the CDS
1791 transferFeatures(dnaSeq, cdsSeq, dnaToCdsMap, null,
1792 SequenceOntologyI.CDS);
1797 AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1799 cds.setDataset(dataset);
1805 * A helper method that finds a CDS sequence in the alignment dataset that is
1806 * mapped to the given protein sequence, and either is, or has a mapping from,
1807 * the given dna sequence.
1810 * set of all mappings on the dataset
1812 * a dna (or cds) sequence we are searching from
1813 * @param seqMappings
1814 * the set of mappings involving dnaSeq
1816 * an initial candidate from seqMappings
1819 static SequenceI findCdsForProtein(List<AlignedCodonFrame> mappings,
1820 SequenceI dnaSeq, List<AlignedCodonFrame> seqMappings,
1824 * TODO a better dna-cds-protein mapping data representation to allow easy
1825 * navigation; until then this clunky looping around lists of mappings
1827 SequenceI seqDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1828 : dnaSeq.getDatasetSequence();
1829 SequenceI proteinProduct = aMapping.getTo();
1832 * is this mapping from the whole dna sequence (i.e. CDS)?
1833 * allowing for possible stop codon on dna but not peptide
1835 int mappedFromLength = MappingUtils.getLength(aMapping.getMap()
1837 int dnaLength = seqDss.getLength();
1838 if (mappedFromLength == dnaLength
1839 || mappedFromLength == dnaLength - CODON_LENGTH)
1845 * looks like we found the dna-to-protein mapping; search for the
1846 * corresponding cds-to-protein mapping
1848 List<AlignedCodonFrame> mappingsToPeptide = MappingUtils
1849 .findMappingsForSequence(proteinProduct, mappings);
1850 for (AlignedCodonFrame acf : mappingsToPeptide)
1852 for (SequenceToSequenceMapping map : acf.getMappings())
1854 Mapping mapping = map.getMapping();
1855 if (mapping != aMapping
1856 && mapping.getMap().getFromRatio() == CODON_LENGTH
1857 && proteinProduct == mapping.getTo()
1858 && seqDss != map.getFromSeq())
1860 mappedFromLength = MappingUtils.getLength(mapping.getMap()
1862 if (mappedFromLength == map.getFromSeq().getLength())
1865 * found a 3:1 mapping to the protein product which covers
1866 * the whole dna sequence i.e. is from CDS; finally check it
1867 * is from the dna start sequence
1869 SequenceI cdsSeq = map.getFromSeq();
1870 List<AlignedCodonFrame> dnaToCdsMaps = MappingUtils
1871 .findMappingsForSequence(cdsSeq, seqMappings);
1872 if (!dnaToCdsMaps.isEmpty())
1884 * Helper method that makes a CDS sequence as defined by the mappings from the
1885 * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1886 * forward or reverse strand).
1891 * - existing dataset. We check for sequences that look like the CDS
1892 * we are about to construct, if one exists already, then we will
1893 * just return that one.
1894 * @return CDS sequence (as a dataset sequence)
1896 static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping,
1899 char[] seqChars = seq.getSequence();
1900 List<int[]> fromRanges = mapping.getMap().getFromRanges();
1901 int cdsWidth = MappingUtils.getLength(fromRanges);
1902 char[] newSeqChars = new char[cdsWidth];
1905 for (int[] range : fromRanges)
1907 if (range[0] <= range[1])
1909 // forward strand mapping - just copy the range
1910 int length = range[1] - range[0] + 1;
1911 System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1917 // reverse strand mapping - copy and complement one by one
1918 for (int i = range[0]; i >= range[1]; i--)
1920 newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1926 * assign 'from id' held in the mapping if set (e.g. EMBL protein_id),
1927 * else generate a sequence name
1929 String mapFromId = mapping.getMappedFromId();
1930 String seqId = "CDS|" + (mapFromId != null ? mapFromId : seq.getName());
1931 SequenceI newSeq = new Sequence(seqId, newSeqChars, 1, newPos);
1932 if (dataset != null)
1934 SequenceI[] matches = dataset.findSequenceMatch(newSeq.getName());
1935 if (matches != null)
1937 boolean matched = false;
1938 for (SequenceI mtch : matches)
1940 if (mtch.getStart() != newSeq.getStart())
1944 if (mtch.getEnd() != newSeq.getEnd())
1948 if (!Arrays.equals(mtch.getSequence(), newSeq.getSequence()))
1960 .println("JAL-2154 regression: warning - found (and ignnored a duplicate CDS sequence):"
1966 // newSeq.setDescription(mapFromId);
1972 * add any DBRefEntrys to cdsSeq from contig that have a Mapping congruent to
1973 * the given mapping.
1978 * @return list of DBRefEntrys added.
1980 public static List<DBRefEntry> propagateDBRefsToCDS(SequenceI cdsSeq,
1981 SequenceI contig, SequenceI proteinProduct, Mapping mapping)
1984 // gather direct refs from contig congrent with mapping
1985 List<DBRefEntry> direct = new ArrayList<DBRefEntry>();
1986 HashSet<String> directSources = new HashSet<String>();
1987 if (contig.getDBRefs() != null)
1989 for (DBRefEntry dbr : contig.getDBRefs())
1991 if (dbr.hasMap() && dbr.getMap().getMap().isTripletMap())
1993 MapList map = dbr.getMap().getMap();
1994 // check if map is the CDS mapping
1995 if (mapping.getMap().equals(map))
1998 directSources.add(dbr.getSource());
2003 DBRefEntry[] onSource = DBRefUtils.selectRefs(
2004 proteinProduct.getDBRefs(),
2005 directSources.toArray(new String[0]));
2006 List<DBRefEntry> propagated = new ArrayList<DBRefEntry>();
2008 // and generate appropriate mappings
2009 for (DBRefEntry cdsref : direct)
2011 // clone maplist and mapping
2012 MapList cdsposmap = new MapList(Arrays.asList(new int[][] { new int[]
2013 { cdsSeq.getStart(), cdsSeq.getEnd() } }), cdsref.getMap().getMap()
2014 .getToRanges(), 3, 1);
2015 Mapping cdsmap = new Mapping(cdsref.getMap().getTo(), cdsref.getMap()
2019 DBRefEntry newref = new DBRefEntry(cdsref.getSource(),
2020 cdsref.getVersion(), cdsref.getAccessionId(), new Mapping(
2021 cdsmap.getTo(), cdsposmap));
2023 // and see if we can map to the protein product for this mapping.
2024 // onSource is the filtered set of accessions on protein that we are
2025 // tranferring, so we assume accession is the same.
2026 if (cdsmap.getTo() == null && onSource != null)
2028 List<DBRefEntry> sourceRefs = DBRefUtils.searchRefs(onSource,
2029 cdsref.getAccessionId());
2030 if (sourceRefs != null)
2032 for (DBRefEntry srcref : sourceRefs)
2034 if (srcref.getSource().equalsIgnoreCase(cdsref.getSource()))
2036 // we have found a complementary dbref on the protein product, so
2037 // update mapping's getTo
2038 newref.getMap().setTo(proteinProduct);
2043 cdsSeq.addDBRef(newref);
2044 propagated.add(newref);
2050 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
2051 * feature start/end ranges, optionally omitting specified feature types.
2052 * Returns the number of features copied.
2057 * if not null, only features of this type are copied (including
2058 * subtypes in the Sequence Ontology)
2060 * the mapping from 'fromSeq' to 'toSeq'
2063 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
2064 MapList mapping, String select, String... omitting)
2066 SequenceI copyTo = toSeq;
2067 while (copyTo.getDatasetSequence() != null)
2069 copyTo = copyTo.getDatasetSequence();
2072 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2074 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
2077 for (SequenceFeature sf : sfs)
2079 String type = sf.getType();
2080 if (select != null && !so.isA(type, select))
2084 boolean omit = false;
2085 for (String toOmit : omitting)
2087 if (type.equals(toOmit))
2098 * locate the mapped range - null if either start or end is
2099 * not mapped (no partial overlaps are calculated)
2101 int start = sf.getBegin();
2102 int end = sf.getEnd();
2103 int[] mappedTo = mapping.locateInTo(start, end);
2105 * if whole exon range doesn't map, try interpreting it
2106 * as 5' or 3' exon overlapping the CDS range
2108 if (mappedTo == null)
2110 mappedTo = mapping.locateInTo(end, end);
2111 if (mappedTo != null)
2114 * end of exon is in CDS range - 5' overlap
2115 * to a range from the start of the peptide
2120 if (mappedTo == null)
2122 mappedTo = mapping.locateInTo(start, start);
2123 if (mappedTo != null)
2126 * start of exon is in CDS range - 3' overlap
2127 * to a range up to the end of the peptide
2129 mappedTo[1] = toSeq.getLength();
2132 if (mappedTo != null)
2134 SequenceFeature copy = new SequenceFeature(sf);
2135 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
2136 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
2137 copyTo.addSequenceFeature(copy);
2146 * Returns a mapping from dna to protein by inspecting sequence features of
2147 * type "CDS" on the dna.
2153 public static MapList mapCdsToProtein(SequenceI dnaSeq,
2154 SequenceI proteinSeq)
2156 List<int[]> ranges = findCdsPositions(dnaSeq);
2157 int mappedDnaLength = MappingUtils.getLength(ranges);
2159 int proteinLength = proteinSeq.getLength();
2160 int proteinStart = proteinSeq.getStart();
2161 int proteinEnd = proteinSeq.getEnd();
2164 * incomplete start codon may mean X at start of peptide
2165 * we ignore both for mapping purposes
2167 if (proteinSeq.getCharAt(0) == 'X')
2169 // todo JAL-2022 support startPhase > 0
2173 List<int[]> proteinRange = new ArrayList<int[]>();
2176 * dna length should map to protein (or protein plus stop codon)
2178 int codesForResidues = mappedDnaLength / CODON_LENGTH;
2179 if (codesForResidues == (proteinLength + 1))
2181 // assuming extra codon is for STOP and not in peptide
2184 if (codesForResidues == proteinLength)
2186 proteinRange.add(new int[] { proteinStart, proteinEnd });
2187 return new MapList(ranges, proteinRange, CODON_LENGTH, 1);
2193 * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
2194 * start/end positions of sequence features of type "CDS" (or a sub-type of
2195 * CDS in the Sequence Ontology). The ranges are sorted into ascending start
2196 * position order, so this method is only valid for linear CDS in the same
2197 * sense as the protein product.
2202 public static List<int[]> findCdsPositions(SequenceI dnaSeq)
2204 List<int[]> result = new ArrayList<int[]>();
2205 SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
2211 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2214 for (SequenceFeature sf : sfs)
2217 * process a CDS feature (or a sub-type of CDS)
2219 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
2224 phase = Integer.parseInt(sf.getPhase());
2225 } catch (NumberFormatException e)
2230 * phase > 0 on first codon means 5' incomplete - skip to the start
2231 * of the next codon; example ENST00000496384
2233 int begin = sf.getBegin();
2234 int end = sf.getEnd();
2235 if (result.isEmpty())
2240 // shouldn't happen!
2242 .println("Error: start phase extends beyond start CDS in "
2243 + dnaSeq.getName());
2246 result.add(new int[] { begin, end });
2251 * remove 'startPhase' positions (usually 0) from the first range
2252 * so we begin at the start of a complete codon
2254 if (!result.isEmpty())
2256 // TODO JAL-2022 correctly model start phase > 0
2257 result.get(0)[0] += startPhase;
2261 * Finally sort ranges by start position. This avoids a dependency on
2262 * keeping features in order on the sequence (if they are in order anyway,
2263 * the sort will have almost no work to do). The implicit assumption is CDS
2264 * ranges are assembled in order. Other cases should not use this method,
2265 * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
2267 Collections.sort(result, new Comparator<int[]>()
2270 public int compare(int[] o1, int[] o2)
2272 return Integer.compare(o1[0], o2[0]);
2279 * Maps exon features from dna to protein, and computes variants in peptide
2280 * product generated by variants in dna, and adds them as sequence_variant
2281 * features on the protein sequence. Returns the number of variant features
2286 * @param dnaToProtein
2288 public static int computeProteinFeatures(SequenceI dnaSeq,
2289 SequenceI peptide, MapList dnaToProtein)
2291 while (dnaSeq.getDatasetSequence() != null)
2293 dnaSeq = dnaSeq.getDatasetSequence();
2295 while (peptide.getDatasetSequence() != null)
2297 peptide = peptide.getDatasetSequence();
2300 transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
2303 * compute protein variants from dna variants and codon mappings;
2304 * NB - alternatively we could retrieve this using the REST service e.g.
2305 * http://rest.ensembl.org/overlap/translation
2306 * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
2307 * which would be a bit slower but possibly more reliable
2311 * build a map with codon variations for each potentially varying peptide
2313 LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
2314 dnaSeq, dnaToProtein);
2317 * scan codon variations, compute peptide variants and add to peptide sequence
2320 for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
2322 int peptidePos = variant.getKey();
2323 List<DnaVariant>[] codonVariants = variant.getValue();
2324 count += computePeptideVariants(peptide, peptidePos, codonVariants);
2328 * sort to get sequence features in start position order
2329 * - would be better to store in Sequence as a TreeSet or NCList?
2331 if (peptide.getSequenceFeatures() != null)
2333 Arrays.sort(peptide.getSequenceFeatures(),
2334 new Comparator<SequenceFeature>()
2337 public int compare(SequenceFeature o1, SequenceFeature o2)
2339 int c = Integer.compare(o1.getBegin(), o2.getBegin());
2340 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
2349 * Computes non-synonymous peptide variants from codon variants and adds them
2350 * as sequence_variant features on the protein sequence (one feature per
2351 * allele variant). Selected attributes (variant id, clinical significance)
2352 * are copied over to the new features.
2355 * the protein sequence
2357 * the position to compute peptide variants for
2358 * @param codonVariants
2359 * a list of dna variants per codon position
2360 * @return the number of features added
2362 static int computePeptideVariants(SequenceI peptide, int peptidePos,
2363 List<DnaVariant>[] codonVariants)
2365 String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
2367 String base1 = codonVariants[0].get(0).base;
2368 String base2 = codonVariants[1].get(0).base;
2369 String base3 = codonVariants[2].get(0).base;
2372 * variants in first codon base
2374 for (DnaVariant var : codonVariants[0])
2376 if (var.variant != null)
2378 String alleles = (String) var.variant.getValue("alleles");
2379 if (alleles != null)
2381 for (String base : alleles.split(","))
2383 String codon = base + base2 + base3;
2384 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2394 * variants in second codon base
2396 for (DnaVariant var : codonVariants[1])
2398 if (var.variant != null)
2400 String alleles = (String) var.variant.getValue("alleles");
2401 if (alleles != null)
2403 for (String base : alleles.split(","))
2405 String codon = base1 + base + base3;
2406 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2416 * variants in third codon base
2418 for (DnaVariant var : codonVariants[2])
2420 if (var.variant != null)
2422 String alleles = (String) var.variant.getValue("alleles");
2423 if (alleles != null)
2425 for (String base : alleles.split(","))
2427 String codon = base1 + base2 + base;
2428 if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2441 * Helper method that adds a peptide variant feature, provided the given codon
2442 * translates to a value different to the current residue (is a non-synonymous
2443 * variant). ID and clinical_significance attributes of the dna variant (if
2444 * present) are copied to the new feature.
2451 * @return true if a feature was added, else false
2453 static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
2454 String residue, DnaVariant var, String codon)
2457 * get peptide translation of codon e.g. GAT -> D
2458 * note that variants which are not single alleles,
2459 * e.g. multibase variants or HGMD_MUTATION etc
2460 * are currently ignored here
2462 String trans = codon.contains("-") ? "-"
2463 : (codon.length() > CODON_LENGTH ? null : ResidueProperties
2464 .codonTranslate(codon));
2465 if (trans != null && !trans.equals(residue))
2467 String residue3Char = StringUtils
2468 .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
2469 String trans3Char = StringUtils
2470 .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
2471 String desc = "p." + residue3Char + peptidePos + trans3Char;
2472 // set score to 0f so 'graduated colour' option is offered! JAL-2060
2473 SequenceFeature sf = new SequenceFeature(
2474 SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
2475 peptidePos, 0f, var.getSource());
2476 StringBuilder attributes = new StringBuilder(32);
2477 String id = (String) var.variant.getValue(ID);
2480 if (id.startsWith(SEQUENCE_VARIANT))
2482 id = id.substring(SEQUENCE_VARIANT.length());
2484 sf.setValue(ID, id);
2485 attributes.append(ID).append("=").append(id);
2486 // TODO handle other species variants JAL-2064
2487 StringBuilder link = new StringBuilder(32);
2493 .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
2494 .append(URLEncoder.encode(id, "UTF-8"));
2495 sf.addLink(link.toString());
2496 } catch (UnsupportedEncodingException e)
2501 String clinSig = (String) var.variant.getValue(CLINICAL_SIGNIFICANCE);
2502 if (clinSig != null)
2504 sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
2505 attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
2508 peptide.addSequenceFeature(sf);
2509 if (attributes.length() > 0)
2511 sf.setAttributes(attributes.toString());
2519 * Builds a map whose key is position in the protein sequence, and value is a
2520 * list of the base and all variants for each corresponding codon position
2523 * @param dnaToProtein
2526 @SuppressWarnings("unchecked")
2527 static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
2528 SequenceI dnaSeq, MapList dnaToProtein)
2531 * map from peptide position to all variants of the codon which codes for it
2532 * LinkedHashMap ensures we keep the peptide features in sequence order
2534 LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2535 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2537 SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2538 if (dnaFeatures == null)
2543 int dnaStart = dnaSeq.getStart();
2544 int[] lastCodon = null;
2545 int lastPeptidePostion = 0;
2548 * build a map of codon variations for peptides
2550 for (SequenceFeature sf : dnaFeatures)
2552 int dnaCol = sf.getBegin();
2553 if (dnaCol != sf.getEnd())
2555 // not handling multi-locus variant features
2558 if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2560 int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2563 // feature doesn't lie within coding region
2566 int peptidePosition = mapsTo[0];
2567 List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2568 if (codonVariants == null)
2570 codonVariants = new ArrayList[CODON_LENGTH];
2571 codonVariants[0] = new ArrayList<DnaVariant>();
2572 codonVariants[1] = new ArrayList<DnaVariant>();
2573 codonVariants[2] = new ArrayList<DnaVariant>();
2574 variants.put(peptidePosition, codonVariants);
2578 * extract dna variants to a string array
2580 String alls = (String) sf.getValue("alleles");
2585 String[] alleles = alls.toUpperCase().split(",");
2587 for (String allele : alleles)
2589 alleles[i++] = allele.trim(); // lose any space characters "A, G"
2593 * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2595 int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2596 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2597 peptidePosition, peptidePosition));
2598 lastPeptidePostion = peptidePosition;
2602 * save nucleotide (and any variant) for each codon position
2604 for (int codonPos = 0; codonPos < CODON_LENGTH; codonPos++)
2606 String nucleotide = String.valueOf(
2607 dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2609 List<DnaVariant> codonVariant = codonVariants[codonPos];
2610 if (codon[codonPos] == dnaCol)
2612 if (!codonVariant.isEmpty()
2613 && codonVariant.get(0).variant == null)
2616 * already recorded base value, add this variant
2618 codonVariant.get(0).variant = sf;
2623 * add variant with base value
2625 codonVariant.add(new DnaVariant(nucleotide, sf));
2628 else if (codonVariant.isEmpty())
2631 * record (possibly non-varying) base value
2633 codonVariant.add(new DnaVariant(nucleotide));
2642 * Makes an alignment with a copy of the given sequences, adding in any
2643 * non-redundant sequences which are mapped to by the cross-referenced
2649 * the alignment dataset shared by the new copy
2652 public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2653 SequenceI[] xrefs, AlignmentI dataset)
2655 AlignmentI copy = new Alignment(new Alignment(seqs));
2656 copy.setDataset(dataset);
2657 boolean isProtein = !copy.isNucleotide();
2658 SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2661 for (SequenceI xref : xrefs)
2663 DBRefEntry[] dbrefs = xref.getDBRefs();
2666 for (DBRefEntry dbref : dbrefs)
2668 if (dbref.getMap() == null || dbref.getMap().getTo() == null
2669 || dbref.getMap().getTo().isProtein() != isProtein)
2673 SequenceI mappedTo = dbref.getMap().getTo();
2674 SequenceI match = matcher.findIdMatch(mappedTo);
2677 matcher.add(mappedTo);
2678 copy.addSequence(mappedTo);
2688 * Try to align sequences in 'unaligned' to match the alignment of their
2689 * mapped regions in 'aligned'. For example, could use this to align CDS
2690 * sequences which are mapped to their parent cDNA sequences.
2692 * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2693 * dna-to-protein or protein-to-dna use alternative methods.
2696 * sequences to be aligned
2698 * holds aligned sequences and their mappings
2701 public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2704 * easy case - aligning a copy of aligned sequences
2706 if (alignAsSameSequences(unaligned, aligned))
2708 return unaligned.getHeight();
2712 * fancy case - aligning via mappings between sequences
2714 List<SequenceI> unmapped = new ArrayList<SequenceI>();
2715 Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2716 unaligned, aligned, unmapped);
2717 int width = columnMap.size();
2718 char gap = unaligned.getGapCharacter();
2719 int realignedCount = 0;
2720 // TODO: verify this loop scales sensibly for very wide/high alignments
2722 for (SequenceI seq : unaligned.getSequences())
2724 if (!unmapped.contains(seq))
2726 char[] newSeq = new char[width];
2727 Arrays.fill(newSeq, gap); // JBPComment - doubt this is faster than the
2728 // Integer iteration below
2733 * traverse the map to find columns populated
2736 for (Integer column : columnMap.keySet())
2738 Character c = columnMap.get(column).get(seq);
2742 * sequence has a character at this position
2752 * trim trailing gaps
2754 if (lastCol < width)
2756 char[] tmp = new char[lastCol + 1];
2757 System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2760 // TODO: optimise SequenceI to avoid char[]->String->char[]
2761 seq.setSequence(String.valueOf(newSeq));
2765 return realignedCount;
2769 * If unaligned and aligned sequences share the same dataset sequences, then
2770 * simply copies the aligned sequences to the unaligned sequences and returns
2771 * true; else returns false
2774 * - sequences to be aligned based on aligned
2776 * - 'guide' alignment containing sequences derived from same dataset
2780 static boolean alignAsSameSequences(AlignmentI unaligned,
2783 if (aligned.getDataset() == null || unaligned.getDataset() == null)
2785 return false; // should only pass alignments with datasets here
2788 // map from dataset sequence to alignment sequence(s)
2789 Map<SequenceI, List<SequenceI>> alignedDatasets = new HashMap<SequenceI, List<SequenceI>>();
2790 for (SequenceI seq : aligned.getSequences())
2792 SequenceI ds = seq.getDatasetSequence();
2793 if (alignedDatasets.get(ds) == null)
2795 alignedDatasets.put(ds, new ArrayList<SequenceI>());
2797 alignedDatasets.get(ds).add(seq);
2801 * first pass - check whether all sequences to be aligned share a dataset
2802 * sequence with an aligned sequence
2804 for (SequenceI seq : unaligned.getSequences())
2806 if (!alignedDatasets.containsKey(seq.getDatasetSequence()))
2813 * second pass - copy aligned sequences;
2814 * heuristic rule: pair off sequences in order for the case where
2815 * more than one shares the same dataset sequence
2817 for (SequenceI seq : unaligned.getSequences())
2819 List<SequenceI> alignedSequences = alignedDatasets.get(seq
2820 .getDatasetSequence());
2821 // TODO: getSequenceAsString() will be deprecated in the future
2822 // TODO: need to leave to SequenceI implementor to update gaps
2823 seq.setSequence(alignedSequences.get(0).getSequenceAsString());
2824 if (alignedSequences.size() > 0)
2826 // pop off aligned sequences (except the last one)
2827 alignedSequences.remove(0);
2835 * Returns a map whose key is alignment column number (base 1), and whose
2836 * values are a map of sequence characters in that column.
2843 static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2844 AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2847 * Map will hold, for each aligned column position, a map of
2848 * {unalignedSequence, characterPerSequence} at that position.
2849 * TreeMap keeps the entries in ascending column order.
2851 Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2854 * record any sequences that have no mapping so can't be realigned
2856 unmapped.addAll(unaligned.getSequences());
2858 List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2860 for (SequenceI seq : unaligned.getSequences())
2862 for (AlignedCodonFrame mapping : mappings)
2864 SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2865 if (fromSeq != null)
2867 Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2868 if (addMappedPositions(seq, fromSeq, seqMap, map))
2870 unmapped.remove(seq);
2879 * Helper method that adds to a map the mapped column positions of a sequence. <br>
2880 * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2881 * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2885 * the sequence whose column positions we are recording
2887 * a sequence that is mapped to the first sequence
2889 * the mapping from 'fromSeq' to 'seq'
2891 * a map to add the column positions (in fromSeq) of the mapped
2895 static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2896 Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2904 * invert mapping if it is from unaligned to aligned sequence
2906 if (seqMap.getTo() == fromSeq.getDatasetSequence())
2908 seqMap = new Mapping(seq.getDatasetSequence(), seqMap.getMap()
2912 char[] fromChars = fromSeq.getSequence();
2913 int toStart = seq.getStart();
2914 char[] toChars = seq.getSequence();
2917 * traverse [start, end, start, end...] ranges in fromSeq
2919 for (int[] fromRange : seqMap.getMap().getFromRanges())
2921 for (int i = 0; i < fromRange.length - 1; i += 2)
2923 boolean forward = fromRange[i + 1] >= fromRange[i];
2926 * find the range mapped to (sequence positions base 1)
2928 int[] range = seqMap.locateMappedRange(fromRange[i],
2932 System.err.println("Error in mapping " + seqMap + " from "
2933 + fromSeq.getName());
2936 int fromCol = fromSeq.findIndex(fromRange[i]);
2937 int mappedCharPos = range[0];
2940 * walk over the 'from' aligned sequence in forward or reverse
2941 * direction; when a non-gap is found, record the column position
2942 * of the next character of the mapped-to sequence; stop when all
2943 * the characters of the range have been counted
2945 while (mappedCharPos <= range[1] && fromCol <= fromChars.length
2948 if (!Comparison.isGap(fromChars[fromCol - 1]))
2951 * mapped from sequence has a character in this column
2952 * record the column position for the mapped to character
2954 Map<SequenceI, Character> seqsMap = map.get(fromCol);
2955 if (seqsMap == null)
2957 seqsMap = new HashMap<SequenceI, Character>();
2958 map.put(fromCol, seqsMap);
2960 seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2963 fromCol += (forward ? 1 : -1);
2970 // strictly temporary hack until proper criteria for aligning protein to cds
2971 // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2972 public static boolean looksLikeEnsembl(AlignmentI alignment)
2974 for (SequenceI seq : alignment.getSequences())
2976 String name = seq.getName();
2977 if (!name.startsWith("ENSG") && !name.startsWith("ENST"))