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.List;
32 import java.util.Map.Entry;
34 import java.util.TreeMap;
36 import jalview.datamodel.AlignedCodon;
37 import jalview.datamodel.AlignedCodonFrame;
38 import jalview.datamodel.AlignmentAnnotation;
39 import jalview.datamodel.AlignmentI;
40 import jalview.datamodel.Mapping;
41 import jalview.datamodel.SearchResults;
42 import jalview.datamodel.Sequence;
43 import jalview.datamodel.SequenceGroup;
44 import jalview.datamodel.SequenceI;
45 import jalview.schemes.ResidueProperties;
46 import jalview.util.MapList;
49 * grab bag of useful alignment manipulation operations Expect these to be
50 * refactored elsewhere at some point.
55 public class AlignmentUtils
59 * given an existing alignment, create a new alignment including all, or up to
60 * flankSize additional symbols from each sequence's dataset sequence
66 public static AlignmentI expandContext(AlignmentI core, int flankSize)
68 List<SequenceI> sq = new ArrayList<SequenceI>();
70 for (SequenceI s : core.getSequences())
72 SequenceI newSeq = s.deriveSequence();
73 if (newSeq.getStart() > maxoffset
74 && newSeq.getDatasetSequence().getStart() < s.getStart())
76 maxoffset = newSeq.getStart();
82 maxoffset = flankSize;
84 // now add offset to create a new expanded alignment
85 for (SequenceI s : sq)
88 while (ds.getDatasetSequence() != null)
90 ds = ds.getDatasetSequence();
92 int s_end = s.findPosition(s.getStart() + s.getLength());
93 // find available flanking residues for sequence
94 int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
97 // build new flanked sequence
99 // compute gap padding to start of flanking sequence
100 int offset = maxoffset - ustream_ds;
102 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
105 if (flankSize < ustream_ds)
107 // take up to flankSize residues
108 offset = maxoffset - flankSize;
109 ustream_ds = flankSize;
111 if (flankSize < dstream_ds)
113 dstream_ds = flankSize;
116 char[] upstream = new String(ds.getSequence(s.getStart() - 1
117 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
118 char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
119 + dstream_ds)).toLowerCase().toCharArray();
120 char[] coreseq = s.getSequence();
121 char[] nseq = new char[offset + upstream.length + downstream.length
123 char c = core.getGapCharacter();
124 // TODO could lowercase the flanking regions
126 for (; p < offset; p++)
130 // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
131 // new String(downstream).toLowerCase());
132 System.arraycopy(upstream, 0, nseq, p, upstream.length);
133 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
135 System.arraycopy(downstream, 0, nseq, p + coreseq.length
136 + upstream.length, downstream.length);
137 s.setSequence(new String(nseq));
138 s.setStart(s.getStart() - ustream_ds);
139 s.setEnd(s_end + downstream.length);
141 AlignmentI newAl = new jalview.datamodel.Alignment(
142 sq.toArray(new SequenceI[0]));
143 for (SequenceI s : sq)
145 if (s.getAnnotation() != null)
147 for (AlignmentAnnotation aa : s.getAnnotation())
149 newAl.addAnnotation(aa);
153 newAl.setDataset(core.getDataset());
158 * Returns the index (zero-based position) of a sequence in an alignment, or
165 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
169 for (SequenceI alSeq : al.getSequences())
182 * Returns a map of lists of sequences in the alignment, keyed by sequence
183 * name. For use in mapping between different alignment views of the same
186 * @see jalview.datamodel.AlignmentI#getSequencesByName()
188 public static Map<String, List<SequenceI>> getSequencesByName(
191 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
192 for (SequenceI seq : al.getSequences())
194 String name = seq.getName();
197 List<SequenceI> seqs = theMap.get(name);
200 seqs = new ArrayList<SequenceI>();
201 theMap.put(name, seqs);
210 * Build mapping of protein to cDNA alignment. Mappings are made between
211 * sequences where the cDNA translates to the protein sequence. Any new
212 * mappings are added to the protein alignment. Returns true if any mappings
213 * either already exist or were added, else false.
215 * @param proteinAlignment
216 * @param cdnaAlignment
219 public static boolean mapProteinToCdna(
220 final AlignmentI proteinAlignment,
221 final AlignmentI cdnaAlignment)
223 if (proteinAlignment == null || cdnaAlignment == null)
228 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
229 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
232 * First pass - map sequences where cross-references exist. This include
233 * 1-to-many mappings to support, for example, variant cDNA.
235 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
236 cdnaAlignment, mappedDna, mappedProtein, true);
239 * Second pass - map sequences where no cross-references exist. This only
240 * does 1-to-1 mappings and assumes corresponding sequences are in the same
241 * order in the alignments.
243 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
244 mappedDna, mappedProtein, false);
245 return mappingPerformed;
249 * Make mappings between compatible sequences (where the cDNA translation
250 * matches the protein).
252 * @param proteinAlignment
253 * @param cdnaAlignment
255 * a set of mapped DNA sequences (to add to)
256 * @param mappedProtein
257 * a set of mapped Protein sequences (to add to)
259 * if true, only map sequences where xrefs exist
262 protected static boolean mapProteinToCdna(
263 final AlignmentI proteinAlignment,
264 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
265 Set<SequenceI> mappedProtein, boolean xrefsOnly)
267 boolean mappingPerformed = false;
268 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
269 for (SequenceI aaSeq : thisSeqs)
271 boolean proteinMapped = false;
272 AlignedCodonFrame acf = new AlignedCodonFrame();
274 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
277 * Always try to map if sequences have xref to each other; this supports
278 * variant cDNA or alternative splicing for a protein sequence.
280 * If no xrefs, try to map progressively, assuming that alignments have
281 * mappable sequences in corresponding order. These are not
282 * many-to-many, as that would risk mixing species with similar cDNA
285 if (xrefsOnly && !CrossRef.haveCrossRef(aaSeq, cdnaSeq))
291 * Don't map non-xrefd sequences more than once each. This heuristic
292 * allows us to pair up similar sequences in ordered alignments.
295 && (mappedProtein.contains(aaSeq) || mappedDna
300 if (!mappingExists(proteinAlignment.getCodonFrames(),
301 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
303 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
306 acf.addMap(cdnaSeq, aaSeq, map);
307 mappingPerformed = true;
308 proteinMapped = true;
309 mappedDna.add(cdnaSeq);
310 mappedProtein.add(aaSeq);
316 proteinAlignment.addCodonFrame(acf);
319 return mappingPerformed;
323 * Answers true if the mappings include one between the given (dataset)
326 public static boolean mappingExists(Set<AlignedCodonFrame> set,
327 SequenceI aaSeq, SequenceI cdnaSeq)
331 for (AlignedCodonFrame acf : set)
333 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
343 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
344 * must be three times the length of the protein, possibly after ignoring
345 * start and/or stop codons, and must translate to the protein. Returns null
346 * if no mapping is determined.
352 public static MapList mapProteinToCdna(SequenceI proteinSeq,
356 * Here we handle either dataset sequence set (desktop) or absent (applet).
357 * Use only the char[] form of the sequence to avoid creating possibly large
360 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
361 char[] aaSeqChars = proteinDataset != null ? proteinDataset
362 .getSequence() : proteinSeq.getSequence();
363 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
364 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
365 : cdnaSeq.getSequence();
366 if (aaSeqChars == null || cdnaSeqChars == null)
372 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
374 final int mappedLength = 3 * aaSeqChars.length;
375 int cdnaLength = cdnaSeqChars.length;
377 int cdnaEnd = cdnaLength;
378 final int proteinStart = 1;
379 final int proteinEnd = aaSeqChars.length;
382 * If lengths don't match, try ignoring stop codon.
384 if (cdnaLength != mappedLength && cdnaLength > 2)
386 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
388 for (String stop : ResidueProperties.STOP)
390 if (lastCodon.equals(stop))
400 * If lengths still don't match, try ignoring start codon.
402 if (cdnaLength != mappedLength
404 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
406 ResidueProperties.START))
412 if (cdnaLength != mappedLength)
416 if (!translatesAs(cdnaSeqChars, cdnaStart - 1, aaSeqChars))
420 MapList map = new MapList(new int[]
421 { cdnaStart, cdnaEnd }, new int[]
422 { proteinStart, proteinEnd }, 3, 1);
427 * Test whether the given cdna sequence, starting at the given offset,
428 * translates to the given amino acid sequence, using the standard translation
429 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
431 * @param cdnaSeqChars
436 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
440 for (int i = cdnaStart; i < cdnaSeqChars.length - 2
441 && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
443 String codon = String.valueOf(cdnaSeqChars, i, 3);
444 final String translated = ResidueProperties.codonTranslate(
447 * ? allow X in protein to match untranslatable in dna ?
449 final char aaRes = aaSeqChars[aaResidue];
450 if ((translated == null || "STOP".equals(translated)) && aaRes == 'X')
454 if (translated == null
455 || !(aaRes == translated.charAt(0)))
458 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
459 // + codon + "(" + translated + ") != " + aaRes));
463 // fail if we didn't match all of the aa sequence
464 return (aaResidue == aaSeqChars.length);
468 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
469 * currently assumes that we are aligning cDNA to match protein.
472 * the sequence to be realigned
474 * the alignment whose sequence alignment is to be 'copied'
476 * character string represent a gap in the realigned sequence
477 * @param preserveUnmappedGaps
478 * @param preserveMappedGaps
479 * @return true if the sequence was realigned, false if it could not be
481 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
482 String gap, boolean preserveMappedGaps,
483 boolean preserveUnmappedGaps)
486 * Get any mappings from the source alignment to the target (dataset) sequence.
488 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
489 // all mappings. Would it help to constrain this?
490 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
491 if (mappings == null || mappings.isEmpty())
497 * Locate the aligned source sequence whose dataset sequence is mapped. We
498 * just take the first match here (as we can't align cDNA like more than one
501 SequenceI alignFrom = null;
502 AlignedCodonFrame mapping = null;
503 for (AlignedCodonFrame mp : mappings)
505 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
506 if (alignFrom != null)
513 if (alignFrom == null)
517 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
518 preserveMappedGaps, preserveUnmappedGaps);
523 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
524 * match residues and codons. Flags control whether existing gaps in unmapped
525 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
526 * and exon are only retained if both flags are set.
533 * @param preserveUnmappedGaps
534 * @param preserveMappedGaps
536 public static void alignSequenceAs(SequenceI alignTo,
538 AlignedCodonFrame mapping, String myGap, char sourceGap,
539 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
541 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
542 final char[] thisSeq = alignTo.getSequence();
543 final char[] thatAligned = alignFrom.getSequence();
544 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
546 // aligned and dataset sequence positions, all base zero
550 int basesWritten = 0;
551 char myGapChar = myGap.charAt(0);
552 int ratio = myGap.length();
555 * Traverse the aligned protein sequence.
557 int sourceGapMappedLength = 0;
558 boolean inExon = false;
559 for (char sourceChar : thatAligned)
561 if (sourceChar == sourceGap)
563 sourceGapMappedLength += ratio;
568 * Found a residue. Locate its mapped codon (start) position.
571 // Note mapping positions are base 1, our sequence positions base 0
572 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
574 if (mappedPos == null)
577 * Abort realignment if unmapped protein. Or could ignore it??
579 System.err.println("Can't align: no codon mapping to residue "
580 + sourceDsPos + "(" + sourceChar + ")");
584 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
585 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
586 StringBuilder trailingCopiedGap = new StringBuilder();
589 * Copy dna sequence up to and including this codon. Optionally, include
590 * gaps before the codon starts (in introns) and/or after the codon starts
593 * Note this only works for 'linear' splicing, not reverse or interleaved.
594 * But then 'align dna as protein' doesn't make much sense otherwise.
596 int intronLength = 0;
597 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
599 final char c = thisSeq[thisSeqPos++];
604 if (basesWritten < mappedCodonStart)
607 * Found an unmapped (intron) base. First add in any preceding gaps
610 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
612 thisAligned.append(trailingCopiedGap.toString());
613 intronLength += trailingCopiedGap.length();
614 trailingCopiedGap = new StringBuilder();
621 final boolean startOfCodon = basesWritten == mappedCodonStart;
622 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
623 preserveUnmappedGaps, sourceGapMappedLength, inExon,
624 trailingCopiedGap.length(), intronLength, startOfCodon);
625 for (int i = 0; i < gapsToAdd; i++)
627 thisAligned.append(myGapChar);
629 sourceGapMappedLength = 0;
632 thisAligned.append(c);
633 trailingCopiedGap = new StringBuilder();
637 if (inExon && preserveMappedGaps)
639 trailingCopiedGap.append(myGapChar);
641 else if (!inExon && preserveUnmappedGaps)
643 trailingCopiedGap.append(myGapChar);
650 * At end of protein sequence. Copy any remaining dna sequence, optionally
651 * including (intron) gaps. We do not copy trailing gaps in protein.
653 while (thisSeqPos < thisSeq.length)
655 final char c = thisSeq[thisSeqPos++];
656 if (c != myGapChar || preserveUnmappedGaps)
658 thisAligned.append(c);
663 * All done aligning, set the aligned sequence.
665 alignTo.setSequence(new String(thisAligned));
669 * Helper method to work out how many gaps to insert when realigning.
671 * @param preserveMappedGaps
672 * @param preserveUnmappedGaps
673 * @param sourceGapMappedLength
675 * @param trailingCopiedGap
676 * @param intronLength
677 * @param startOfCodon
680 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
681 boolean preserveUnmappedGaps, int sourceGapMappedLength,
682 boolean inExon, int trailingGapLength,
683 int intronLength, final boolean startOfCodon)
689 * Reached start of codon. Ignore trailing gaps in intron unless we are
690 * preserving gaps in both exon and intron. Ignore them anyway if the
691 * protein alignment introduces a gap at least as large as the intronic
694 if (inExon && !preserveMappedGaps)
696 trailingGapLength = 0;
698 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
700 trailingGapLength = 0;
704 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
708 if (intronLength + trailingGapLength <= sourceGapMappedLength)
710 gapsToAdd = sourceGapMappedLength - intronLength;
714 gapsToAdd = Math.min(intronLength + trailingGapLength
715 - sourceGapMappedLength, trailingGapLength);
722 * second or third base of codon; check for any gaps in dna
724 if (!preserveMappedGaps)
726 trailingGapLength = 0;
728 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
734 * Returns a list of sequences mapped from the given sequences and aligned
735 * (gapped) in the same way. For example, the cDNA for aligned protein, where
736 * a single gap in protein generates three gaps in cDNA.
739 * @param gapCharacter
743 public static List<SequenceI> getAlignedTranslation(
744 List<SequenceI> sequences, char gapCharacter,
745 Set<AlignedCodonFrame> mappings)
747 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
749 for (SequenceI seq : sequences)
751 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
753 alignedSeqs.addAll(mapped);
759 * Returns sequences aligned 'like' the source sequence, as mapped by the
760 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
761 * will support 1-to-many as well.
764 * @param gapCharacter
768 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
769 char gapCharacter, Set<AlignedCodonFrame> mappings)
771 List<SequenceI> result = new ArrayList<SequenceI>();
772 for (AlignedCodonFrame mapping : mappings)
774 if (mapping.involvesSequence(seq))
776 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
787 * Returns the translation of 'seq' (as held in the mapping) with
788 * corresponding alignment (gaps).
791 * @param gapCharacter
795 protected static SequenceI getAlignedTranslation(SequenceI seq,
796 char gapCharacter, AlignedCodonFrame mapping)
798 String gap = String.valueOf(gapCharacter);
799 boolean toDna = false;
801 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
804 // mapping is from protein to nucleotide
806 // should ideally get gap count ratio from mapping
807 gap = String.valueOf(new char[]
808 { gapCharacter, gapCharacter, gapCharacter });
812 // mapping is from nucleotide to protein
813 mapTo = mapping.getAaForDnaSeq(seq);
816 StringBuilder newseq = new StringBuilder(seq.getLength()
819 int residueNo = 0; // in seq, base 1
820 int[] phrase = new int[fromRatio];
821 int phraseOffset = 0;
823 boolean first = true;
824 final Sequence alignedSeq = new Sequence("", "");
826 for (char c : seq.getSequence())
828 if (c == gapCharacter)
831 if (gapWidth >= fromRatio)
839 phrase[phraseOffset++] = residueNo + 1;
840 if (phraseOffset == fromRatio)
843 * Have read a whole codon (or protein residue), now translate: map
844 * source phrase to positions in target sequence add characters at
845 * these positions to newseq Note mapping positions are base 1, our
846 * sequence positions base 0.
848 SearchResults sr = new SearchResults();
849 for (int pos : phrase)
851 mapping.markMappedRegion(seq, pos, sr);
853 newseq.append(sr.toString());
857 // Hack: Copy sequence dataset, name and description from
858 // SearchResults.match[0].sequence
859 // TODO? carry over sequence names from original 'complement'
861 SequenceI mappedTo = sr.getResultSequence(0);
862 alignedSeq.setName(mappedTo.getName());
863 alignedSeq.setDescription(mappedTo.getDescription());
864 alignedSeq.setDatasetSequence(mappedTo);
871 alignedSeq.setSequence(newseq.toString());
876 * Realigns the given protein to match the alignment of the dna, using codon
877 * mappings to translate aligned codon positions to protein residues.
880 * the alignment whose sequences are realigned by this method
882 * the dna alignment whose alignment we are 'copying'
883 * @return the number of sequences that were realigned
885 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
887 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
890 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
891 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
892 * comparator keeps the codon positions ordered.
894 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, String>>(
895 new CodonComparator());
896 for (SequenceI dnaSeq : dna.getSequences())
898 for (AlignedCodonFrame mapping : mappings)
900 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
901 SequenceI prot = mapping.findAlignedSequence(
902 dnaSeq.getDatasetSequence(), protein);
905 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
906 seqMap, alignedCodons);
910 return alignProteinAs(protein, alignedCodons);
914 * Update the aligned protein sequences to match the codon alignments given in
918 * @param alignedCodons
919 * an ordered map of codon positions (columns), with sequence/peptide
920 * values present in each column
923 protected static int alignProteinAs(AlignmentI protein,
924 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
927 * Prefill aligned sequences with gaps before inserting aligned protein
930 int alignedWidth = alignedCodons.size();
931 char[] gaps = new char[alignedWidth];
932 Arrays.fill(gaps, protein.getGapCharacter());
933 String allGaps = String.valueOf(gaps);
934 for (SequenceI seq : protein.getSequences())
936 seq.setSequence(allGaps);
940 for (AlignedCodon codon : alignedCodons.keySet())
942 final Map<SequenceI, String> columnResidues = alignedCodons.get(codon);
943 for (Entry<SequenceI, String> entry : columnResidues
946 // place translated codon at its column position in sequence
947 entry.getKey().getSequence()[column] = entry.getValue().charAt(0);
955 * Populate the map of aligned codons by traversing the given sequence
956 * mapping, locating the aligned positions of mapped codons, and adding those
957 * positions and their translation products to the map.
960 * the aligned sequence we are mapping from
962 * the sequence to be aligned to the codons
964 * the gap character in the dna sequence
966 * a mapping to a sequence translation
967 * @param alignedCodons
968 * the map we are building up
970 static void addCodonPositions(SequenceI dna, SequenceI protein,
973 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
975 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
976 while (codons.hasNext())
978 AlignedCodon codon = codons.next();
979 Map<SequenceI, String> seqProduct = alignedCodons.get(codon);
980 if (seqProduct == null)
982 seqProduct = new HashMap<SequenceI, String>();
983 alignedCodons.put(codon, seqProduct);
985 seqProduct.put(protein, codon.product);
990 * Returns true if a cDNA/Protein mapping either exists, or could be made,
991 * between at least one pair of sequences in the two alignments. Currently,
994 * <li>One alignment must be nucleotide, and the other protein</li>
995 * <li>At least one pair of sequences must be already mapped, or mappable</li>
996 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
997 * <li>The translation may ignore start and stop codons if present in the
1005 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1008 * Require one nucleotide and one protein
1010 if (al1.isNucleotide() == al2.isNucleotide())
1014 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1015 AlignmentI protein = dna == al1 ? al2 : al1;
1016 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
1017 for (SequenceI dnaSeq : dna.getSequences())
1019 for (SequenceI proteinSeq : protein.getSequences())
1021 if (isMappable(dnaSeq, proteinSeq, mappings))
1031 * Returns true if the dna sequence is mapped, or could be mapped, to the
1039 public static boolean isMappable(SequenceI dnaSeq, SequenceI proteinSeq,
1040 Set<AlignedCodonFrame> mappings)
1042 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq.getDatasetSequence();
1043 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1044 : proteinSeq.getDatasetSequence();
1049 for (AlignedCodonFrame mapping : mappings) {
1050 if ( proteinDs == mapping.getAaForDnaSeq(dnaDs)) {
1056 * Just try to make a mapping (it is not yet stored), test whether
1059 return mapProteinToCdna(proteinDs, dnaDs) != null;
1063 * Finds any reference annotations associated with the sequences in
1064 * sequenceScope, that are not already added to the alignment, and adds them
1065 * to the 'candidates' map. Also populates a lookup table of annotation
1066 * labels, keyed by calcId, for use in constructing tooltips or the like.
1068 * @param sequenceScope
1069 * the sequences to scan for reference annotations
1070 * @param labelForCalcId
1071 * (optional) map to populate with label for calcId
1073 * map to populate with annotations for sequence
1075 * the alignment to check for presence of annotations
1077 public static void findAddableReferenceAnnotations(
1078 List<SequenceI> sequenceScope, Map<String, String> labelForCalcId,
1079 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1082 if (sequenceScope == null)
1088 * For each sequence in scope, make a list of any annotations on the
1089 * underlying dataset sequence which are not already on the alignment.
1091 * Add to a map of { alignmentSequence, <List of annotations to add> }
1093 for (SequenceI seq : sequenceScope)
1095 SequenceI dataset = seq.getDatasetSequence();
1096 if (dataset == null)
1100 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1101 if (datasetAnnotations == null)
1105 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1106 for (AlignmentAnnotation dsann : datasetAnnotations)
1109 * Find matching annotations on the alignment. If none is found, then
1110 * add this annotation to the list of 'addable' annotations for this
1113 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1114 .findAnnotations(seq, dsann.getCalcId(),
1116 if (!matchedAlignmentAnnotations.iterator().hasNext())
1119 if (labelForCalcId != null)
1121 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1126 * Save any addable annotations for this sequence
1128 if (!result.isEmpty())
1130 candidates.put(seq, result);
1136 * Adds annotations to the top of the alignment annotations, in the same order
1137 * as their related sequences.
1139 * @param annotations
1140 * the annotations to add
1142 * the alignment to add them to
1143 * @param selectionGroup
1144 * current selection group (or null if none)
1146 public static void addReferenceAnnotations(
1147 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1148 final AlignmentI alignment, final SequenceGroup selectionGroup)
1150 for (SequenceI seq : annotations.keySet())
1152 for (AlignmentAnnotation ann : annotations.get(seq))
1154 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1156 int endRes = ann.annotations.length;
1157 if (selectionGroup != null)
1159 startRes = selectionGroup.getStartRes();
1160 endRes = selectionGroup.getEndRes();
1162 copyAnn.restrict(startRes, endRes);
1165 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1166 * original annotation is already on the sequence.
1168 if (!seq.hasAnnotation(ann))
1170 seq.addAlignmentAnnotation(copyAnn);
1173 copyAnn.adjustForAlignment();
1174 // add to the alignment and set visible
1175 alignment.addAnnotation(copyAnn);
1176 copyAnn.visible = true;
1182 * Set visibility of alignment annotations of specified types (labels), for
1183 * specified sequences. This supports controls like
1184 * "Show all secondary structure", "Hide all Temp factor", etc.
1186 * @al the alignment to scan for annotations
1188 * the types (labels) of annotations to be updated
1189 * @param forSequences
1190 * if not null, only annotations linked to one of these sequences are
1191 * in scope for update; if null, acts on all sequence annotations
1193 * if this flag is true, 'types' is ignored (label not checked)
1195 * if true, set visibility on, else set off
1197 public static void showOrHideSequenceAnnotations(AlignmentI al,
1198 Collection<String> types, List<SequenceI> forSequences,
1199 boolean anyType, boolean doShow)
1201 for (AlignmentAnnotation aa : al
1202 .getAlignmentAnnotation())
1204 if (anyType || types.contains(aa.label))
1206 if ((aa.sequenceRef != null)
1207 && (forSequences == null || forSequences
1208 .contains(aa.sequenceRef)))
1210 aa.visible = doShow;