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 java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.LinkedHashMap;
30 import java.util.LinkedHashSet;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.TreeMap;
37 import jalview.datamodel.AlignedCodon;
38 import jalview.datamodel.AlignedCodonFrame;
39 import jalview.datamodel.Alignment;
40 import jalview.datamodel.AlignmentAnnotation;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.DBRefEntry;
43 import jalview.datamodel.DBRefSource;
44 import jalview.datamodel.FeatureProperties;
45 import jalview.datamodel.Mapping;
46 import jalview.datamodel.SearchResults;
47 import jalview.datamodel.Sequence;
48 import jalview.datamodel.SequenceGroup;
49 import jalview.datamodel.SequenceI;
50 import jalview.schemes.ResidueProperties;
51 import jalview.util.DBRefUtils;
52 import jalview.util.MapList;
53 import jalview.util.MappingUtils;
56 * grab bag of useful alignment manipulation operations Expect these to be
57 * refactored elsewhere at some point.
62 public class AlignmentUtils
66 * given an existing alignment, create a new alignment including all, or up to
67 * flankSize additional symbols from each sequence's dataset sequence
73 public static AlignmentI expandContext(AlignmentI core, int flankSize)
75 List<SequenceI> sq = new ArrayList<SequenceI>();
77 for (SequenceI s : core.getSequences())
79 SequenceI newSeq = s.deriveSequence();
80 if (newSeq.getStart() > maxoffset
81 && newSeq.getDatasetSequence().getStart() < s.getStart())
83 maxoffset = newSeq.getStart();
89 maxoffset = flankSize;
91 // now add offset to create a new expanded alignment
92 for (SequenceI s : sq)
95 while (ds.getDatasetSequence() != null)
97 ds = ds.getDatasetSequence();
99 int s_end = s.findPosition(s.getStart() + s.getLength());
100 // find available flanking residues for sequence
101 int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
104 // build new flanked sequence
106 // compute gap padding to start of flanking sequence
107 int offset = maxoffset - ustream_ds;
109 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
112 if (flankSize < ustream_ds)
114 // take up to flankSize residues
115 offset = maxoffset - flankSize;
116 ustream_ds = flankSize;
118 if (flankSize < dstream_ds)
120 dstream_ds = flankSize;
123 char[] upstream = new String(ds.getSequence(s.getStart() - 1
124 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
125 char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
126 + dstream_ds)).toLowerCase().toCharArray();
127 char[] coreseq = s.getSequence();
128 char[] nseq = new char[offset + upstream.length + downstream.length
130 char c = core.getGapCharacter();
131 // TODO could lowercase the flanking regions
133 for (; p < offset; p++)
137 // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
138 // new String(downstream).toLowerCase());
139 System.arraycopy(upstream, 0, nseq, p, upstream.length);
140 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
142 System.arraycopy(downstream, 0, nseq, p + coreseq.length
143 + upstream.length, downstream.length);
144 s.setSequence(new String(nseq));
145 s.setStart(s.getStart() - ustream_ds);
146 s.setEnd(s_end + downstream.length);
148 AlignmentI newAl = new jalview.datamodel.Alignment(
149 sq.toArray(new SequenceI[0]));
150 for (SequenceI s : sq)
152 if (s.getAnnotation() != null)
154 for (AlignmentAnnotation aa : s.getAnnotation())
156 newAl.addAnnotation(aa);
160 newAl.setDataset(core.getDataset());
165 * Returns the index (zero-based position) of a sequence in an alignment, or
172 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
176 for (SequenceI alSeq : al.getSequences())
189 * Returns a map of lists of sequences in the alignment, keyed by sequence
190 * name. For use in mapping between different alignment views of the same
193 * @see jalview.datamodel.AlignmentI#getSequencesByName()
195 public static Map<String, List<SequenceI>> getSequencesByName(
198 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
199 for (SequenceI seq : al.getSequences())
201 String name = seq.getName();
204 List<SequenceI> seqs = theMap.get(name);
207 seqs = new ArrayList<SequenceI>();
208 theMap.put(name, seqs);
217 * Build mapping of protein to cDNA alignment. Mappings are made between
218 * sequences where the cDNA translates to the protein sequence. Any new
219 * mappings are added to the protein alignment. Returns true if any mappings
220 * either already exist or were added, else false.
222 * @param proteinAlignment
223 * @param cdnaAlignment
226 public static boolean mapProteinToCdna(
227 final AlignmentI proteinAlignment,
228 final AlignmentI cdnaAlignment)
230 if (proteinAlignment == null || cdnaAlignment == null)
235 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
236 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
239 * First pass - map sequences where cross-references exist. This include
240 * 1-to-many mappings to support, for example, variant cDNA.
242 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
243 cdnaAlignment, mappedDna, mappedProtein, true);
246 * Second pass - map sequences where no cross-references exist. This only
247 * does 1-to-1 mappings and assumes corresponding sequences are in the same
248 * order in the alignments.
250 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
251 mappedDna, mappedProtein, false);
252 return mappingPerformed;
256 * Make mappings between compatible sequences (where the cDNA translation
257 * matches the protein).
259 * @param proteinAlignment
260 * @param cdnaAlignment
262 * a set of mapped DNA sequences (to add to)
263 * @param mappedProtein
264 * a set of mapped Protein sequences (to add to)
266 * if true, only map sequences where xrefs exist
269 protected static boolean mapProteinToCdna(
270 final AlignmentI proteinAlignment,
271 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
272 Set<SequenceI> mappedProtein, boolean xrefsOnly)
274 boolean mappingPerformed = false;
275 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
276 for (SequenceI aaSeq : thisSeqs)
278 boolean proteinMapped = false;
279 AlignedCodonFrame acf = new AlignedCodonFrame();
281 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
284 * Always try to map if sequences have xref to each other; this supports
285 * variant cDNA or alternative splicing for a protein sequence.
287 * If no xrefs, try to map progressively, assuming that alignments have
288 * mappable sequences in corresponding order. These are not
289 * many-to-many, as that would risk mixing species with similar cDNA
292 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
298 * Don't map non-xrefd sequences more than once each. This heuristic
299 * allows us to pair up similar sequences in ordered alignments.
302 && (mappedProtein.contains(aaSeq) || mappedDna
307 if (!mappingExists(proteinAlignment.getCodonFrames(),
308 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
310 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
313 acf.addMap(cdnaSeq, aaSeq, map);
314 mappingPerformed = true;
315 proteinMapped = true;
316 mappedDna.add(cdnaSeq);
317 mappedProtein.add(aaSeq);
323 proteinAlignment.addCodonFrame(acf);
326 return mappingPerformed;
330 * Answers true if the mappings include one between the given (dataset)
333 public static boolean mappingExists(Set<AlignedCodonFrame> set,
334 SequenceI aaSeq, SequenceI cdnaSeq)
338 for (AlignedCodonFrame acf : set)
340 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
350 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
351 * must be three times the length of the protein, possibly after ignoring
352 * start and/or stop codons, and must translate to the protein. Returns null
353 * if no mapping is determined.
359 public static MapList mapProteinToCdna(SequenceI proteinSeq,
363 * Here we handle either dataset sequence set (desktop) or absent (applet).
364 * Use only the char[] form of the sequence to avoid creating possibly large
367 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
368 char[] aaSeqChars = proteinDataset != null ? proteinDataset
369 .getSequence() : proteinSeq.getSequence();
370 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
371 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
372 : cdnaSeq.getSequence();
373 if (aaSeqChars == null || cdnaSeqChars == null)
379 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
381 final int mappedLength = 3 * aaSeqChars.length;
382 int cdnaLength = cdnaSeqChars.length;
384 int cdnaEnd = cdnaLength;
385 final int proteinStart = 1;
386 final int proteinEnd = aaSeqChars.length;
389 * If lengths don't match, try ignoring stop codon.
391 if (cdnaLength != mappedLength && cdnaLength > 2)
393 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
395 for (String stop : ResidueProperties.STOP)
397 if (lastCodon.equals(stop))
407 * If lengths still don't match, try ignoring start codon.
409 if (cdnaLength != mappedLength
411 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
413 ResidueProperties.START))
419 if (cdnaLength != mappedLength)
423 if (!translatesAs(cdnaSeqChars, cdnaStart - 1, aaSeqChars))
427 MapList map = new MapList(new int[]
428 { cdnaStart, cdnaEnd }, new int[]
429 { proteinStart, proteinEnd }, 3, 1);
434 * Test whether the given cdna sequence, starting at the given offset,
435 * translates to the given amino acid sequence, using the standard translation
436 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
438 * @param cdnaSeqChars
443 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
447 for (int i = cdnaStart; i < cdnaSeqChars.length - 2
448 && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
450 String codon = String.valueOf(cdnaSeqChars, i, 3);
451 final String translated = ResidueProperties.codonTranslate(
454 * ? allow X in protein to match untranslatable in dna ?
456 final char aaRes = aaSeqChars[aaResidue];
457 if ((translated == null || "STOP".equals(translated)) && aaRes == 'X')
461 if (translated == null
462 || !(aaRes == translated.charAt(0)))
465 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
466 // + codon + "(" + translated + ") != " + aaRes));
470 // fail if we didn't match all of the aa sequence
471 return (aaResidue == aaSeqChars.length);
475 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
476 * currently assumes that we are aligning cDNA to match protein.
479 * the sequence to be realigned
481 * the alignment whose sequence alignment is to be 'copied'
483 * character string represent a gap in the realigned sequence
484 * @param preserveUnmappedGaps
485 * @param preserveMappedGaps
486 * @return true if the sequence was realigned, false if it could not be
488 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
489 String gap, boolean preserveMappedGaps,
490 boolean preserveUnmappedGaps)
493 * Get any mappings from the source alignment to the target (dataset) sequence.
495 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
496 // all mappings. Would it help to constrain this?
497 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
498 if (mappings == null || mappings.isEmpty())
504 * Locate the aligned source sequence whose dataset sequence is mapped. We
505 * just take the first match here (as we can't align cDNA like more than one
508 SequenceI alignFrom = null;
509 AlignedCodonFrame mapping = null;
510 for (AlignedCodonFrame mp : mappings)
512 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
513 if (alignFrom != null)
520 if (alignFrom == null)
524 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
525 preserveMappedGaps, preserveUnmappedGaps);
530 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
531 * match residues and codons. Flags control whether existing gaps in unmapped
532 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
533 * and exon are only retained if both flags are set.
540 * @param preserveUnmappedGaps
541 * @param preserveMappedGaps
543 public static void alignSequenceAs(SequenceI alignTo,
545 AlignedCodonFrame mapping, String myGap, char sourceGap,
546 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
548 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
549 final char[] thisSeq = alignTo.getSequence();
550 final char[] thatAligned = alignFrom.getSequence();
551 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
553 // aligned and dataset sequence positions, all base zero
557 int basesWritten = 0;
558 char myGapChar = myGap.charAt(0);
559 int ratio = myGap.length();
562 * Traverse the aligned protein sequence.
564 int sourceGapMappedLength = 0;
565 boolean inExon = false;
566 for (char sourceChar : thatAligned)
568 if (sourceChar == sourceGap)
570 sourceGapMappedLength += ratio;
575 * Found a residue. Locate its mapped codon (start) position.
578 // Note mapping positions are base 1, our sequence positions base 0
579 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
581 if (mappedPos == null)
584 * Abort realignment if unmapped protein. Or could ignore it??
586 System.err.println("Can't align: no codon mapping to residue "
587 + sourceDsPos + "(" + sourceChar + ")");
591 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
592 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
593 StringBuilder trailingCopiedGap = new StringBuilder();
596 * Copy dna sequence up to and including this codon. Optionally, include
597 * gaps before the codon starts (in introns) and/or after the codon starts
600 * Note this only works for 'linear' splicing, not reverse or interleaved.
601 * But then 'align dna as protein' doesn't make much sense otherwise.
603 int intronLength = 0;
604 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
606 final char c = thisSeq[thisSeqPos++];
611 if (basesWritten < mappedCodonStart)
614 * Found an unmapped (intron) base. First add in any preceding gaps
617 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
619 thisAligned.append(trailingCopiedGap.toString());
620 intronLength += trailingCopiedGap.length();
621 trailingCopiedGap = new StringBuilder();
628 final boolean startOfCodon = basesWritten == mappedCodonStart;
629 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
630 preserveUnmappedGaps, sourceGapMappedLength, inExon,
631 trailingCopiedGap.length(), intronLength, startOfCodon);
632 for (int i = 0; i < gapsToAdd; i++)
634 thisAligned.append(myGapChar);
636 sourceGapMappedLength = 0;
639 thisAligned.append(c);
640 trailingCopiedGap = new StringBuilder();
644 if (inExon && preserveMappedGaps)
646 trailingCopiedGap.append(myGapChar);
648 else if (!inExon && preserveUnmappedGaps)
650 trailingCopiedGap.append(myGapChar);
657 * At end of protein sequence. Copy any remaining dna sequence, optionally
658 * including (intron) gaps. We do not copy trailing gaps in protein.
660 while (thisSeqPos < thisSeq.length)
662 final char c = thisSeq[thisSeqPos++];
663 if (c != myGapChar || preserveUnmappedGaps)
665 thisAligned.append(c);
670 * All done aligning, set the aligned sequence.
672 alignTo.setSequence(new String(thisAligned));
676 * Helper method to work out how many gaps to insert when realigning.
678 * @param preserveMappedGaps
679 * @param preserveUnmappedGaps
680 * @param sourceGapMappedLength
682 * @param trailingCopiedGap
683 * @param intronLength
684 * @param startOfCodon
687 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
688 boolean preserveUnmappedGaps, int sourceGapMappedLength,
689 boolean inExon, int trailingGapLength,
690 int intronLength, final boolean startOfCodon)
696 * Reached start of codon. Ignore trailing gaps in intron unless we are
697 * preserving gaps in both exon and intron. Ignore them anyway if the
698 * protein alignment introduces a gap at least as large as the intronic
701 if (inExon && !preserveMappedGaps)
703 trailingGapLength = 0;
705 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
707 trailingGapLength = 0;
711 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
715 if (intronLength + trailingGapLength <= sourceGapMappedLength)
717 gapsToAdd = sourceGapMappedLength - intronLength;
721 gapsToAdd = Math.min(intronLength + trailingGapLength
722 - sourceGapMappedLength, trailingGapLength);
729 * second or third base of codon; check for any gaps in dna
731 if (!preserveMappedGaps)
733 trailingGapLength = 0;
735 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
741 * Returns a list of sequences mapped from the given sequences and aligned
742 * (gapped) in the same way. For example, the cDNA for aligned protein, where
743 * a single gap in protein generates three gaps in cDNA.
746 * @param gapCharacter
750 public static List<SequenceI> getAlignedTranslation(
751 List<SequenceI> sequences, char gapCharacter,
752 Set<AlignedCodonFrame> mappings)
754 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
756 for (SequenceI seq : sequences)
758 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
760 alignedSeqs.addAll(mapped);
766 * Returns sequences aligned 'like' the source sequence, as mapped by the
767 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
768 * will support 1-to-many as well.
771 * @param gapCharacter
775 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
776 char gapCharacter, Set<AlignedCodonFrame> mappings)
778 List<SequenceI> result = new ArrayList<SequenceI>();
779 for (AlignedCodonFrame mapping : mappings)
781 if (mapping.involvesSequence(seq))
783 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
794 * Returns the translation of 'seq' (as held in the mapping) with
795 * corresponding alignment (gaps).
798 * @param gapCharacter
802 protected static SequenceI getAlignedTranslation(SequenceI seq,
803 char gapCharacter, AlignedCodonFrame mapping)
805 String gap = String.valueOf(gapCharacter);
806 boolean toDna = false;
808 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
811 // mapping is from protein to nucleotide
813 // should ideally get gap count ratio from mapping
814 gap = String.valueOf(new char[]
815 { gapCharacter, gapCharacter, gapCharacter });
819 // mapping is from nucleotide to protein
820 mapTo = mapping.getAaForDnaSeq(seq);
823 StringBuilder newseq = new StringBuilder(seq.getLength()
826 int residueNo = 0; // in seq, base 1
827 int[] phrase = new int[fromRatio];
828 int phraseOffset = 0;
830 boolean first = true;
831 final Sequence alignedSeq = new Sequence("", "");
833 for (char c : seq.getSequence())
835 if (c == gapCharacter)
838 if (gapWidth >= fromRatio)
846 phrase[phraseOffset++] = residueNo + 1;
847 if (phraseOffset == fromRatio)
850 * Have read a whole codon (or protein residue), now translate: map
851 * source phrase to positions in target sequence add characters at
852 * these positions to newseq Note mapping positions are base 1, our
853 * sequence positions base 0.
855 SearchResults sr = new SearchResults();
856 for (int pos : phrase)
858 mapping.markMappedRegion(seq, pos, sr);
860 newseq.append(sr.toString());
864 // Hack: Copy sequence dataset, name and description from
865 // SearchResults.match[0].sequence
866 // TODO? carry over sequence names from original 'complement'
868 SequenceI mappedTo = sr.getResultSequence(0);
869 alignedSeq.setName(mappedTo.getName());
870 alignedSeq.setDescription(mappedTo.getDescription());
871 alignedSeq.setDatasetSequence(mappedTo);
878 alignedSeq.setSequence(newseq.toString());
883 * Realigns the given protein to match the alignment of the dna, using codon
884 * mappings to translate aligned codon positions to protein residues.
887 * the alignment whose sequences are realigned by this method
889 * the dna alignment whose alignment we are 'copying'
890 * @return the number of sequences that were realigned
892 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
894 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
897 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
898 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
899 * comparator keeps the codon positions ordered.
901 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, String>>(
902 new CodonComparator());
903 for (SequenceI dnaSeq : dna.getSequences())
905 for (AlignedCodonFrame mapping : mappings)
907 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
908 SequenceI prot = mapping.findAlignedSequence(
909 dnaSeq.getDatasetSequence(), protein);
912 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
913 seqMap, alignedCodons);
917 return alignProteinAs(protein, alignedCodons);
921 * Update the aligned protein sequences to match the codon alignments given in
925 * @param alignedCodons
926 * an ordered map of codon positions (columns), with sequence/peptide
927 * values present in each column
930 protected static int alignProteinAs(AlignmentI protein,
931 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
934 * Prefill aligned sequences with gaps before inserting aligned protein
937 int alignedWidth = alignedCodons.size();
938 char[] gaps = new char[alignedWidth];
939 Arrays.fill(gaps, protein.getGapCharacter());
940 String allGaps = String.valueOf(gaps);
941 for (SequenceI seq : protein.getSequences())
943 seq.setSequence(allGaps);
947 for (AlignedCodon codon : alignedCodons.keySet())
949 final Map<SequenceI, String> columnResidues = alignedCodons.get(codon);
950 for (Entry<SequenceI, String> entry : columnResidues
953 // place translated codon at its column position in sequence
954 entry.getKey().getSequence()[column] = entry.getValue().charAt(0);
962 * Populate the map of aligned codons by traversing the given sequence
963 * mapping, locating the aligned positions of mapped codons, and adding those
964 * positions and their translation products to the map.
967 * the aligned sequence we are mapping from
969 * the sequence to be aligned to the codons
971 * the gap character in the dna sequence
973 * a mapping to a sequence translation
974 * @param alignedCodons
975 * the map we are building up
977 static void addCodonPositions(SequenceI dna, SequenceI protein,
980 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
982 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
983 while (codons.hasNext())
985 AlignedCodon codon = codons.next();
986 Map<SequenceI, String> seqProduct = alignedCodons.get(codon);
987 if (seqProduct == null)
989 seqProduct = new HashMap<SequenceI, String>();
990 alignedCodons.put(codon, seqProduct);
992 seqProduct.put(protein, codon.product);
997 * Returns true if a cDNA/Protein mapping either exists, or could be made,
998 * between at least one pair of sequences in the two alignments. Currently,
1001 * <li>One alignment must be nucleotide, and the other protein</li>
1002 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1003 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1004 * <li>The translation may ignore start and stop codons if present in the
1012 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1015 * Require one nucleotide and one protein
1017 if (al1.isNucleotide() == al2.isNucleotide())
1021 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1022 AlignmentI protein = dna == al1 ? al2 : al1;
1023 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
1024 for (SequenceI dnaSeq : dna.getSequences())
1026 for (SequenceI proteinSeq : protein.getSequences())
1028 if (isMappable(dnaSeq, proteinSeq, mappings))
1038 * Returns true if the dna sequence is mapped, or could be mapped, to the
1046 public static boolean isMappable(SequenceI dnaSeq, SequenceI proteinSeq,
1047 Set<AlignedCodonFrame> mappings)
1049 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq.getDatasetSequence();
1050 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1051 : proteinSeq.getDatasetSequence();
1056 for (AlignedCodonFrame mapping : mappings) {
1057 if ( proteinDs == mapping.getAaForDnaSeq(dnaDs)) {
1063 * Just try to make a mapping (it is not yet stored), test whether
1066 return mapProteinToCdna(proteinDs, dnaDs) != null;
1070 * Finds any reference annotations associated with the sequences in
1071 * sequenceScope, that are not already added to the alignment, and adds them
1072 * to the 'candidates' map. Also populates a lookup table of annotation
1073 * labels, keyed by calcId, for use in constructing tooltips or the like.
1075 * @param sequenceScope
1076 * the sequences to scan for reference annotations
1077 * @param labelForCalcId
1078 * (optional) map to populate with label for calcId
1080 * map to populate with annotations for sequence
1082 * the alignment to check for presence of annotations
1084 public static void findAddableReferenceAnnotations(
1085 List<SequenceI> sequenceScope, Map<String, String> labelForCalcId,
1086 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1089 if (sequenceScope == null)
1095 * For each sequence in scope, make a list of any annotations on the
1096 * underlying dataset sequence which are not already on the alignment.
1098 * Add to a map of { alignmentSequence, <List of annotations to add> }
1100 for (SequenceI seq : sequenceScope)
1102 SequenceI dataset = seq.getDatasetSequence();
1103 if (dataset == null)
1107 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1108 if (datasetAnnotations == null)
1112 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1113 for (AlignmentAnnotation dsann : datasetAnnotations)
1116 * Find matching annotations on the alignment. If none is found, then
1117 * add this annotation to the list of 'addable' annotations for this
1120 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1121 .findAnnotations(seq, dsann.getCalcId(),
1123 if (!matchedAlignmentAnnotations.iterator().hasNext())
1126 if (labelForCalcId != null)
1128 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1133 * Save any addable annotations for this sequence
1135 if (!result.isEmpty())
1137 candidates.put(seq, result);
1143 * Adds annotations to the top of the alignment annotations, in the same order
1144 * as their related sequences.
1146 * @param annotations
1147 * the annotations to add
1149 * the alignment to add them to
1150 * @param selectionGroup
1151 * current selection group (or null if none)
1153 public static void addReferenceAnnotations(
1154 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1155 final AlignmentI alignment, final SequenceGroup selectionGroup)
1157 for (SequenceI seq : annotations.keySet())
1159 for (AlignmentAnnotation ann : annotations.get(seq))
1161 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1163 int endRes = ann.annotations.length;
1164 if (selectionGroup != null)
1166 startRes = selectionGroup.getStartRes();
1167 endRes = selectionGroup.getEndRes();
1169 copyAnn.restrict(startRes, endRes);
1172 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1173 * original annotation is already on the sequence.
1175 if (!seq.hasAnnotation(ann))
1177 seq.addAlignmentAnnotation(copyAnn);
1180 copyAnn.adjustForAlignment();
1181 // add to the alignment and set visible
1182 alignment.addAnnotation(copyAnn);
1183 copyAnn.visible = true;
1189 * Set visibility of alignment annotations of specified types (labels), for
1190 * specified sequences. This supports controls like
1191 * "Show all secondary structure", "Hide all Temp factor", etc.
1193 * @al the alignment to scan for annotations
1195 * the types (labels) of annotations to be updated
1196 * @param forSequences
1197 * if not null, only annotations linked to one of these sequences are
1198 * in scope for update; if null, acts on all sequence annotations
1200 * if this flag is true, 'types' is ignored (label not checked)
1202 * if true, set visibility on, else set off
1204 public static void showOrHideSequenceAnnotations(AlignmentI al,
1205 Collection<String> types, List<SequenceI> forSequences,
1206 boolean anyType, boolean doShow)
1208 for (AlignmentAnnotation aa : al
1209 .getAlignmentAnnotation())
1211 if (anyType || types.contains(aa.label))
1213 if ((aa.sequenceRef != null)
1214 && (forSequences == null || forSequences
1215 .contains(aa.sequenceRef)))
1217 aa.visible = doShow;
1224 * Returns true if either sequence has a cross-reference to the other
1230 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1232 // Note: moved here from class CrossRef as the latter class has dependencies
1233 // not availability to the applet's classpath
1234 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1238 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1239 * that sequence name is structured as Source|AccessId.
1245 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1247 if (seq1 == null || seq2 == null)
1251 String name = seq2.getName();
1252 final DBRefEntry[] xrefs = seq1.getDBRef();
1255 for (DBRefEntry xref : xrefs)
1257 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1258 // case-insensitive test, consistent with DBRefEntry.equalRef()
1259 if (xrefName.equalsIgnoreCase(name))
1269 * Constructs an alignment consisting of the mapped exon regions in the given
1270 * nucleotide sequences, and updates mappings to match.
1273 * aligned dna sequences
1275 * from dna to protein; these are replaced with new mappings
1276 * @return an alignment whose sequences are the exon-only parts of the dna
1277 * sequences (or null if no exons are found)
1279 public static AlignmentI makeExonAlignment(SequenceI[] dna,
1280 Set<AlignedCodonFrame> mappings)
1282 Set<AlignedCodonFrame> newMappings = new LinkedHashSet<AlignedCodonFrame>();
1283 List<SequenceI> exonSequences = new ArrayList<SequenceI>();
1285 for (SequenceI dnaSeq : dna)
1287 final SequenceI ds = dnaSeq.getDatasetSequence();
1288 List<AlignedCodonFrame> seqMappings = MappingUtils
1289 .findMappingsForSequence(ds, mappings);
1290 for (AlignedCodonFrame acf : seqMappings)
1292 AlignedCodonFrame newMapping = new AlignedCodonFrame();
1293 final List<SequenceI> mappedExons = makeExonSequences(ds, acf,
1295 if (!mappedExons.isEmpty())
1297 exonSequences.addAll(mappedExons);
1298 newMappings.add(newMapping);
1302 AlignmentI al = new Alignment(
1303 exonSequences.toArray(new SequenceI[exonSequences.size()]));
1304 al.setDataset(null);
1307 * Replace the old mappings with the new ones
1310 mappings.addAll(newMappings);
1316 * Helper method to make exon-only sequences and populate their mappings to
1319 * For example, if ggCCaTTcGAg has mappings [3, 4, 6, 7, 9, 10] to protein
1320 * then generate a sequence CCTTGA with mapping [1, 6] to the same protein
1323 * Typically eukaryotic dna will include exons encoding for a single peptide
1324 * sequence i.e. return a single result. Bacterial dna may have overlapping
1325 * exon mappings coding for multiple peptides so return multiple results
1326 * (example EMBL KF591215).
1329 * a dna dataset sequence
1331 * containing one or more mappings of the sequence to protein
1333 * the new mapping to populate, from the exon-only sequences to their
1334 * mapped protein sequences
1337 protected static List<SequenceI> makeExonSequences(SequenceI dnaSeq,
1338 AlignedCodonFrame mapping, AlignedCodonFrame newMapping)
1340 List<SequenceI> exonSequences = new ArrayList<SequenceI>();
1341 List<Mapping> seqMappings = mapping.getMappingsForSequence(dnaSeq);
1342 final char[] dna = dnaSeq.getSequence();
1343 for (Mapping seqMapping : seqMappings)
1345 StringBuilder newSequence = new StringBuilder(dnaSeq.getLength());
1348 * Get the codon regions as { [2, 5], [7, 12], [14, 14] etc }
1350 final List<int[]> dnaExonRanges = seqMapping.getMap().getFromRanges();
1351 for (int[] range : dnaExonRanges)
1353 for (int pos = range[0]; pos <= range[1]; pos++)
1355 newSequence.append(dna[pos - 1]);
1359 SequenceI exon = new Sequence(dnaSeq.getName(),
1360 newSequence.toString());
1363 * Locate any xrefs to CDS database on the protein product and attach to
1364 * the CDS sequence. Also add as a sub-token of the sequence name.
1366 // default to "CDS" if we can't locate an actual gene id
1367 String cdsAccId = FeatureProperties
1368 .getCodingFeature(DBRefSource.EMBL);
1369 DBRefEntry[] cdsRefs = DBRefUtils.selectRefs(seqMapping.getTo()
1370 .getDBRef(), DBRefSource.CODINGDBS);
1371 if (cdsRefs != null)
1373 for (DBRefEntry cdsRef : cdsRefs)
1375 exon.addDBRef(new DBRefEntry(cdsRef));
1376 cdsAccId = cdsRef.getAccessionId();
1379 exon.setName(exon.getName() + "|" + cdsAccId);
1380 exon.createDatasetSequence();
1383 * Build new mappings - from the same protein regions, but now to
1386 List<int[]> exonRange = new ArrayList<int[]>();
1387 exonRange.add(new int[]
1388 { 1, newSequence.length() });
1389 MapList map = new MapList(exonRange, seqMapping.getMap()
1392 newMapping.addMap(exon.getDatasetSequence(), seqMapping.getTo(), map);
1393 MapList cdsToDnaMap = new MapList(dnaExonRanges, exonRange, 1, 1);
1394 newMapping.addMap(dnaSeq, exon.getDatasetSequence(), cdsToDnaMap);
1396 exonSequences.add(exon);
1398 return exonSequences;