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.Mapping;
32 import jalview.datamodel.SearchResults;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceGroup;
35 import jalview.datamodel.SequenceI;
36 import jalview.schemes.ResidueProperties;
37 import jalview.util.DBRefUtils;
38 import jalview.util.MapList;
39 import jalview.util.MappingUtils;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collection;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.Iterator;
47 import java.util.LinkedHashMap;
48 import java.util.LinkedHashSet;
49 import java.util.List;
51 import java.util.Map.Entry;
53 import java.util.TreeMap;
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 final int newSeqStart = newSeq.getStart() - 1;
81 if (newSeqStart > maxoffset
82 && newSeq.getDatasetSequence().getStart() < s.getStart())
84 maxoffset = newSeqStart;
90 maxoffset = Math.min(maxoffset, flankSize);
94 * now add offset left and right to create an expanded alignment
96 for (SequenceI s : sq)
99 while (ds.getDatasetSequence() != null)
101 ds = ds.getDatasetSequence();
103 int s_end = s.findPosition(s.getStart() + s.getLength());
104 // find available flanking residues for sequence
105 int ustream_ds = s.getStart() - ds.getStart();
106 int dstream_ds = ds.getEnd() - s_end;
108 // build new flanked sequence
110 // compute gap padding to start of flanking sequence
111 int offset = maxoffset - ustream_ds;
113 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
116 if (flankSize < ustream_ds)
118 // take up to flankSize residues
119 offset = maxoffset - flankSize;
120 ustream_ds = flankSize;
122 if (flankSize <= dstream_ds)
124 dstream_ds = flankSize - 1;
127 // TODO use Character.toLowerCase to avoid creating String objects?
128 char[] upstream = new String(ds.getSequence(s.getStart() - 1
129 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
130 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
131 + dstream_ds)).toLowerCase().toCharArray();
132 char[] coreseq = s.getSequence();
133 char[] nseq = new char[offset + upstream.length + downstream.length
135 char c = core.getGapCharacter();
138 for (; p < offset; p++)
143 System.arraycopy(upstream, 0, nseq, p, upstream.length);
144 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
146 System.arraycopy(downstream, 0, nseq, p + coreseq.length
147 + upstream.length, downstream.length);
148 s.setSequence(new String(nseq));
149 s.setStart(s.getStart() - ustream_ds);
150 s.setEnd(s_end + downstream.length);
152 AlignmentI newAl = new jalview.datamodel.Alignment(
153 sq.toArray(new SequenceI[0]));
154 for (SequenceI s : sq)
156 if (s.getAnnotation() != null)
158 for (AlignmentAnnotation aa : s.getAnnotation())
160 aa.adjustForAlignment(); // JAL-1712 fix
161 newAl.addAnnotation(aa);
165 newAl.setDataset(core.getDataset());
170 * Returns the index (zero-based position) of a sequence in an alignment, or
177 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
181 for (SequenceI alSeq : al.getSequences())
194 * Returns a map of lists of sequences in the alignment, keyed by sequence
195 * name. For use in mapping between different alignment views of the same
198 * @see jalview.datamodel.AlignmentI#getSequencesByName()
200 public static Map<String, List<SequenceI>> getSequencesByName(
203 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
204 for (SequenceI seq : al.getSequences())
206 String name = seq.getName();
209 List<SequenceI> seqs = theMap.get(name);
212 seqs = new ArrayList<SequenceI>();
213 theMap.put(name, seqs);
222 * Build mapping of protein to cDNA alignment. Mappings are made between
223 * sequences where the cDNA translates to the protein sequence. Any new
224 * mappings are added to the protein alignment. Returns true if any mappings
225 * either already exist or were added, else false.
227 * @param proteinAlignment
228 * @param cdnaAlignment
231 public static boolean mapProteinAlignmentToCdna(
232 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
234 if (proteinAlignment == null || cdnaAlignment == null)
239 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
240 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
243 * First pass - map sequences where cross-references exist. This include
244 * 1-to-many mappings to support, for example, variant cDNA.
246 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
247 cdnaAlignment, mappedDna, mappedProtein, true);
250 * Second pass - map sequences where no cross-references exist. This only
251 * does 1-to-1 mappings and assumes corresponding sequences are in the same
252 * order in the alignments.
254 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
255 mappedDna, mappedProtein, false);
256 return mappingPerformed;
260 * Make mappings between compatible sequences (where the cDNA translation
261 * matches the protein).
263 * @param proteinAlignment
264 * @param cdnaAlignment
266 * a set of mapped DNA sequences (to add to)
267 * @param mappedProtein
268 * a set of mapped Protein sequences (to add to)
270 * if true, only map sequences where xrefs exist
273 protected static boolean mapProteinToCdna(
274 final AlignmentI proteinAlignment,
275 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
276 Set<SequenceI> mappedProtein, boolean xrefsOnly)
278 boolean mappingExistsOrAdded = false;
279 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
280 for (SequenceI aaSeq : thisSeqs)
282 boolean proteinMapped = false;
283 AlignedCodonFrame acf = new AlignedCodonFrame();
285 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
288 * Always try to map if sequences have xref to each other; this supports
289 * variant cDNA or alternative splicing for a protein sequence.
291 * If no xrefs, try to map progressively, assuming that alignments have
292 * mappable sequences in corresponding order. These are not
293 * many-to-many, as that would risk mixing species with similar cDNA
296 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
302 * Don't map non-xrefd sequences more than once each. This heuristic
303 * allows us to pair up similar sequences in ordered alignments.
306 && (mappedProtein.contains(aaSeq) || mappedDna
311 if (mappingExists(proteinAlignment.getCodonFrames(),
312 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
314 mappingExistsOrAdded = true;
318 MapList map = mapProteinSequenceToCdna(aaSeq, cdnaSeq);
321 acf.addMap(cdnaSeq, aaSeq, map);
322 mappingExistsOrAdded = true;
323 proteinMapped = true;
324 mappedDna.add(cdnaSeq);
325 mappedProtein.add(aaSeq);
331 proteinAlignment.addCodonFrame(acf);
334 return mappingExistsOrAdded;
338 * Answers true if the mappings include one between the given (dataset)
341 public static boolean mappingExists(Set<AlignedCodonFrame> set,
342 SequenceI aaSeq, SequenceI cdnaSeq)
346 for (AlignedCodonFrame acf : set)
348 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
358 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
359 * must be three times the length of the protein, possibly after ignoring
360 * start and/or stop codons, and must translate to the protein. Returns null
361 * if no mapping is determined.
367 public static MapList mapProteinSequenceToCdna(SequenceI proteinSeq,
371 * Here we handle either dataset sequence set (desktop) or absent (applet).
372 * Use only the char[] form of the sequence to avoid creating possibly large
375 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
376 char[] aaSeqChars = proteinDataset != null ? proteinDataset
377 .getSequence() : proteinSeq.getSequence();
378 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
379 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
380 : cdnaSeq.getSequence();
381 if (aaSeqChars == null || cdnaSeqChars == null)
387 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
389 final int mappedLength = 3 * aaSeqChars.length;
390 int cdnaLength = cdnaSeqChars.length;
391 int cdnaStart = cdnaSeq.getStart();
392 int cdnaEnd = cdnaSeq.getEnd();
393 final int proteinStart = proteinSeq.getStart();
394 final int proteinEnd = proteinSeq.getEnd();
397 * If lengths don't match, try ignoring stop codon.
399 if (cdnaLength != mappedLength && cdnaLength > 2)
401 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
403 for (String stop : ResidueProperties.STOP)
405 if (lastCodon.equals(stop))
415 * If lengths still don't match, try ignoring start codon.
418 if (cdnaLength != mappedLength
420 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
421 .equals(ResidueProperties.START))
428 if (cdnaLength != mappedLength)
432 if (!translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
436 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[] {
437 proteinStart, proteinEnd }, 3, 1);
442 * Test whether the given cdna sequence, starting at the given offset,
443 * translates to the given amino acid sequence, using the standard translation
444 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
446 * @param cdnaSeqChars
451 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
454 if (cdnaSeqChars == null || aaSeqChars == null)
460 for (int i = cdnaStart; i < cdnaSeqChars.length - 2
461 && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
463 String codon = String.valueOf(cdnaSeqChars, i, 3);
464 final String translated = ResidueProperties.codonTranslate(codon);
466 * allow * in protein to match untranslatable in dna
468 final char aaRes = aaSeqChars[aaResidue];
469 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
473 if (translated == null || !(aaRes == translated.charAt(0)))
476 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
477 // + codon + "(" + translated + ") != " + aaRes));
481 // fail if we didn't match all of the aa sequence
482 return (aaResidue == aaSeqChars.length);
486 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
487 * currently assumes that we are aligning cDNA to match protein.
490 * the sequence to be realigned
492 * the alignment whose sequence alignment is to be 'copied'
494 * character string represent a gap in the realigned sequence
495 * @param preserveUnmappedGaps
496 * @param preserveMappedGaps
497 * @return true if the sequence was realigned, false if it could not be
499 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
500 String gap, boolean preserveMappedGaps,
501 boolean preserveUnmappedGaps)
504 * Get any mappings from the source alignment to the target (dataset)
507 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
508 // all mappings. Would it help to constrain this?
509 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
510 if (mappings == null || mappings.isEmpty())
516 * Locate the aligned source sequence whose dataset sequence is mapped. We
517 * just take the first match here (as we can't align cDNA like more than one
520 SequenceI alignFrom = null;
521 AlignedCodonFrame mapping = null;
522 for (AlignedCodonFrame mp : mappings)
524 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
525 if (alignFrom != null)
532 if (alignFrom == null)
536 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
537 preserveMappedGaps, preserveUnmappedGaps);
542 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
543 * match residues and codons. Flags control whether existing gaps in unmapped
544 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
545 * and exon are only retained if both flags are set.
552 * @param preserveUnmappedGaps
553 * @param preserveMappedGaps
555 public static void alignSequenceAs(SequenceI alignTo,
556 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
557 char sourceGap, boolean preserveMappedGaps,
558 boolean preserveUnmappedGaps)
560 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
561 final char[] thisSeq = alignTo.getSequence();
562 final char[] thatAligned = alignFrom.getSequence();
563 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
565 // aligned and dataset sequence positions, all base zero
569 int basesWritten = 0;
570 char myGapChar = myGap.charAt(0);
571 int ratio = myGap.length();
574 * Traverse the aligned protein sequence.
576 int fromOffset = alignFrom.getStart() - 1;
577 int toOffset = alignTo.getStart() - 1;
578 int sourceGapMappedLength = 0;
579 boolean inExon = false;
580 for (char sourceChar : thatAligned)
582 if (sourceChar == sourceGap)
584 sourceGapMappedLength += ratio;
589 * Found a residue. Locate its mapped codon (start) position.
592 // Note mapping positions are base 1, our sequence positions base 0
593 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
594 sourceDsPos + fromOffset);
595 if (mappedPos == null)
598 * Abort realignment if unmapped protein. Or could ignore it??
600 System.err.println("Can't align: no codon mapping to residue "
601 + sourceDsPos + "(" + sourceChar + ")");
605 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
606 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
607 StringBuilder trailingCopiedGap = new StringBuilder();
610 * Copy dna sequence up to and including this codon. Optionally, include
611 * gaps before the codon starts (in introns) and/or after the codon starts
614 * Note this only works for 'linear' splicing, not reverse or interleaved.
615 * But then 'align dna as protein' doesn't make much sense otherwise.
617 int intronLength = 0;
618 while (basesWritten + toOffset < mappedCodonEnd
619 && thisSeqPos < thisSeq.length)
621 final char c = thisSeq[thisSeqPos++];
625 int sourcePosition = basesWritten + toOffset;
626 if (sourcePosition < mappedCodonStart)
629 * Found an unmapped (intron) base. First add in any preceding gaps
632 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
634 thisAligned.append(trailingCopiedGap.toString());
635 intronLength += trailingCopiedGap.length();
636 trailingCopiedGap = new StringBuilder();
643 final boolean startOfCodon = sourcePosition == mappedCodonStart;
644 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
645 preserveUnmappedGaps, sourceGapMappedLength, inExon,
646 trailingCopiedGap.length(), intronLength, startOfCodon);
647 for (int i = 0; i < gapsToAdd; i++)
649 thisAligned.append(myGapChar);
651 sourceGapMappedLength = 0;
654 thisAligned.append(c);
655 trailingCopiedGap = new StringBuilder();
659 if (inExon && preserveMappedGaps)
661 trailingCopiedGap.append(myGapChar);
663 else if (!inExon && preserveUnmappedGaps)
665 trailingCopiedGap.append(myGapChar);
672 * At end of protein sequence. Copy any remaining dna sequence, optionally
673 * including (intron) gaps. We do not copy trailing gaps in protein.
675 while (thisSeqPos < thisSeq.length)
677 final char c = thisSeq[thisSeqPos++];
678 if (c != myGapChar || preserveUnmappedGaps)
680 thisAligned.append(c);
685 * All done aligning, set the aligned sequence.
687 alignTo.setSequence(new String(thisAligned));
691 * Helper method to work out how many gaps to insert when realigning.
693 * @param preserveMappedGaps
694 * @param preserveUnmappedGaps
695 * @param sourceGapMappedLength
697 * @param trailingCopiedGap
698 * @param intronLength
699 * @param startOfCodon
702 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
703 boolean preserveUnmappedGaps, int sourceGapMappedLength,
704 boolean inExon, int trailingGapLength, int intronLength,
705 final boolean startOfCodon)
711 * Reached start of codon. Ignore trailing gaps in intron unless we are
712 * preserving gaps in both exon and intron. Ignore them anyway if the
713 * protein alignment introduces a gap at least as large as the intronic
716 if (inExon && !preserveMappedGaps)
718 trailingGapLength = 0;
720 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
722 trailingGapLength = 0;
726 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
730 if (intronLength + trailingGapLength <= sourceGapMappedLength)
732 gapsToAdd = sourceGapMappedLength - intronLength;
736 gapsToAdd = Math.min(intronLength + trailingGapLength
737 - sourceGapMappedLength, trailingGapLength);
744 * second or third base of codon; check for any gaps in dna
746 if (!preserveMappedGaps)
748 trailingGapLength = 0;
750 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
756 * Returns a list of sequences mapped from the given sequences and aligned
757 * (gapped) in the same way. For example, the cDNA for aligned protein, where
758 * a single gap in protein generates three gaps in cDNA.
761 * @param gapCharacter
765 public static List<SequenceI> getAlignedTranslation(
766 List<SequenceI> sequences, char gapCharacter,
767 Set<AlignedCodonFrame> mappings)
769 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
771 for (SequenceI seq : sequences)
773 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
775 alignedSeqs.addAll(mapped);
781 * Returns sequences aligned 'like' the source sequence, as mapped by the
782 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
783 * will support 1-to-many as well.
786 * @param gapCharacter
790 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
791 char gapCharacter, Set<AlignedCodonFrame> mappings)
793 List<SequenceI> result = new ArrayList<SequenceI>();
794 for (AlignedCodonFrame mapping : mappings)
796 if (mapping.involvesSequence(seq))
798 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
809 * Returns the translation of 'seq' (as held in the mapping) with
810 * corresponding alignment (gaps).
813 * @param gapCharacter
817 protected static SequenceI getAlignedTranslation(SequenceI seq,
818 char gapCharacter, AlignedCodonFrame mapping)
820 String gap = String.valueOf(gapCharacter);
821 boolean toDna = false;
823 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
826 // mapping is from protein to nucleotide
828 // should ideally get gap count ratio from mapping
829 gap = String.valueOf(new char[] { gapCharacter, gapCharacter,
834 // mapping is from nucleotide to protein
835 mapTo = mapping.getAaForDnaSeq(seq);
838 StringBuilder newseq = new StringBuilder(seq.getLength()
841 int residueNo = 0; // in seq, base 1
842 int[] phrase = new int[fromRatio];
843 int phraseOffset = 0;
845 boolean first = true;
846 final Sequence alignedSeq = new Sequence("", "");
848 for (char c : seq.getSequence())
850 if (c == gapCharacter)
853 if (gapWidth >= fromRatio)
861 phrase[phraseOffset++] = residueNo + 1;
862 if (phraseOffset == fromRatio)
865 * Have read a whole codon (or protein residue), now translate: map
866 * source phrase to positions in target sequence add characters at
867 * these positions to newseq Note mapping positions are base 1, our
868 * sequence positions base 0.
870 SearchResults sr = new SearchResults();
871 for (int pos : phrase)
873 mapping.markMappedRegion(seq, pos, sr);
875 newseq.append(sr.getCharacters());
879 // Hack: Copy sequence dataset, name and description from
880 // SearchResults.match[0].sequence
881 // TODO? carry over sequence names from original 'complement'
883 SequenceI mappedTo = sr.getResultSequence(0);
884 alignedSeq.setName(mappedTo.getName());
885 alignedSeq.setDescription(mappedTo.getDescription());
886 alignedSeq.setDatasetSequence(mappedTo);
893 alignedSeq.setSequence(newseq.toString());
898 * Realigns the given protein to match the alignment of the dna, using codon
899 * mappings to translate aligned codon positions to protein residues.
902 * the alignment whose sequences are realigned by this method
904 * the dna alignment whose alignment we are 'copying'
905 * @return the number of sequences that were realigned
907 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
909 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
910 unmappedProtein.addAll(protein.getSequences());
912 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
915 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
916 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
917 * comparator keeps the codon positions ordered.
919 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, String>>(
920 new CodonComparator());
921 for (SequenceI dnaSeq : dna.getSequences())
923 for (AlignedCodonFrame mapping : mappings)
925 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
926 SequenceI prot = mapping.findAlignedSequence(
927 dnaSeq.getDatasetSequence(), protein);
930 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
931 seqMap, alignedCodons);
932 unmappedProtein.remove(prot);
936 return alignProteinAs(protein, alignedCodons, unmappedProtein);
940 * Update the aligned protein sequences to match the codon alignments given in
944 * @param alignedCodons
945 * an ordered map of codon positions (columns), with sequence/peptide
946 * values present in each column
947 * @param unmappedProtein
950 protected static int alignProteinAs(AlignmentI protein,
951 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons,
952 List<SequenceI> unmappedProtein)
955 * Prefill aligned sequences with gaps before inserting aligned protein
958 int alignedWidth = alignedCodons.size();
959 char[] gaps = new char[alignedWidth];
960 Arrays.fill(gaps, protein.getGapCharacter());
961 String allGaps = String.valueOf(gaps);
962 for (SequenceI seq : protein.getSequences())
964 if (!unmappedProtein.contains(seq))
966 seq.setSequence(allGaps);
971 for (AlignedCodon codon : alignedCodons.keySet())
973 final Map<SequenceI, String> columnResidues = alignedCodons
975 for (Entry<SequenceI, String> entry : columnResidues.entrySet())
977 // place translated codon at its column position in sequence
978 entry.getKey().getSequence()[column] = entry.getValue().charAt(0);
986 * Populate the map of aligned codons by traversing the given sequence
987 * mapping, locating the aligned positions of mapped codons, and adding those
988 * positions and their translation products to the map.
991 * the aligned sequence we are mapping from
993 * the sequence to be aligned to the codons
995 * the gap character in the dna sequence
997 * a mapping to a sequence translation
998 * @param alignedCodons
999 * the map we are building up
1001 static void addCodonPositions(SequenceI dna, SequenceI protein,
1002 char gapChar, Mapping seqMap,
1003 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
1005 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1006 while (codons.hasNext())
1008 AlignedCodon codon = codons.next();
1009 Map<SequenceI, String> seqProduct = alignedCodons.get(codon);
1010 if (seqProduct == null)
1012 seqProduct = new HashMap<SequenceI, String>();
1013 alignedCodons.put(codon, seqProduct);
1015 seqProduct.put(protein, codon.product);
1020 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1021 * between at least one pair of sequences in the two alignments. Currently,
1024 * <li>One alignment must be nucleotide, and the other protein</li>
1025 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1026 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1027 * <li>The translation may ignore start and stop codons if present in the
1035 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1037 if (al1 == null || al2 == null)
1043 * Require one nucleotide and one protein
1045 if (al1.isNucleotide() == al2.isNucleotide())
1049 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1050 AlignmentI protein = dna == al1 ? al2 : al1;
1051 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
1052 for (SequenceI dnaSeq : dna.getSequences())
1054 for (SequenceI proteinSeq : protein.getSequences())
1056 if (isMappable(dnaSeq, proteinSeq, mappings))
1066 * Returns true if the dna sequence is mapped, or could be mapped, to the
1074 protected static boolean isMappable(SequenceI dnaSeq,
1075 SequenceI proteinSeq, Set<AlignedCodonFrame> mappings)
1077 if (dnaSeq == null || proteinSeq == null)
1082 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1083 .getDatasetSequence();
1084 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1085 : proteinSeq.getDatasetSequence();
1090 for (AlignedCodonFrame mapping : mappings)
1092 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1099 * Just try to make a mapping (it is not yet stored), test whether
1102 return mapProteinSequenceToCdna(proteinDs, dnaDs) != null;
1106 * Finds any reference annotations associated with the sequences in
1107 * sequenceScope, that are not already added to the alignment, and adds them
1108 * to the 'candidates' map. Also populates a lookup table of annotation
1109 * labels, keyed by calcId, for use in constructing tooltips or the like.
1111 * @param sequenceScope
1112 * the sequences to scan for reference annotations
1113 * @param labelForCalcId
1114 * (optional) map to populate with label for calcId
1116 * map to populate with annotations for sequence
1118 * the alignment to check for presence of annotations
1120 public static void findAddableReferenceAnnotations(
1121 List<SequenceI> sequenceScope,
1122 Map<String, String> labelForCalcId,
1123 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1126 if (sequenceScope == null)
1132 * For each sequence in scope, make a list of any annotations on the
1133 * underlying dataset sequence which are not already on the alignment.
1135 * Add to a map of { alignmentSequence, <List of annotations to add> }
1137 for (SequenceI seq : sequenceScope)
1139 SequenceI dataset = seq.getDatasetSequence();
1140 if (dataset == null)
1144 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1145 if (datasetAnnotations == null)
1149 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1150 for (AlignmentAnnotation dsann : datasetAnnotations)
1153 * Find matching annotations on the alignment. If none is found, then
1154 * add this annotation to the list of 'addable' annotations for this
1157 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1158 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1159 if (!matchedAlignmentAnnotations.iterator().hasNext())
1162 if (labelForCalcId != null)
1164 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1169 * Save any addable annotations for this sequence
1171 if (!result.isEmpty())
1173 candidates.put(seq, result);
1179 * Adds annotations to the top of the alignment annotations, in the same order
1180 * as their related sequences.
1182 * @param annotations
1183 * the annotations to add
1185 * the alignment to add them to
1186 * @param selectionGroup
1187 * current selection group (or null if none)
1189 public static void addReferenceAnnotations(
1190 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1191 final AlignmentI alignment, final SequenceGroup selectionGroup)
1193 for (SequenceI seq : annotations.keySet())
1195 for (AlignmentAnnotation ann : annotations.get(seq))
1197 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1199 int endRes = ann.annotations.length;
1200 if (selectionGroup != null)
1202 startRes = selectionGroup.getStartRes();
1203 endRes = selectionGroup.getEndRes();
1205 copyAnn.restrict(startRes, endRes);
1208 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1209 * original annotation is already on the sequence.
1211 if (!seq.hasAnnotation(ann))
1213 seq.addAlignmentAnnotation(copyAnn);
1216 copyAnn.adjustForAlignment();
1217 // add to the alignment and set visible
1218 alignment.addAnnotation(copyAnn);
1219 copyAnn.visible = true;
1225 * Set visibility of alignment annotations of specified types (labels), for
1226 * specified sequences. This supports controls like
1227 * "Show all secondary structure", "Hide all Temp factor", etc.
1229 * @al the alignment to scan for annotations
1231 * the types (labels) of annotations to be updated
1232 * @param forSequences
1233 * if not null, only annotations linked to one of these sequences are
1234 * in scope for update; if null, acts on all sequence annotations
1236 * if this flag is true, 'types' is ignored (label not checked)
1238 * if true, set visibility on, else set off
1240 public static void showOrHideSequenceAnnotations(AlignmentI al,
1241 Collection<String> types, List<SequenceI> forSequences,
1242 boolean anyType, boolean doShow)
1244 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1246 if (anyType || types.contains(aa.label))
1248 if ((aa.sequenceRef != null)
1249 && (forSequences == null || forSequences
1250 .contains(aa.sequenceRef)))
1252 aa.visible = doShow;
1259 * Returns true if either sequence has a cross-reference to the other
1265 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1267 // Note: moved here from class CrossRef as the latter class has dependencies
1268 // not availability to the applet's classpath
1269 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1273 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1274 * that sequence name is structured as Source|AccessionId.
1280 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1282 if (seq1 == null || seq2 == null)
1286 String name = seq2.getName();
1287 final DBRefEntry[] xrefs = seq1.getDBRefs();
1290 for (DBRefEntry xref : xrefs)
1292 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1293 // case-insensitive test, consistent with DBRefEntry.equalRef()
1294 if (xrefName.equalsIgnoreCase(name))
1304 * Constructs an alignment consisting of the mapped exon regions in the given
1305 * nucleotide sequences, and updates mappings to match.
1308 * aligned dna sequences
1310 * from dna to protein; these are replaced with new mappings
1311 * @return an alignment whose sequences are the exon-only parts of the dna
1312 * sequences (or null if no exons are found)
1314 public static AlignmentI makeExonAlignment(SequenceI[] dna,
1315 Set<AlignedCodonFrame> mappings)
1317 Set<AlignedCodonFrame> newMappings = new LinkedHashSet<AlignedCodonFrame>();
1318 List<SequenceI> exonSequences = new ArrayList<SequenceI>();
1320 for (SequenceI dnaSeq : dna)
1322 final SequenceI ds = dnaSeq.getDatasetSequence();
1323 List<AlignedCodonFrame> seqMappings = MappingUtils
1324 .findMappingsForSequence(ds, mappings);
1325 for (AlignedCodonFrame acf : seqMappings)
1327 AlignedCodonFrame newMapping = new AlignedCodonFrame();
1328 final List<SequenceI> mappedExons = makeExonSequences(ds, acf,
1330 if (!mappedExons.isEmpty())
1332 exonSequences.addAll(mappedExons);
1333 newMappings.add(newMapping);
1337 AlignmentI al = new Alignment(
1338 exonSequences.toArray(new SequenceI[exonSequences.size()]));
1339 al.setDataset(null);
1342 * Replace the old mappings with the new ones
1345 mappings.addAll(newMappings);
1351 * Helper method to make exon-only sequences and populate their mappings to
1354 * For example, if ggCCaTTcGAg has mappings [3, 4, 6, 7, 9, 10] to protein
1355 * then generate a sequence CCTTGA with mapping [1, 6] to the same protein
1358 * Typically eukaryotic dna will include exons encoding for a single peptide
1359 * sequence i.e. return a single result. Bacterial dna may have overlapping
1360 * exon mappings coding for multiple peptides so return multiple results
1361 * (example EMBL KF591215).
1364 * a dna dataset sequence
1366 * containing one or more mappings of the sequence to protein
1368 * the new mapping to populate, from the exon-only sequences to their
1369 * mapped protein sequences
1372 protected static List<SequenceI> makeExonSequences(SequenceI dnaSeq,
1373 AlignedCodonFrame mapping, AlignedCodonFrame newMapping)
1375 List<SequenceI> exonSequences = new ArrayList<SequenceI>();
1376 List<Mapping> seqMappings = mapping.getMappingsForSequence(dnaSeq);
1377 final char[] dna = dnaSeq.getSequence();
1378 for (Mapping seqMapping : seqMappings)
1380 StringBuilder newSequence = new StringBuilder(dnaSeq.getLength());
1383 * Get the codon regions as { [2, 5], [7, 12], [14, 14] etc }
1385 final List<int[]> dnaExonRanges = seqMapping.getMap().getFromRanges();
1386 for (int[] range : dnaExonRanges)
1388 for (int pos = range[0]; pos <= range[1]; pos++)
1390 newSequence.append(dna[pos - 1]);
1394 SequenceI exon = new Sequence(dnaSeq.getName(),
1395 newSequence.toString());
1398 * Locate any xrefs to CDS database on the protein product and attach to
1399 * the CDS sequence. Also add as a sub-token of the sequence name.
1401 // default to "CDS" if we can't locate an actual gene id
1402 String cdsAccId = FeatureProperties
1403 .getCodingFeature(DBRefSource.EMBL);
1404 DBRefEntry[] cdsRefs = DBRefUtils.selectRefs(seqMapping.getTo()
1405 .getDBRefs(), DBRefSource.CODINGDBS);
1406 if (cdsRefs != null)
1408 for (DBRefEntry cdsRef : cdsRefs)
1410 exon.addDBRef(new DBRefEntry(cdsRef));
1411 cdsAccId = cdsRef.getAccessionId();
1414 exon.setName(exon.getName() + "|" + cdsAccId);
1415 exon.createDatasetSequence();
1418 * Build new mappings - from the same protein regions, but now to
1421 List<int[]> exonRange = new ArrayList<int[]>();
1422 exonRange.add(new int[] { 1, newSequence.length() });
1423 MapList map = new MapList(exonRange, seqMapping.getMap()
1424 .getToRanges(), 3, 1);
1425 newMapping.addMap(exon.getDatasetSequence(), seqMapping.getTo(), map);
1426 MapList cdsToDnaMap = new MapList(dnaExonRanges, exonRange, 1, 1);
1427 newMapping.addMap(dnaSeq, exon.getDatasetSequence(), cdsToDnaMap);
1429 exonSequences.add(exon);
1431 return exonSequences;