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 jalview.datamodel.AlignedCodon;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.FeatureProperties;
31 import jalview.datamodel.IncompleteCodonException;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.SearchResults;
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;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.Collection;
49 import java.util.Collections;
50 import java.util.Comparator;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.Iterator;
54 import java.util.LinkedHashMap;
55 import java.util.List;
57 import java.util.Map.Entry;
59 import java.util.TreeMap;
62 * grab bag of useful alignment manipulation operations Expect these to be
63 * refactored elsewhere at some point.
68 public class AlignmentUtils
72 * given an existing alignment, create a new alignment including all, or up to
73 * flankSize additional symbols from each sequence's dataset sequence
79 public static AlignmentI expandContext(AlignmentI core, int flankSize)
81 List<SequenceI> sq = new ArrayList<SequenceI>();
83 for (SequenceI s : core.getSequences())
85 SequenceI newSeq = s.deriveSequence();
86 final int newSeqStart = newSeq.getStart() - 1;
87 if (newSeqStart > maxoffset
88 && newSeq.getDatasetSequence().getStart() < s.getStart())
90 maxoffset = newSeqStart;
96 maxoffset = Math.min(maxoffset, flankSize);
100 * now add offset left and right to create an expanded alignment
102 for (SequenceI s : sq)
105 while (ds.getDatasetSequence() != null)
107 ds = ds.getDatasetSequence();
109 int s_end = s.findPosition(s.getStart() + s.getLength());
110 // find available flanking residues for sequence
111 int ustream_ds = s.getStart() - ds.getStart();
112 int dstream_ds = ds.getEnd() - s_end;
114 // build new flanked sequence
116 // compute gap padding to start of flanking sequence
117 int offset = maxoffset - ustream_ds;
119 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
122 if (flankSize < ustream_ds)
124 // take up to flankSize residues
125 offset = maxoffset - flankSize;
126 ustream_ds = flankSize;
128 if (flankSize <= dstream_ds)
130 dstream_ds = flankSize - 1;
133 // TODO use Character.toLowerCase to avoid creating String objects?
134 char[] upstream = new String(ds.getSequence(s.getStart() - 1
135 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
136 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
137 + dstream_ds)).toLowerCase().toCharArray();
138 char[] coreseq = s.getSequence();
139 char[] nseq = new char[offset + upstream.length + downstream.length
141 char c = core.getGapCharacter();
144 for (; p < offset; p++)
149 System.arraycopy(upstream, 0, nseq, p, upstream.length);
150 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
152 System.arraycopy(downstream, 0, nseq, p + coreseq.length
153 + upstream.length, downstream.length);
154 s.setSequence(new String(nseq));
155 s.setStart(s.getStart() - ustream_ds);
156 s.setEnd(s_end + downstream.length);
158 AlignmentI newAl = new jalview.datamodel.Alignment(
159 sq.toArray(new SequenceI[0]));
160 for (SequenceI s : sq)
162 if (s.getAnnotation() != null)
164 for (AlignmentAnnotation aa : s.getAnnotation())
166 aa.adjustForAlignment(); // JAL-1712 fix
167 newAl.addAnnotation(aa);
171 newAl.setDataset(core.getDataset());
176 * Returns the index (zero-based position) of a sequence in an alignment, or
183 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
187 for (SequenceI alSeq : al.getSequences())
200 * Returns a map of lists of sequences in the alignment, keyed by sequence
201 * name. For use in mapping between different alignment views of the same
204 * @see jalview.datamodel.AlignmentI#getSequencesByName()
206 public static Map<String, List<SequenceI>> getSequencesByName(
209 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
210 for (SequenceI seq : al.getSequences())
212 String name = seq.getName();
215 List<SequenceI> seqs = theMap.get(name);
218 seqs = new ArrayList<SequenceI>();
219 theMap.put(name, seqs);
228 * Build mapping of protein to cDNA alignment. Mappings are made between
229 * sequences where the cDNA translates to the protein sequence. Any new
230 * mappings are added to the protein alignment. Returns true if any mappings
231 * either already exist or were added, else false.
233 * @param proteinAlignment
234 * @param cdnaAlignment
237 public static boolean mapProteinAlignmentToCdna(
238 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
240 if (proteinAlignment == null || cdnaAlignment == null)
245 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
246 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
249 * First pass - map sequences where cross-references exist. This include
250 * 1-to-many mappings to support, for example, variant cDNA.
252 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
253 cdnaAlignment, mappedDna, mappedProtein, true);
256 * Second pass - map sequences where no cross-references exist. This only
257 * does 1-to-1 mappings and assumes corresponding sequences are in the same
258 * order in the alignments.
260 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
261 mappedDna, mappedProtein, false);
262 return mappingPerformed;
266 * Make mappings between compatible sequences (where the cDNA translation
267 * matches the protein).
269 * @param proteinAlignment
270 * @param cdnaAlignment
272 * a set of mapped DNA sequences (to add to)
273 * @param mappedProtein
274 * a set of mapped Protein sequences (to add to)
276 * if true, only map sequences where xrefs exist
279 protected static boolean mapProteinToCdna(
280 final AlignmentI proteinAlignment,
281 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
282 Set<SequenceI> mappedProtein, boolean xrefsOnly)
284 boolean mappingExistsOrAdded = false;
285 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
286 for (SequenceI aaSeq : thisSeqs)
288 boolean proteinMapped = false;
289 AlignedCodonFrame acf = new AlignedCodonFrame();
291 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
294 * Always try to map if sequences have xref to each other; this supports
295 * variant cDNA or alternative splicing for a protein sequence.
297 * If no xrefs, try to map progressively, assuming that alignments have
298 * mappable sequences in corresponding order. These are not
299 * many-to-many, as that would risk mixing species with similar cDNA
302 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
308 * Don't map non-xrefd sequences more than once each. This heuristic
309 * allows us to pair up similar sequences in ordered alignments.
312 && (mappedProtein.contains(aaSeq) || mappedDna
317 if (mappingExists(proteinAlignment.getCodonFrames(),
318 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
320 mappingExistsOrAdded = true;
324 MapList map = mapProteinSequenceToCdna(aaSeq, cdnaSeq);
327 acf.addMap(cdnaSeq, aaSeq, map);
328 mappingExistsOrAdded = true;
329 proteinMapped = true;
330 mappedDna.add(cdnaSeq);
331 mappedProtein.add(aaSeq);
337 proteinAlignment.addCodonFrame(acf);
340 return mappingExistsOrAdded;
344 * Answers true if the mappings include one between the given (dataset)
347 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
348 SequenceI aaSeq, SequenceI cdnaSeq)
350 if (mappings != null)
352 for (AlignedCodonFrame acf : mappings)
354 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
364 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
365 * must be three times the length of the protein, possibly after ignoring
366 * start and/or stop codons, and must translate to the protein. Returns null
367 * if no mapping is determined.
373 public static MapList mapProteinSequenceToCdna(SequenceI proteinSeq,
377 * Here we handle either dataset sequence set (desktop) or absent (applet).
378 * Use only the char[] form of the sequence to avoid creating possibly large
381 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
382 char[] aaSeqChars = proteinDataset != null ? proteinDataset
383 .getSequence() : proteinSeq.getSequence();
384 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
385 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
386 : cdnaSeq.getSequence();
387 if (aaSeqChars == null || cdnaSeqChars == null)
393 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
395 final int mappedLength = 3 * aaSeqChars.length;
396 int cdnaLength = cdnaSeqChars.length;
397 int cdnaStart = cdnaSeq.getStart();
398 int cdnaEnd = cdnaSeq.getEnd();
399 final int proteinStart = proteinSeq.getStart();
400 final int proteinEnd = proteinSeq.getEnd();
403 * If lengths don't match, try ignoring stop codon.
405 if (cdnaLength != mappedLength && cdnaLength > 2)
407 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
409 for (String stop : ResidueProperties.STOP)
411 if (lastCodon.equals(stop))
421 * If lengths still don't match, try ignoring start codon.
424 if (cdnaLength != mappedLength
426 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
427 .equals(ResidueProperties.START))
434 if (cdnaLength != mappedLength)
438 if (!translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
442 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[] {
443 proteinStart, proteinEnd }, 3, 1);
448 * Test whether the given cdna sequence, starting at the given offset,
449 * translates to the given amino acid sequence, using the standard translation
450 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
452 * @param cdnaSeqChars
457 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
460 if (cdnaSeqChars == null || aaSeqChars == null)
466 for (int i = cdnaStart; i < cdnaSeqChars.length - 2
467 && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
469 String codon = String.valueOf(cdnaSeqChars, i, 3);
470 final String translated = ResidueProperties.codonTranslate(codon);
472 * allow * in protein to match untranslatable in dna
474 final char aaRes = aaSeqChars[aaResidue];
475 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
479 if (translated == null || !(aaRes == translated.charAt(0)))
482 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
483 // + codon + "(" + translated + ") != " + aaRes));
487 // fail if we didn't match all of the aa sequence
488 return (aaResidue == aaSeqChars.length);
492 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
493 * currently assumes that we are aligning cDNA to match protein.
496 * the sequence to be realigned
498 * the alignment whose sequence alignment is to be 'copied'
500 * character string represent a gap in the realigned sequence
501 * @param preserveUnmappedGaps
502 * @param preserveMappedGaps
503 * @return true if the sequence was realigned, false if it could not be
505 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
506 String gap, boolean preserveMappedGaps,
507 boolean preserveUnmappedGaps)
510 * Get any mappings from the source alignment to the target (dataset)
513 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
514 // all mappings. Would it help to constrain this?
515 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
516 if (mappings == null || mappings.isEmpty())
522 * Locate the aligned source sequence whose dataset sequence is mapped. We
523 * just take the first match here (as we can't align like more than one
526 SequenceI alignFrom = null;
527 AlignedCodonFrame mapping = null;
528 for (AlignedCodonFrame mp : mappings)
530 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
531 if (alignFrom != null)
538 if (alignFrom == null)
542 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
543 preserveMappedGaps, preserveUnmappedGaps);
548 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
549 * match residues and codons. Flags control whether existing gaps in unmapped
550 * (intron) and mapped (exon) regions are preserved or not. Gaps between
551 * intron and exon are only retained if both flags are set.
558 * @param preserveUnmappedGaps
559 * @param preserveMappedGaps
561 public static void alignSequenceAs(SequenceI alignTo,
562 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
563 char sourceGap, boolean preserveMappedGaps,
564 boolean preserveUnmappedGaps)
566 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
568 // aligned and dataset sequence positions, all base zero
572 int basesWritten = 0;
573 char myGapChar = myGap.charAt(0);
574 int ratio = myGap.length();
576 int fromOffset = alignFrom.getStart() - 1;
577 int toOffset = alignTo.getStart() - 1;
578 int sourceGapMappedLength = 0;
579 boolean inExon = false;
580 final char[] thisSeq = alignTo.getSequence();
581 final char[] thatAligned = alignFrom.getSequence();
582 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
585 * Traverse the 'model' aligned sequence
587 for (char sourceChar : thatAligned)
589 if (sourceChar == sourceGap)
591 sourceGapMappedLength += ratio;
596 * Found a non-gap character. Locate its mapped region if any.
599 // Note mapping positions are base 1, our sequence positions base 0
600 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
601 sourceDsPos + fromOffset);
602 if (mappedPos == null)
605 * unmapped position; treat like a gap
607 sourceGapMappedLength += ratio;
608 // System.err.println("Can't align: no codon mapping to residue "
609 // + sourceDsPos + "(" + sourceChar + ")");
614 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
615 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
616 StringBuilder trailingCopiedGap = new StringBuilder();
619 * Copy dna sequence up to and including this codon. Optionally, include
620 * gaps before the codon starts (in introns) and/or after the codon starts
623 * Note this only works for 'linear' splicing, not reverse or interleaved.
624 * But then 'align dna as protein' doesn't make much sense otherwise.
626 int intronLength = 0;
627 while (basesWritten + toOffset < mappedCodonEnd
628 && thisSeqPos < thisSeq.length)
630 final char c = thisSeq[thisSeqPos++];
634 int sourcePosition = basesWritten + toOffset;
635 if (sourcePosition < mappedCodonStart)
638 * Found an unmapped (intron) base. First add in any preceding gaps
641 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
643 thisAligned.append(trailingCopiedGap.toString());
644 intronLength += trailingCopiedGap.length();
645 trailingCopiedGap = new StringBuilder();
652 final boolean startOfCodon = sourcePosition == mappedCodonStart;
653 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
654 preserveUnmappedGaps, sourceGapMappedLength, inExon,
655 trailingCopiedGap.length(), intronLength, startOfCodon);
656 for (int i = 0; i < gapsToAdd; i++)
658 thisAligned.append(myGapChar);
660 sourceGapMappedLength = 0;
663 thisAligned.append(c);
664 trailingCopiedGap = new StringBuilder();
668 if (inExon && preserveMappedGaps)
670 trailingCopiedGap.append(myGapChar);
672 else if (!inExon && preserveUnmappedGaps)
674 trailingCopiedGap.append(myGapChar);
681 * At end of model aligned sequence. Copy any remaining target sequence, optionally
682 * including (intron) gaps.
684 while (thisSeqPos < thisSeq.length)
686 final char c = thisSeq[thisSeqPos++];
687 if (c != myGapChar || preserveUnmappedGaps)
689 thisAligned.append(c);
691 sourceGapMappedLength--;
695 * finally add gaps to pad for any trailing source gaps or
696 * unmapped characters
698 if (preserveUnmappedGaps)
700 while (sourceGapMappedLength > 0)
702 thisAligned.append(myGapChar);
703 sourceGapMappedLength--;
708 * All done aligning, set the aligned sequence.
710 alignTo.setSequence(new String(thisAligned));
714 * Helper method to work out how many gaps to insert when realigning.
716 * @param preserveMappedGaps
717 * @param preserveUnmappedGaps
718 * @param sourceGapMappedLength
720 * @param trailingCopiedGap
721 * @param intronLength
722 * @param startOfCodon
725 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
726 boolean preserveUnmappedGaps, int sourceGapMappedLength,
727 boolean inExon, int trailingGapLength, int intronLength,
728 final boolean startOfCodon)
734 * Reached start of codon. Ignore trailing gaps in intron unless we are
735 * preserving gaps in both exon and intron. Ignore them anyway if the
736 * protein alignment introduces a gap at least as large as the intronic
739 if (inExon && !preserveMappedGaps)
741 trailingGapLength = 0;
743 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
745 trailingGapLength = 0;
749 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
753 if (intronLength + trailingGapLength <= sourceGapMappedLength)
755 gapsToAdd = sourceGapMappedLength - intronLength;
759 gapsToAdd = Math.min(intronLength + trailingGapLength
760 - sourceGapMappedLength, trailingGapLength);
767 * second or third base of codon; check for any gaps in dna
769 if (!preserveMappedGaps)
771 trailingGapLength = 0;
773 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
779 * Returns a list of sequences mapped from the given sequences and aligned
780 * (gapped) in the same way. For example, the cDNA for aligned protein, where
781 * a single gap in protein generates three gaps in cDNA.
784 * @param gapCharacter
788 public static List<SequenceI> getAlignedTranslation(
789 List<SequenceI> sequences, char gapCharacter,
790 Set<AlignedCodonFrame> mappings)
792 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
794 for (SequenceI seq : sequences)
796 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
798 alignedSeqs.addAll(mapped);
804 * Returns sequences aligned 'like' the source sequence, as mapped by the
805 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
806 * will support 1-to-many as well.
809 * @param gapCharacter
813 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
814 char gapCharacter, Set<AlignedCodonFrame> mappings)
816 List<SequenceI> result = new ArrayList<SequenceI>();
817 for (AlignedCodonFrame mapping : mappings)
819 if (mapping.involvesSequence(seq))
821 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
832 * Returns the translation of 'seq' (as held in the mapping) with
833 * corresponding alignment (gaps).
836 * @param gapCharacter
840 protected static SequenceI getAlignedTranslation(SequenceI seq,
841 char gapCharacter, AlignedCodonFrame mapping)
843 String gap = String.valueOf(gapCharacter);
844 boolean toDna = false;
846 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
849 // mapping is from protein to nucleotide
851 // should ideally get gap count ratio from mapping
852 gap = String.valueOf(new char[] { gapCharacter, gapCharacter,
857 // mapping is from nucleotide to protein
858 mapTo = mapping.getAaForDnaSeq(seq);
861 StringBuilder newseq = new StringBuilder(seq.getLength()
864 int residueNo = 0; // in seq, base 1
865 int[] phrase = new int[fromRatio];
866 int phraseOffset = 0;
868 boolean first = true;
869 final Sequence alignedSeq = new Sequence("", "");
871 for (char c : seq.getSequence())
873 if (c == gapCharacter)
876 if (gapWidth >= fromRatio)
884 phrase[phraseOffset++] = residueNo + 1;
885 if (phraseOffset == fromRatio)
888 * Have read a whole codon (or protein residue), now translate: map
889 * source phrase to positions in target sequence add characters at
890 * these positions to newseq Note mapping positions are base 1, our
891 * sequence positions base 0.
893 SearchResults sr = new SearchResults();
894 for (int pos : phrase)
896 mapping.markMappedRegion(seq, pos, sr);
898 newseq.append(sr.getCharacters());
902 // Hack: Copy sequence dataset, name and description from
903 // SearchResults.match[0].sequence
904 // TODO? carry over sequence names from original 'complement'
906 SequenceI mappedTo = sr.getResultSequence(0);
907 alignedSeq.setName(mappedTo.getName());
908 alignedSeq.setDescription(mappedTo.getDescription());
909 alignedSeq.setDatasetSequence(mappedTo);
916 alignedSeq.setSequence(newseq.toString());
921 * Realigns the given protein to match the alignment of the dna, using codon
922 * mappings to translate aligned codon positions to protein residues.
925 * the alignment whose sequences are realigned by this method
927 * the dna alignment whose alignment we are 'copying'
928 * @return the number of sequences that were realigned
930 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
932 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
933 unmappedProtein.addAll(protein.getSequences());
935 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
938 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
939 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
940 * comparator keeps the codon positions ordered.
942 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, String>>(
943 new CodonComparator());
944 for (SequenceI dnaSeq : dna.getSequences())
946 for (AlignedCodonFrame mapping : mappings)
948 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
949 SequenceI prot = mapping.findAlignedSequence(
950 dnaSeq.getDatasetSequence(), protein);
953 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
954 seqMap, alignedCodons);
955 unmappedProtein.remove(prot);
959 return alignProteinAs(protein, alignedCodons, unmappedProtein);
963 * Update the aligned protein sequences to match the codon alignments given in
967 * @param alignedCodons
968 * an ordered map of codon positions (columns), with sequence/peptide
969 * values present in each column
970 * @param unmappedProtein
973 protected static int alignProteinAs(AlignmentI protein,
974 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons,
975 List<SequenceI> unmappedProtein)
978 * Prefill aligned sequences with gaps before inserting aligned protein
981 int alignedWidth = alignedCodons.size();
982 char[] gaps = new char[alignedWidth];
983 Arrays.fill(gaps, protein.getGapCharacter());
984 String allGaps = String.valueOf(gaps);
985 for (SequenceI seq : protein.getSequences())
987 if (!unmappedProtein.contains(seq))
989 seq.setSequence(allGaps);
994 for (AlignedCodon codon : alignedCodons.keySet())
996 final Map<SequenceI, String> columnResidues = alignedCodons
998 for (Entry<SequenceI, String> entry : columnResidues.entrySet())
1000 // place translated codon at its column position in sequence
1001 entry.getKey().getSequence()[column] = entry.getValue().charAt(0);
1009 * Populate the map of aligned codons by traversing the given sequence
1010 * mapping, locating the aligned positions of mapped codons, and adding those
1011 * positions and their translation products to the map.
1014 * the aligned sequence we are mapping from
1016 * the sequence to be aligned to the codons
1018 * the gap character in the dna sequence
1020 * a mapping to a sequence translation
1021 * @param alignedCodons
1022 * the map we are building up
1024 static void addCodonPositions(SequenceI dna, SequenceI protein,
1025 char gapChar, Mapping seqMap,
1026 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
1028 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1029 while (codons.hasNext())
1033 AlignedCodon codon = codons.next();
1034 Map<SequenceI, String> seqProduct = alignedCodons.get(codon);
1035 if (seqProduct == null)
1037 seqProduct = new HashMap<SequenceI, String>();
1038 alignedCodons.put(codon, seqProduct);
1040 seqProduct.put(protein, codon.product);
1041 } catch (IncompleteCodonException e)
1043 // possible incomplete trailing codon - ignore
1049 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1050 * between at least one pair of sequences in the two alignments. Currently,
1053 * <li>One alignment must be nucleotide, and the other protein</li>
1054 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1055 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1056 * <li>The translation may ignore start and stop codons if present in the
1064 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1066 if (al1 == null || al2 == null)
1072 * Require one nucleotide and one protein
1074 if (al1.isNucleotide() == al2.isNucleotide())
1078 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1079 AlignmentI protein = dna == al1 ? al2 : al1;
1080 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1081 for (SequenceI dnaSeq : dna.getSequences())
1083 for (SequenceI proteinSeq : protein.getSequences())
1085 if (isMappable(dnaSeq, proteinSeq, mappings))
1095 * Returns true if the dna sequence is mapped, or could be mapped, to the
1103 protected static boolean isMappable(SequenceI dnaSeq,
1104 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1106 if (dnaSeq == null || proteinSeq == null)
1111 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1112 .getDatasetSequence();
1113 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1114 : proteinSeq.getDatasetSequence();
1116 for (AlignedCodonFrame mapping : mappings)
1118 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1128 * Just try to make a mapping (it is not yet stored), test whether
1131 return mapProteinSequenceToCdna(proteinDs, dnaDs) != null;
1135 * Finds any reference annotations associated with the sequences in
1136 * sequenceScope, that are not already added to the alignment, and adds them
1137 * to the 'candidates' map. Also populates a lookup table of annotation
1138 * labels, keyed by calcId, for use in constructing tooltips or the like.
1140 * @param sequenceScope
1141 * the sequences to scan for reference annotations
1142 * @param labelForCalcId
1143 * (optional) map to populate with label for calcId
1145 * map to populate with annotations for sequence
1147 * the alignment to check for presence of annotations
1149 public static void findAddableReferenceAnnotations(
1150 List<SequenceI> sequenceScope,
1151 Map<String, String> labelForCalcId,
1152 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1155 if (sequenceScope == null)
1161 * For each sequence in scope, make a list of any annotations on the
1162 * underlying dataset sequence which are not already on the alignment.
1164 * Add to a map of { alignmentSequence, <List of annotations to add> }
1166 for (SequenceI seq : sequenceScope)
1168 SequenceI dataset = seq.getDatasetSequence();
1169 if (dataset == null)
1173 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1174 if (datasetAnnotations == null)
1178 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1179 for (AlignmentAnnotation dsann : datasetAnnotations)
1182 * Find matching annotations on the alignment. If none is found, then
1183 * add this annotation to the list of 'addable' annotations for this
1186 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1187 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1188 if (!matchedAlignmentAnnotations.iterator().hasNext())
1191 if (labelForCalcId != null)
1193 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1198 * Save any addable annotations for this sequence
1200 if (!result.isEmpty())
1202 candidates.put(seq, result);
1208 * Adds annotations to the top of the alignment annotations, in the same order
1209 * as their related sequences.
1211 * @param annotations
1212 * the annotations to add
1214 * the alignment to add them to
1215 * @param selectionGroup
1216 * current selection group (or null if none)
1218 public static void addReferenceAnnotations(
1219 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1220 final AlignmentI alignment, final SequenceGroup selectionGroup)
1222 for (SequenceI seq : annotations.keySet())
1224 for (AlignmentAnnotation ann : annotations.get(seq))
1226 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1228 int endRes = ann.annotations.length;
1229 if (selectionGroup != null)
1231 startRes = selectionGroup.getStartRes();
1232 endRes = selectionGroup.getEndRes();
1234 copyAnn.restrict(startRes, endRes);
1237 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1238 * original annotation is already on the sequence.
1240 if (!seq.hasAnnotation(ann))
1242 seq.addAlignmentAnnotation(copyAnn);
1245 copyAnn.adjustForAlignment();
1246 // add to the alignment and set visible
1247 alignment.addAnnotation(copyAnn);
1248 copyAnn.visible = true;
1254 * Set visibility of alignment annotations of specified types (labels), for
1255 * specified sequences. This supports controls like
1256 * "Show all secondary structure", "Hide all Temp factor", etc.
1258 * @al the alignment to scan for annotations
1260 * the types (labels) of annotations to be updated
1261 * @param forSequences
1262 * if not null, only annotations linked to one of these sequences are
1263 * in scope for update; if null, acts on all sequence annotations
1265 * if this flag is true, 'types' is ignored (label not checked)
1267 * if true, set visibility on, else set off
1269 public static void showOrHideSequenceAnnotations(AlignmentI al,
1270 Collection<String> types, List<SequenceI> forSequences,
1271 boolean anyType, boolean doShow)
1273 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1275 if (anyType || types.contains(aa.label))
1277 if ((aa.sequenceRef != null)
1278 && (forSequences == null || forSequences
1279 .contains(aa.sequenceRef)))
1281 aa.visible = doShow;
1288 * Returns true if either sequence has a cross-reference to the other
1294 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1296 // Note: moved here from class CrossRef as the latter class has dependencies
1297 // not availability to the applet's classpath
1298 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1302 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1303 * that sequence name is structured as Source|AccessionId.
1309 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1311 if (seq1 == null || seq2 == null)
1315 String name = seq2.getName();
1316 final DBRefEntry[] xrefs = seq1.getDBRefs();
1319 for (DBRefEntry xref : xrefs)
1321 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1322 // case-insensitive test, consistent with DBRefEntry.equalRef()
1323 if (xrefName.equalsIgnoreCase(name))
1333 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1334 * nucleotide sequences, and updates mappings to match. The new sequences are
1335 * aligned as per the original sequences (with gapped columns omitted).
1338 * aligned dna sequences
1340 * from dna to protein; these are replaced with new mappings
1342 * @return an alignment whose sequences are the cds-only parts of the dna
1343 * sequences (or null if no mappings are found)
1345 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1346 List<AlignedCodonFrame> mappings, char gapChar)
1348 List<int[]> cdsColumns = findCdsColumns(dna);
1351 * create CDS sequences and new mappings
1352 * (from cdna to cds, and cds to peptide)
1354 List<AlignedCodonFrame> newMappings = new ArrayList<AlignedCodonFrame>();
1355 List<SequenceI> cdsSequences = new ArrayList<SequenceI>();
1357 for (SequenceI dnaSeq : dna)
1359 final SequenceI ds = dnaSeq.getDatasetSequence();
1360 List<AlignedCodonFrame> seqMappings = MappingUtils
1361 .findMappingsForSequence(ds, mappings);
1362 for (AlignedCodonFrame acf : seqMappings)
1364 AlignedCodonFrame newMapping = new AlignedCodonFrame();
1365 final List<SequenceI> mappedCds = makeCdsSequences(dnaSeq, acf,
1366 cdsColumns, newMapping, gapChar);
1367 if (!mappedCds.isEmpty())
1369 cdsSequences.addAll(mappedCds);
1370 newMappings.add(newMapping);
1374 AlignmentI al = new Alignment(
1375 cdsSequences.toArray(new SequenceI[cdsSequences.size()]));
1376 al.setGapCharacter(gapChar);
1377 al.setDataset(null);
1380 * Replace the old mappings with the new ones
1383 mappings.addAll(newMappings);
1389 * Returns a consolidated list of column ranges where at least one sequence
1390 * has a CDS feature. This assumes CDS features are on genomic sequence i.e.
1391 * are for contiguous CDS ranges (no gaps).
1396 public static List<int[]> findCdsColumns(SequenceI[] seqs)
1398 // TODO use refactored code from AlignViewController
1399 // markColumnsContainingFeatures, not reinvent the wheel!
1401 List<int[]> result = new ArrayList<int[]>();
1402 for (SequenceI seq : seqs)
1404 result.addAll(findCdsColumns(seq));
1408 * sort and compact the list into ascending, non-overlapping ranges
1410 Collections.sort(result, new Comparator<int[]>()
1413 public int compare(int[] o1, int[] o2)
1415 return Integer.compare(o1[0], o2[0]);
1418 result = MapList.coalesceRanges(result);
1423 public static List<int[]> findCdsColumns(SequenceI seq)
1425 List<int[]> result = new ArrayList<int[]>();
1426 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1427 SequenceFeature[] sfs = seq.getSequenceFeatures();
1430 for (SequenceFeature sf : sfs)
1432 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1434 int colStart = seq.findIndex(sf.getBegin());
1435 int colEnd = seq.findIndex(sf.getEnd());
1436 result.add(new int[] { colStart, colEnd });
1444 * Answers true if all sequences have a gap at (or do not extend to) the
1445 * specified column position (base 1)
1451 public static boolean isGappedColumn(List<SequenceI> seqs, int col)
1455 for (SequenceI seq : seqs)
1457 if (!Comparison.isGap(seq.getCharAt(col - 1)))
1467 * Returns the column ranges (base 1) of each aligned sequence that are
1468 * involved in any mapping. This is a helper method for aligning protein
1469 * products of aligned transcripts.
1471 * @param mappedSequences
1472 * (possibly gapped) dna sequences
1476 protected static List<List<int[]>> getMappedColumns(
1477 List<SequenceI> mappedSequences,
1478 List<AlignedCodonFrame> mappings)
1480 List<List<int[]>> result = new ArrayList<List<int[]>>();
1481 for (SequenceI seq : mappedSequences)
1483 List<int[]> columns = new ArrayList<int[]>();
1484 List<AlignedCodonFrame> seqMappings = MappingUtils
1485 .findMappingsForSequence(seq, mappings);
1486 for (AlignedCodonFrame mapping : seqMappings)
1488 List<Mapping> maps = mapping.getMappingsForSequence(seq);
1489 for (Mapping map : maps)
1492 * Get the codon regions as { [2, 5], [7, 12], [14, 14] etc }
1493 * Find and add the overall aligned column range for each
1495 for (int[] cdsRange : map.getMap().getFromRanges())
1497 int startPos = cdsRange[0];
1498 int endPos = cdsRange[1];
1499 int startCol = seq.findIndex(startPos);
1500 int endCol = seq.findIndex(endPos);
1501 columns.add(new int[] { startCol, endCol });
1505 result.add(columns);
1511 * Helper method to make cds-only sequences and populate their mappings to
1514 * For example, if ggCCaTTcGAg has mappings [3, 4, 6, 7, 9, 10] to protein
1515 * then generate a sequence CCTTGA with mapping [1, 6] to the same protein
1518 * Typically eukaryotic dna will include cds encoding for a single peptide
1519 * sequence i.e. return a single result. Bacterial dna may have overlapping
1520 * cds mappings coding for multiple peptides so return multiple results
1521 * (example EMBL KF591215).
1524 * a dna aligned sequence
1526 * containing one or more mappings of the sequence to protein
1527 * @param ungappedCdsColumns
1528 * @param newMappings
1529 * the new mapping to populate, from the cds-only sequences to their
1530 * mapped protein sequences
1533 protected static List<SequenceI> makeCdsSequences(SequenceI dnaSeq,
1534 AlignedCodonFrame mapping, List<int[]> ungappedCdsColumns,
1535 AlignedCodonFrame newMappings, char gapChar)
1537 List<SequenceI> cdsSequences = new ArrayList<SequenceI>();
1538 List<Mapping> seqMappings = mapping.getMappingsForSequence(dnaSeq);
1540 for (Mapping seqMapping : seqMappings)
1542 SequenceI cds = makeCdsSequence(dnaSeq, seqMapping,
1543 ungappedCdsColumns, gapChar);
1544 cdsSequences.add(cds);
1547 * add new mappings, from dna to cds, and from cds to peptide
1549 MapList dnaToCds = addCdsMappings(dnaSeq.getDatasetSequence(), cds,
1550 seqMapping, newMappings);
1553 * transfer any features on dna that overlap the CDS
1555 transferFeatures(dnaSeq, cds, dnaToCds, null, SequenceOntologyI.CDS);
1557 return cdsSequences;
1561 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1562 * feature start/end ranges, optionally omitting specified feature types.
1563 * Returns the number of features copied.
1568 * if not null, only features of this type are copied (including
1569 * subtypes in the Sequence Ontology)
1571 * the mapping from 'fromSeq' to 'toSeq'
1574 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1575 MapList mapping, String select, String... omitting)
1577 SequenceI copyTo = toSeq;
1578 while (copyTo.getDatasetSequence() != null)
1580 copyTo = copyTo.getDatasetSequence();
1583 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1585 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1588 for (SequenceFeature sf : sfs)
1590 String type = sf.getType();
1591 if (select != null && !so.isA(type, select))
1595 boolean omit = false;
1596 for (String toOmit : omitting)
1598 if (type.equals(toOmit))
1609 * locate the mapped range - null if either start or end is
1610 * not mapped (no partial overlaps are calculated)
1612 int start = sf.getBegin();
1613 int end = sf.getEnd();
1614 int[] mappedTo = mapping.locateInTo(start, end);
1616 * if whole exon range doesn't map, try interpreting it
1617 * as 5' or 3' exon overlapping the CDS range
1619 if (mappedTo == null)
1621 mappedTo = mapping.locateInTo(end, end);
1622 if (mappedTo != null)
1625 * end of exon is in CDS range - 5' overlap
1626 * to a range from the start of the peptide
1631 if (mappedTo == null)
1633 mappedTo = mapping.locateInTo(start, start);
1634 if (mappedTo != null)
1637 * start of exon is in CDS range - 3' overlap
1638 * to a range up to the end of the peptide
1640 mappedTo[1] = toSeq.getLength();
1643 if (mappedTo != null)
1645 SequenceFeature copy = new SequenceFeature(sf);
1646 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1647 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1648 copyTo.addSequenceFeature(copy);
1657 * Creates and adds mappings
1659 * <li>from cds to peptide</li>
1660 * <li>from dna to cds</li>
1662 * and returns the dna-to-cds mapping
1667 * @param newMappings
1670 protected static MapList addCdsMappings(SequenceI dnaSeq,
1672 Mapping dnaMapping, AlignedCodonFrame newMappings)
1674 cdsSeq.createDatasetSequence();
1677 * CDS to peptide is just a contiguous 3:1 mapping, with
1678 * the peptide ranges taken unchanged from the dna mapping
1680 List<int[]> cdsRanges = new ArrayList<int[]>();
1681 SequenceI cdsDataset = cdsSeq.getDatasetSequence();
1682 cdsRanges.add(new int[] { 1, cdsDataset.getLength() });
1683 MapList cdsToPeptide = new MapList(cdsRanges, dnaMapping.getMap()
1684 .getToRanges(), 3, 1);
1685 newMappings.addMap(cdsDataset, dnaMapping.getTo(),
1689 * dna 'from' ranges map 1:1 to the contiguous extracted CDS
1691 MapList dnaToCds = new MapList(
1692 dnaMapping.getMap().getFromRanges(), cdsRanges, 1, 1);
1693 newMappings.addMap(dnaSeq, cdsDataset, dnaToCds);
1698 * Makes and returns a CDS-only sequence, where the CDS regions are identified
1699 * as the 'from' ranges of the mapping on the dna.
1702 * nucleotide sequence
1704 * mappings from CDS regions of nucleotide
1705 * @param ungappedCdsColumns
1708 protected static SequenceI makeCdsSequence(SequenceI dnaSeq,
1709 Mapping seqMapping, List<int[]> ungappedCdsColumns, char gapChar)
1711 int cdsWidth = MappingUtils.getLength(ungappedCdsColumns);
1714 * populate CDS columns with the aligned
1715 * column character if that column is mapped (which may be a gap
1716 * if an intron interrupts a codon), else with a gap
1718 List<int[]> fromRanges = seqMapping.getMap().getFromRanges();
1719 char[] cdsChars = new char[cdsWidth];
1721 for (int[] columns : ungappedCdsColumns)
1723 for (int i = columns[0]; i <= columns[1]; i++)
1725 char dnaChar = dnaSeq.getCharAt(i - 1);
1726 if (Comparison.isGap(dnaChar))
1728 cdsChars[pos] = gapChar;
1732 int seqPos = dnaSeq.findPosition(i - 1);
1733 if (MappingUtils.contains(fromRanges, seqPos))
1735 cdsChars[pos] = dnaChar;
1739 cdsChars[pos] = gapChar;
1745 SequenceI cdsSequence = new Sequence(dnaSeq.getName(),
1746 String.valueOf(cdsChars));
1748 transferDbRefs(seqMapping.getTo(), cdsSequence);
1754 * Locate any xrefs to CDS databases on the protein product and attach to the
1755 * CDS sequence. Also add as a sub-token of the sequence name.
1760 protected static void transferDbRefs(SequenceI from, SequenceI to)
1762 String cdsAccId = FeatureProperties.getCodingFeature(DBRefSource.EMBL);
1763 DBRefEntry[] cdsRefs = DBRefUtils.selectRefs(from.getDBRefs(),
1764 DBRefSource.CODINGDBS);
1765 if (cdsRefs != null)
1767 for (DBRefEntry cdsRef : cdsRefs)
1769 to.addDBRef(new DBRefEntry(cdsRef));
1770 cdsAccId = cdsRef.getAccessionId();
1773 if (!to.getName().contains(cdsAccId))
1775 to.setName(to.getName() + "|" + cdsAccId);