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.DBRefEntry;
41 import jalview.datamodel.Mapping;
42 import jalview.datamodel.SearchResults;
43 import jalview.datamodel.Sequence;
44 import jalview.datamodel.SequenceGroup;
45 import jalview.datamodel.SequenceI;
46 import jalview.schemes.ResidueProperties;
47 import jalview.util.MapList;
50 * grab bag of useful alignment manipulation operations Expect these to be
51 * refactored elsewhere at some point.
56 public class AlignmentUtils
60 * given an existing alignment, create a new alignment including all, or up to
61 * flankSize additional symbols from each sequence's dataset sequence
67 public static AlignmentI expandContext(AlignmentI core, int flankSize)
69 List<SequenceI> sq = new ArrayList<SequenceI>();
71 for (SequenceI s : core.getSequences())
73 SequenceI newSeq = s.deriveSequence();
74 if (newSeq.getStart() > maxoffset
75 && newSeq.getDatasetSequence().getStart() < s.getStart())
77 maxoffset = newSeq.getStart();
83 maxoffset = flankSize;
85 // now add offset to create a new expanded alignment
86 for (SequenceI s : sq)
89 while (ds.getDatasetSequence() != null)
91 ds = ds.getDatasetSequence();
93 int s_end = s.findPosition(s.getStart() + s.getLength());
94 // find available flanking residues for sequence
95 int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
98 // build new flanked sequence
100 // compute gap padding to start of flanking sequence
101 int offset = maxoffset - ustream_ds;
103 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
106 if (flankSize < ustream_ds)
108 // take up to flankSize residues
109 offset = maxoffset - flankSize;
110 ustream_ds = flankSize;
112 if (flankSize < dstream_ds)
114 dstream_ds = flankSize;
117 char[] upstream = new String(ds.getSequence(s.getStart() - 1
118 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
119 char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
120 + dstream_ds)).toLowerCase().toCharArray();
121 char[] coreseq = s.getSequence();
122 char[] nseq = new char[offset + upstream.length + downstream.length
124 char c = core.getGapCharacter();
125 // TODO could lowercase the flanking regions
127 for (; p < offset; p++)
131 // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
132 // new String(downstream).toLowerCase());
133 System.arraycopy(upstream, 0, nseq, p, upstream.length);
134 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
136 System.arraycopy(downstream, 0, nseq, p + coreseq.length
137 + upstream.length, downstream.length);
138 s.setSequence(new String(nseq));
139 s.setStart(s.getStart() - ustream_ds);
140 s.setEnd(s_end + downstream.length);
142 AlignmentI newAl = new jalview.datamodel.Alignment(
143 sq.toArray(new SequenceI[0]));
144 for (SequenceI s : sq)
146 if (s.getAnnotation() != null)
148 for (AlignmentAnnotation aa : s.getAnnotation())
150 newAl.addAnnotation(aa);
154 newAl.setDataset(core.getDataset());
159 * Returns the index (zero-based position) of a sequence in an alignment, or
166 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
170 for (SequenceI alSeq : al.getSequences())
183 * Returns a map of lists of sequences in the alignment, keyed by sequence
184 * name. For use in mapping between different alignment views of the same
187 * @see jalview.datamodel.AlignmentI#getSequencesByName()
189 public static Map<String, List<SequenceI>> getSequencesByName(
192 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
193 for (SequenceI seq : al.getSequences())
195 String name = seq.getName();
198 List<SequenceI> seqs = theMap.get(name);
201 seqs = new ArrayList<SequenceI>();
202 theMap.put(name, seqs);
211 * Build mapping of protein to cDNA alignment. Mappings are made between
212 * sequences where the cDNA translates to the protein sequence. Any new
213 * mappings are added to the protein alignment. Returns true if any mappings
214 * either already exist or were added, else false.
216 * @param proteinAlignment
217 * @param cdnaAlignment
220 public static boolean mapProteinToCdna(
221 final AlignmentI proteinAlignment,
222 final AlignmentI cdnaAlignment)
224 if (proteinAlignment == null || cdnaAlignment == null)
229 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
230 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
233 * First pass - map sequences where cross-references exist. This include
234 * 1-to-many mappings to support, for example, variant cDNA.
236 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
237 cdnaAlignment, mappedDna, mappedProtein, true);
240 * Second pass - map sequences where no cross-references exist. This only
241 * does 1-to-1 mappings and assumes corresponding sequences are in the same
242 * order in the alignments.
244 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
245 mappedDna, mappedProtein, false);
246 return mappingPerformed;
250 * Make mappings between compatible sequences (where the cDNA translation
251 * matches the protein).
253 * @param proteinAlignment
254 * @param cdnaAlignment
256 * a set of mapped DNA sequences (to add to)
257 * @param mappedProtein
258 * a set of mapped Protein sequences (to add to)
260 * if true, only map sequences where xrefs exist
263 protected static boolean mapProteinToCdna(
264 final AlignmentI proteinAlignment,
265 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
266 Set<SequenceI> mappedProtein, boolean xrefsOnly)
268 boolean mappingPerformed = false;
269 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
270 for (SequenceI aaSeq : thisSeqs)
272 boolean proteinMapped = false;
273 AlignedCodonFrame acf = new AlignedCodonFrame();
275 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
278 * Always try to map if sequences have xref to each other; this supports
279 * variant cDNA or alternative splicing for a protein sequence.
281 * If no xrefs, try to map progressively, assuming that alignments have
282 * mappable sequences in corresponding order. These are not
283 * many-to-many, as that would risk mixing species with similar cDNA
286 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
292 * Don't map non-xrefd sequences more than once each. This heuristic
293 * allows us to pair up similar sequences in ordered alignments.
296 && (mappedProtein.contains(aaSeq) || mappedDna
301 if (!mappingExists(proteinAlignment.getCodonFrames(),
302 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
304 MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
307 acf.addMap(cdnaSeq, aaSeq, map);
308 mappingPerformed = true;
309 proteinMapped = true;
310 mappedDna.add(cdnaSeq);
311 mappedProtein.add(aaSeq);
317 proteinAlignment.addCodonFrame(acf);
320 return mappingPerformed;
324 * Answers true if the mappings include one between the given (dataset)
327 public static boolean mappingExists(Set<AlignedCodonFrame> set,
328 SequenceI aaSeq, SequenceI cdnaSeq)
332 for (AlignedCodonFrame acf : set)
334 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
344 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
345 * must be three times the length of the protein, possibly after ignoring
346 * start and/or stop codons, and must translate to the protein. Returns null
347 * if no mapping is determined.
353 public static MapList mapProteinToCdna(SequenceI proteinSeq,
357 * Here we handle either dataset sequence set (desktop) or absent (applet).
358 * Use only the char[] form of the sequence to avoid creating possibly large
361 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
362 char[] aaSeqChars = proteinDataset != null ? proteinDataset
363 .getSequence() : proteinSeq.getSequence();
364 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
365 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
366 : cdnaSeq.getSequence();
367 if (aaSeqChars == null || cdnaSeqChars == null)
373 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
375 final int mappedLength = 3 * aaSeqChars.length;
376 int cdnaLength = cdnaSeqChars.length;
378 int cdnaEnd = cdnaLength;
379 final int proteinStart = 1;
380 final int proteinEnd = aaSeqChars.length;
383 * If lengths don't match, try ignoring stop codon.
385 if (cdnaLength != mappedLength && cdnaLength > 2)
387 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
389 for (String stop : ResidueProperties.STOP)
391 if (lastCodon.equals(stop))
401 * If lengths still don't match, try ignoring start codon.
403 if (cdnaLength != mappedLength
405 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
407 ResidueProperties.START))
413 if (cdnaLength != mappedLength)
417 if (!translatesAs(cdnaSeqChars, cdnaStart - 1, aaSeqChars))
421 MapList map = new MapList(new int[]
422 { cdnaStart, cdnaEnd }, new int[]
423 { proteinStart, proteinEnd }, 3, 1);
428 * Test whether the given cdna sequence, starting at the given offset,
429 * translates to the given amino acid sequence, using the standard translation
430 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
432 * @param cdnaSeqChars
437 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
441 for (int i = cdnaStart; i < cdnaSeqChars.length - 2
442 && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
444 String codon = String.valueOf(cdnaSeqChars, i, 3);
445 final String translated = ResidueProperties.codonTranslate(
448 * ? allow X in protein to match untranslatable in dna ?
450 final char aaRes = aaSeqChars[aaResidue];
451 if ((translated == null || "STOP".equals(translated)) && aaRes == 'X')
455 if (translated == null
456 || !(aaRes == translated.charAt(0)))
459 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
460 // + codon + "(" + translated + ") != " + aaRes));
464 // fail if we didn't match all of the aa sequence
465 return (aaResidue == aaSeqChars.length);
469 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
470 * currently assumes that we are aligning cDNA to match protein.
473 * the sequence to be realigned
475 * the alignment whose sequence alignment is to be 'copied'
477 * character string represent a gap in the realigned sequence
478 * @param preserveUnmappedGaps
479 * @param preserveMappedGaps
480 * @return true if the sequence was realigned, false if it could not be
482 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
483 String gap, boolean preserveMappedGaps,
484 boolean preserveUnmappedGaps)
487 * Get any mappings from the source alignment to the target (dataset) sequence.
489 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
490 // all mappings. Would it help to constrain this?
491 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
492 if (mappings == null || mappings.isEmpty())
498 * Locate the aligned source sequence whose dataset sequence is mapped. We
499 * just take the first match here (as we can't align cDNA like more than one
502 SequenceI alignFrom = null;
503 AlignedCodonFrame mapping = null;
504 for (AlignedCodonFrame mp : mappings)
506 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
507 if (alignFrom != null)
514 if (alignFrom == null)
518 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
519 preserveMappedGaps, preserveUnmappedGaps);
524 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
525 * match residues and codons. Flags control whether existing gaps in unmapped
526 * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
527 * and exon are only retained if both flags are set.
534 * @param preserveUnmappedGaps
535 * @param preserveMappedGaps
537 public static void alignSequenceAs(SequenceI alignTo,
539 AlignedCodonFrame mapping, String myGap, char sourceGap,
540 boolean preserveMappedGaps, boolean preserveUnmappedGaps)
542 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
543 final char[] thisSeq = alignTo.getSequence();
544 final char[] thatAligned = alignFrom.getSequence();
545 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
547 // aligned and dataset sequence positions, all base zero
551 int basesWritten = 0;
552 char myGapChar = myGap.charAt(0);
553 int ratio = myGap.length();
556 * Traverse the aligned protein sequence.
558 int sourceGapMappedLength = 0;
559 boolean inExon = false;
560 for (char sourceChar : thatAligned)
562 if (sourceChar == sourceGap)
564 sourceGapMappedLength += ratio;
569 * Found a residue. Locate its mapped codon (start) position.
572 // Note mapping positions are base 1, our sequence positions base 0
573 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
575 if (mappedPos == null)
578 * Abort realignment if unmapped protein. Or could ignore it??
580 System.err.println("Can't align: no codon mapping to residue "
581 + sourceDsPos + "(" + sourceChar + ")");
585 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
586 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
587 StringBuilder trailingCopiedGap = new StringBuilder();
590 * Copy dna sequence up to and including this codon. Optionally, include
591 * gaps before the codon starts (in introns) and/or after the codon starts
594 * Note this only works for 'linear' splicing, not reverse or interleaved.
595 * But then 'align dna as protein' doesn't make much sense otherwise.
597 int intronLength = 0;
598 while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
600 final char c = thisSeq[thisSeqPos++];
605 if (basesWritten < mappedCodonStart)
608 * Found an unmapped (intron) base. First add in any preceding gaps
611 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
613 thisAligned.append(trailingCopiedGap.toString());
614 intronLength += trailingCopiedGap.length();
615 trailingCopiedGap = new StringBuilder();
622 final boolean startOfCodon = basesWritten == mappedCodonStart;
623 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
624 preserveUnmappedGaps, sourceGapMappedLength, inExon,
625 trailingCopiedGap.length(), intronLength, startOfCodon);
626 for (int i = 0; i < gapsToAdd; i++)
628 thisAligned.append(myGapChar);
630 sourceGapMappedLength = 0;
633 thisAligned.append(c);
634 trailingCopiedGap = new StringBuilder();
638 if (inExon && preserveMappedGaps)
640 trailingCopiedGap.append(myGapChar);
642 else if (!inExon && preserveUnmappedGaps)
644 trailingCopiedGap.append(myGapChar);
651 * At end of protein sequence. Copy any remaining dna sequence, optionally
652 * including (intron) gaps. We do not copy trailing gaps in protein.
654 while (thisSeqPos < thisSeq.length)
656 final char c = thisSeq[thisSeqPos++];
657 if (c != myGapChar || preserveUnmappedGaps)
659 thisAligned.append(c);
664 * All done aligning, set the aligned sequence.
666 alignTo.setSequence(new String(thisAligned));
670 * Helper method to work out how many gaps to insert when realigning.
672 * @param preserveMappedGaps
673 * @param preserveUnmappedGaps
674 * @param sourceGapMappedLength
676 * @param trailingCopiedGap
677 * @param intronLength
678 * @param startOfCodon
681 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
682 boolean preserveUnmappedGaps, int sourceGapMappedLength,
683 boolean inExon, int trailingGapLength,
684 int intronLength, final boolean startOfCodon)
690 * Reached start of codon. Ignore trailing gaps in intron unless we are
691 * preserving gaps in both exon and intron. Ignore them anyway if the
692 * protein alignment introduces a gap at least as large as the intronic
695 if (inExon && !preserveMappedGaps)
697 trailingGapLength = 0;
699 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
701 trailingGapLength = 0;
705 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
709 if (intronLength + trailingGapLength <= sourceGapMappedLength)
711 gapsToAdd = sourceGapMappedLength - intronLength;
715 gapsToAdd = Math.min(intronLength + trailingGapLength
716 - sourceGapMappedLength, trailingGapLength);
723 * second or third base of codon; check for any gaps in dna
725 if (!preserveMappedGaps)
727 trailingGapLength = 0;
729 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
735 * Returns a list of sequences mapped from the given sequences and aligned
736 * (gapped) in the same way. For example, the cDNA for aligned protein, where
737 * a single gap in protein generates three gaps in cDNA.
740 * @param gapCharacter
744 public static List<SequenceI> getAlignedTranslation(
745 List<SequenceI> sequences, char gapCharacter,
746 Set<AlignedCodonFrame> mappings)
748 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
750 for (SequenceI seq : sequences)
752 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
754 alignedSeqs.addAll(mapped);
760 * Returns sequences aligned 'like' the source sequence, as mapped by the
761 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
762 * will support 1-to-many as well.
765 * @param gapCharacter
769 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
770 char gapCharacter, Set<AlignedCodonFrame> mappings)
772 List<SequenceI> result = new ArrayList<SequenceI>();
773 for (AlignedCodonFrame mapping : mappings)
775 if (mapping.involvesSequence(seq))
777 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
788 * Returns the translation of 'seq' (as held in the mapping) with
789 * corresponding alignment (gaps).
792 * @param gapCharacter
796 protected static SequenceI getAlignedTranslation(SequenceI seq,
797 char gapCharacter, AlignedCodonFrame mapping)
799 String gap = String.valueOf(gapCharacter);
800 boolean toDna = false;
802 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
805 // mapping is from protein to nucleotide
807 // should ideally get gap count ratio from mapping
808 gap = String.valueOf(new char[]
809 { gapCharacter, gapCharacter, gapCharacter });
813 // mapping is from nucleotide to protein
814 mapTo = mapping.getAaForDnaSeq(seq);
817 StringBuilder newseq = new StringBuilder(seq.getLength()
820 int residueNo = 0; // in seq, base 1
821 int[] phrase = new int[fromRatio];
822 int phraseOffset = 0;
824 boolean first = true;
825 final Sequence alignedSeq = new Sequence("", "");
827 for (char c : seq.getSequence())
829 if (c == gapCharacter)
832 if (gapWidth >= fromRatio)
840 phrase[phraseOffset++] = residueNo + 1;
841 if (phraseOffset == fromRatio)
844 * Have read a whole codon (or protein residue), now translate: map
845 * source phrase to positions in target sequence add characters at
846 * these positions to newseq Note mapping positions are base 1, our
847 * sequence positions base 0.
849 SearchResults sr = new SearchResults();
850 for (int pos : phrase)
852 mapping.markMappedRegion(seq, pos, sr);
854 newseq.append(sr.toString());
858 // Hack: Copy sequence dataset, name and description from
859 // SearchResults.match[0].sequence
860 // TODO? carry over sequence names from original 'complement'
862 SequenceI mappedTo = sr.getResultSequence(0);
863 alignedSeq.setName(mappedTo.getName());
864 alignedSeq.setDescription(mappedTo.getDescription());
865 alignedSeq.setDatasetSequence(mappedTo);
872 alignedSeq.setSequence(newseq.toString());
877 * Realigns the given protein to match the alignment of the dna, using codon
878 * mappings to translate aligned codon positions to protein residues.
881 * the alignment whose sequences are realigned by this method
883 * the dna alignment whose alignment we are 'copying'
884 * @return the number of sequences that were realigned
886 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
888 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
891 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
892 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
893 * comparator keeps the codon positions ordered.
895 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, String>>(
896 new CodonComparator());
897 for (SequenceI dnaSeq : dna.getSequences())
899 for (AlignedCodonFrame mapping : mappings)
901 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
902 SequenceI prot = mapping.findAlignedSequence(
903 dnaSeq.getDatasetSequence(), protein);
906 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
907 seqMap, alignedCodons);
911 return alignProteinAs(protein, alignedCodons);
915 * Update the aligned protein sequences to match the codon alignments given in
919 * @param alignedCodons
920 * an ordered map of codon positions (columns), with sequence/peptide
921 * values present in each column
924 protected static int alignProteinAs(AlignmentI protein,
925 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
928 * Prefill aligned sequences with gaps before inserting aligned protein
931 int alignedWidth = alignedCodons.size();
932 char[] gaps = new char[alignedWidth];
933 Arrays.fill(gaps, protein.getGapCharacter());
934 String allGaps = String.valueOf(gaps);
935 for (SequenceI seq : protein.getSequences())
937 seq.setSequence(allGaps);
941 for (AlignedCodon codon : alignedCodons.keySet())
943 final Map<SequenceI, String> columnResidues = alignedCodons.get(codon);
944 for (Entry<SequenceI, String> entry : columnResidues
947 // place translated codon at its column position in sequence
948 entry.getKey().getSequence()[column] = entry.getValue().charAt(0);
956 * Populate the map of aligned codons by traversing the given sequence
957 * mapping, locating the aligned positions of mapped codons, and adding those
958 * positions and their translation products to the map.
961 * the aligned sequence we are mapping from
963 * the sequence to be aligned to the codons
965 * the gap character in the dna sequence
967 * a mapping to a sequence translation
968 * @param alignedCodons
969 * the map we are building up
971 static void addCodonPositions(SequenceI dna, SequenceI protein,
974 Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
976 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
977 while (codons.hasNext())
979 AlignedCodon codon = codons.next();
980 Map<SequenceI, String> seqProduct = alignedCodons.get(codon);
981 if (seqProduct == null)
983 seqProduct = new HashMap<SequenceI, String>();
984 alignedCodons.put(codon, seqProduct);
986 seqProduct.put(protein, codon.product);
991 * Returns true if a cDNA/Protein mapping either exists, or could be made,
992 * between at least one pair of sequences in the two alignments. Currently,
995 * <li>One alignment must be nucleotide, and the other protein</li>
996 * <li>At least one pair of sequences must be already mapped, or mappable</li>
997 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
998 * <li>The translation may ignore start and stop codons if present in the
1006 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1009 * Require one nucleotide and one protein
1011 if (al1.isNucleotide() == al2.isNucleotide())
1015 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1016 AlignmentI protein = dna == al1 ? al2 : al1;
1017 Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
1018 for (SequenceI dnaSeq : dna.getSequences())
1020 for (SequenceI proteinSeq : protein.getSequences())
1022 if (isMappable(dnaSeq, proteinSeq, mappings))
1032 * Returns true if the dna sequence is mapped, or could be mapped, to the
1040 public static boolean isMappable(SequenceI dnaSeq, SequenceI proteinSeq,
1041 Set<AlignedCodonFrame> mappings)
1043 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq.getDatasetSequence();
1044 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1045 : proteinSeq.getDatasetSequence();
1050 for (AlignedCodonFrame mapping : mappings) {
1051 if ( proteinDs == mapping.getAaForDnaSeq(dnaDs)) {
1057 * Just try to make a mapping (it is not yet stored), test whether
1060 return mapProteinToCdna(proteinDs, dnaDs) != null;
1064 * Finds any reference annotations associated with the sequences in
1065 * sequenceScope, that are not already added to the alignment, and adds them
1066 * to the 'candidates' map. Also populates a lookup table of annotation
1067 * labels, keyed by calcId, for use in constructing tooltips or the like.
1069 * @param sequenceScope
1070 * the sequences to scan for reference annotations
1071 * @param labelForCalcId
1072 * (optional) map to populate with label for calcId
1074 * map to populate with annotations for sequence
1076 * the alignment to check for presence of annotations
1078 public static void findAddableReferenceAnnotations(
1079 List<SequenceI> sequenceScope, Map<String, String> labelForCalcId,
1080 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1083 if (sequenceScope == null)
1089 * For each sequence in scope, make a list of any annotations on the
1090 * underlying dataset sequence which are not already on the alignment.
1092 * Add to a map of { alignmentSequence, <List of annotations to add> }
1094 for (SequenceI seq : sequenceScope)
1096 SequenceI dataset = seq.getDatasetSequence();
1097 if (dataset == null)
1101 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1102 if (datasetAnnotations == null)
1106 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1107 for (AlignmentAnnotation dsann : datasetAnnotations)
1110 * Find matching annotations on the alignment. If none is found, then
1111 * add this annotation to the list of 'addable' annotations for this
1114 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1115 .findAnnotations(seq, dsann.getCalcId(),
1117 if (!matchedAlignmentAnnotations.iterator().hasNext())
1120 if (labelForCalcId != null)
1122 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1127 * Save any addable annotations for this sequence
1129 if (!result.isEmpty())
1131 candidates.put(seq, result);
1137 * Adds annotations to the top of the alignment annotations, in the same order
1138 * as their related sequences.
1140 * @param annotations
1141 * the annotations to add
1143 * the alignment to add them to
1144 * @param selectionGroup
1145 * current selection group (or null if none)
1147 public static void addReferenceAnnotations(
1148 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1149 final AlignmentI alignment, final SequenceGroup selectionGroup)
1151 for (SequenceI seq : annotations.keySet())
1153 for (AlignmentAnnotation ann : annotations.get(seq))
1155 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1157 int endRes = ann.annotations.length;
1158 if (selectionGroup != null)
1160 startRes = selectionGroup.getStartRes();
1161 endRes = selectionGroup.getEndRes();
1163 copyAnn.restrict(startRes, endRes);
1166 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1167 * original annotation is already on the sequence.
1169 if (!seq.hasAnnotation(ann))
1171 seq.addAlignmentAnnotation(copyAnn);
1174 copyAnn.adjustForAlignment();
1175 // add to the alignment and set visible
1176 alignment.addAnnotation(copyAnn);
1177 copyAnn.visible = true;
1183 * Set visibility of alignment annotations of specified types (labels), for
1184 * specified sequences. This supports controls like
1185 * "Show all secondary structure", "Hide all Temp factor", etc.
1187 * @al the alignment to scan for annotations
1189 * the types (labels) of annotations to be updated
1190 * @param forSequences
1191 * if not null, only annotations linked to one of these sequences are
1192 * in scope for update; if null, acts on all sequence annotations
1194 * if this flag is true, 'types' is ignored (label not checked)
1196 * if true, set visibility on, else set off
1198 public static void showOrHideSequenceAnnotations(AlignmentI al,
1199 Collection<String> types, List<SequenceI> forSequences,
1200 boolean anyType, boolean doShow)
1202 for (AlignmentAnnotation aa : al
1203 .getAlignmentAnnotation())
1205 if (anyType || types.contains(aa.label))
1207 if ((aa.sequenceRef != null)
1208 && (forSequences == null || forSequences
1209 .contains(aa.sequenceRef)))
1211 aa.visible = doShow;
1218 * Returns true if either sequence has a cross-reference to the other
1224 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1226 // Note: moved here from class CrossRef as the latter class has dependencies
1227 // not availability to the applet's classpath
1228 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1232 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1233 * that sequence name is structured as Source|AccessId.
1239 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1241 if (seq1 == null || seq2 == null)
1245 String name = seq2.getName();
1246 final DBRefEntry[] xrefs = seq1.getDBRef();
1249 for (DBRefEntry xref : xrefs)
1251 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1252 // case-insensitive test, consistent with DBRefEntry.equalRef()
1253 if (xrefName.equalsIgnoreCase(name))