2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.analysis;
23 import jalview.datamodel.AlignedCodon;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.FeatureProperties;
31 import jalview.datamodel.IncompleteCodonException;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.SearchResults;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.gff.SequenceOntologyFactory;
39 import jalview.io.gff.SequenceOntologyI;
40 import jalview.schemes.ResidueProperties;
41 import jalview.util.Comparison;
42 import jalview.util.DBRefUtils;
43 import jalview.util.MapList;
44 import jalview.util.MappingUtils;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.Collection;
49 import java.util.Collections;
50 import java.util.Comparator;
51 import java.util.HashMap;
52 import java.util.HashSet;
53 import java.util.Iterator;
54 import java.util.LinkedHashMap;
55 import java.util.List;
57 import java.util.Map.Entry;
59 import java.util.TreeMap;
62 * grab bag of useful alignment manipulation operations Expect these to be
63 * refactored elsewhere at some point.
68 public class AlignmentUtils
72 * given an existing alignment, create a new alignment including all, or up to
73 * flankSize additional symbols from each sequence's dataset sequence
79 public static AlignmentI expandContext(AlignmentI core, int flankSize)
81 List<SequenceI> sq = new ArrayList<SequenceI>();
83 for (SequenceI s : core.getSequences())
85 SequenceI newSeq = s.deriveSequence();
86 final int newSeqStart = newSeq.getStart() - 1;
87 if (newSeqStart > maxoffset
88 && newSeq.getDatasetSequence().getStart() < s.getStart())
90 maxoffset = newSeqStart;
96 maxoffset = Math.min(maxoffset, flankSize);
100 * now add offset left and right to create an expanded alignment
102 for (SequenceI s : sq)
105 while (ds.getDatasetSequence() != null)
107 ds = ds.getDatasetSequence();
109 int s_end = s.findPosition(s.getStart() + s.getLength());
110 // find available flanking residues for sequence
111 int ustream_ds = s.getStart() - ds.getStart();
112 int dstream_ds = ds.getEnd() - s_end;
114 // build new flanked sequence
116 // compute gap padding to start of flanking sequence
117 int offset = maxoffset - ustream_ds;
119 // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
122 if (flankSize < ustream_ds)
124 // take up to flankSize residues
125 offset = maxoffset - flankSize;
126 ustream_ds = flankSize;
128 if (flankSize <= dstream_ds)
130 dstream_ds = flankSize - 1;
133 // TODO use Character.toLowerCase to avoid creating String objects?
134 char[] upstream = new String(ds.getSequence(s.getStart() - 1
135 - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
136 char[] downstream = new String(ds.getSequence(s_end - 1, s_end
137 + dstream_ds)).toLowerCase().toCharArray();
138 char[] coreseq = s.getSequence();
139 char[] nseq = new char[offset + upstream.length + downstream.length
141 char c = core.getGapCharacter();
144 for (; p < offset; p++)
149 System.arraycopy(upstream, 0, nseq, p, upstream.length);
150 System.arraycopy(coreseq, 0, nseq, p + upstream.length,
152 System.arraycopy(downstream, 0, nseq, p + coreseq.length
153 + upstream.length, downstream.length);
154 s.setSequence(new String(nseq));
155 s.setStart(s.getStart() - ustream_ds);
156 s.setEnd(s_end + downstream.length);
158 AlignmentI newAl = new jalview.datamodel.Alignment(
159 sq.toArray(new SequenceI[0]));
160 for (SequenceI s : sq)
162 if (s.getAnnotation() != null)
164 for (AlignmentAnnotation aa : s.getAnnotation())
166 aa.adjustForAlignment(); // JAL-1712 fix
167 newAl.addAnnotation(aa);
171 newAl.setDataset(core.getDataset());
176 * Returns the index (zero-based position) of a sequence in an alignment, or
183 public static int getSequenceIndex(AlignmentI al, SequenceI seq)
187 for (SequenceI alSeq : al.getSequences())
200 * Returns a map of lists of sequences in the alignment, keyed by sequence
201 * name. For use in mapping between different alignment views of the same
204 * @see jalview.datamodel.AlignmentI#getSequencesByName()
206 public static Map<String, List<SequenceI>> getSequencesByName(
209 Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
210 for (SequenceI seq : al.getSequences())
212 String name = seq.getName();
215 List<SequenceI> seqs = theMap.get(name);
218 seqs = new ArrayList<SequenceI>();
219 theMap.put(name, seqs);
228 * Build mapping of protein to cDNA alignment. Mappings are made between
229 * sequences where the cDNA translates to the protein sequence. Any new
230 * mappings are added to the protein alignment. Returns true if any mappings
231 * either already exist or were added, else false.
233 * @param proteinAlignment
234 * @param cdnaAlignment
237 public static boolean mapProteinAlignmentToCdna(
238 final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
240 if (proteinAlignment == null || cdnaAlignment == null)
245 Set<SequenceI> mappedDna = new HashSet<SequenceI>();
246 Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
249 * First pass - map sequences where cross-references exist. This include
250 * 1-to-many mappings to support, for example, variant cDNA.
252 boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
253 cdnaAlignment, mappedDna, mappedProtein, true);
256 * Second pass - map sequences where no cross-references exist. This only
257 * does 1-to-1 mappings and assumes corresponding sequences are in the same
258 * order in the alignments.
260 mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
261 mappedDna, mappedProtein, false);
262 return mappingPerformed;
266 * Make mappings between compatible sequences (where the cDNA translation
267 * matches the protein).
269 * @param proteinAlignment
270 * @param cdnaAlignment
272 * a set of mapped DNA sequences (to add to)
273 * @param mappedProtein
274 * a set of mapped Protein sequences (to add to)
276 * if true, only map sequences where xrefs exist
279 protected static boolean mapProteinToCdna(
280 final AlignmentI proteinAlignment,
281 final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
282 Set<SequenceI> mappedProtein, boolean xrefsOnly)
284 boolean mappingExistsOrAdded = false;
285 List<SequenceI> thisSeqs = proteinAlignment.getSequences();
286 for (SequenceI aaSeq : thisSeqs)
288 boolean proteinMapped = false;
289 AlignedCodonFrame acf = new AlignedCodonFrame();
291 for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
294 * Always try to map if sequences have xref to each other; this supports
295 * variant cDNA or alternative splicing for a protein sequence.
297 * If no xrefs, try to map progressively, assuming that alignments have
298 * mappable sequences in corresponding order. These are not
299 * many-to-many, as that would risk mixing species with similar cDNA
302 if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
308 * Don't map non-xrefd sequences more than once each. This heuristic
309 * allows us to pair up similar sequences in ordered alignments.
312 && (mappedProtein.contains(aaSeq) || mappedDna
317 if (mappingExists(proteinAlignment.getCodonFrames(),
318 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
320 mappingExistsOrAdded = true;
324 MapList map = mapProteinSequenceToCdna(aaSeq, cdnaSeq);
327 acf.addMap(cdnaSeq, aaSeq, map);
328 mappingExistsOrAdded = true;
329 proteinMapped = true;
330 mappedDna.add(cdnaSeq);
331 mappedProtein.add(aaSeq);
337 proteinAlignment.addCodonFrame(acf);
340 return mappingExistsOrAdded;
344 * Answers true if the mappings include one between the given (dataset)
347 public static boolean mappingExists(List<AlignedCodonFrame> mappings,
348 SequenceI aaSeq, SequenceI cdnaSeq)
350 if (mappings != null)
352 for (AlignedCodonFrame acf : mappings)
354 if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
364 * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
365 * must be three times the length of the protein, possibly after ignoring
366 * start and/or stop codons, and must translate to the protein. Returns null
367 * if no mapping is determined.
373 public static MapList mapProteinSequenceToCdna(SequenceI proteinSeq,
377 * Here we handle either dataset sequence set (desktop) or absent (applet).
378 * Use only the char[] form of the sequence to avoid creating possibly large
381 final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
382 char[] aaSeqChars = proteinDataset != null ? proteinDataset
383 .getSequence() : proteinSeq.getSequence();
384 final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
385 char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
386 : cdnaSeq.getSequence();
387 if (aaSeqChars == null || cdnaSeqChars == null)
393 * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
395 final int mappedLength = 3 * aaSeqChars.length;
396 int cdnaLength = cdnaSeqChars.length;
397 int cdnaStart = cdnaSeq.getStart();
398 int cdnaEnd = cdnaSeq.getEnd();
399 final int proteinStart = proteinSeq.getStart();
400 final int proteinEnd = proteinSeq.getEnd();
403 * If lengths don't match, try ignoring stop codon.
405 if (cdnaLength != mappedLength && cdnaLength > 2)
407 String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
409 for (String stop : ResidueProperties.STOP)
411 if (lastCodon.equals(stop))
421 * If lengths still don't match, try ignoring start codon.
424 if (cdnaLength != mappedLength
426 && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
427 .equals(ResidueProperties.START))
434 if (cdnaLength != mappedLength)
438 if (!translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
442 MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[] {
443 proteinStart, proteinEnd }, 3, 1);
448 * Test whether the given cdna sequence, starting at the given offset,
449 * translates to the given amino acid sequence, using the standard translation
450 * table. Designed to fail fast i.e. as soon as a mismatch position is found.
452 * @param cdnaSeqChars
457 protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
460 if (cdnaSeqChars == null || aaSeqChars == null)
466 for (int i = cdnaStart; i < cdnaSeqChars.length - 2
467 && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
469 String codon = String.valueOf(cdnaSeqChars, i, 3);
470 final String translated = ResidueProperties.codonTranslate(codon);
472 * allow * in protein to match untranslatable in dna
474 final char aaRes = aaSeqChars[aaResidue];
475 if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
479 if (translated == null || !(aaRes == translated.charAt(0)))
482 // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
483 // + codon + "(" + translated + ") != " + aaRes));
487 // fail if we didn't match all of the aa sequence
488 return (aaResidue == aaSeqChars.length);
492 * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
493 * currently assumes that we are aligning cDNA to match protein.
496 * the sequence to be realigned
498 * the alignment whose sequence alignment is to be 'copied'
500 * character string represent a gap in the realigned sequence
501 * @param preserveUnmappedGaps
502 * @param preserveMappedGaps
503 * @return true if the sequence was realigned, false if it could not be
505 public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
506 String gap, boolean preserveMappedGaps,
507 boolean preserveUnmappedGaps)
510 * Get any mappings from the source alignment to the target (dataset)
513 // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
514 // all mappings. Would it help to constrain this?
515 List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
516 if (mappings == null || mappings.isEmpty())
522 * Locate the aligned source sequence whose dataset sequence is mapped. We
523 * just take the first match here (as we can't align like more than one
526 SequenceI alignFrom = null;
527 AlignedCodonFrame mapping = null;
528 for (AlignedCodonFrame mp : mappings)
530 alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
531 if (alignFrom != null)
538 if (alignFrom == null)
542 alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
543 preserveMappedGaps, preserveUnmappedGaps);
548 * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
549 * match residues and codons. Flags control whether existing gaps in unmapped
550 * (intron) and mapped (exon) regions are preserved or not. Gaps between
551 * intron and exon are only retained if both flags are set.
558 * @param preserveUnmappedGaps
559 * @param preserveMappedGaps
561 public static void alignSequenceAs(SequenceI alignTo,
562 SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
563 char sourceGap, boolean preserveMappedGaps,
564 boolean preserveUnmappedGaps)
566 // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
568 // aligned and dataset sequence positions, all base zero
572 int basesWritten = 0;
573 char myGapChar = myGap.charAt(0);
574 int ratio = myGap.length();
576 int fromOffset = alignFrom.getStart() - 1;
577 int toOffset = alignTo.getStart() - 1;
578 int sourceGapMappedLength = 0;
579 boolean inExon = false;
580 final char[] thisSeq = alignTo.getSequence();
581 final char[] thatAligned = alignFrom.getSequence();
582 StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
585 * Traverse the 'model' aligned sequence
587 for (char sourceChar : thatAligned)
589 if (sourceChar == sourceGap)
591 sourceGapMappedLength += ratio;
596 * Found a non-gap character. Locate its mapped region if any.
599 // Note mapping positions are base 1, our sequence positions base 0
600 int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
601 sourceDsPos + fromOffset);
602 if (mappedPos == null)
605 * unmapped position; treat like a gap
607 sourceGapMappedLength += ratio;
608 // System.err.println("Can't align: no codon mapping to residue "
609 // + sourceDsPos + "(" + sourceChar + ")");
614 int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
615 int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
616 StringBuilder trailingCopiedGap = new StringBuilder();
619 * Copy dna sequence up to and including this codon. Optionally, include
620 * gaps before the codon starts (in introns) and/or after the codon starts
623 * Note this only works for 'linear' splicing, not reverse or interleaved.
624 * But then 'align dna as protein' doesn't make much sense otherwise.
626 int intronLength = 0;
627 while (basesWritten + toOffset < mappedCodonEnd
628 && thisSeqPos < thisSeq.length)
630 final char c = thisSeq[thisSeqPos++];
634 int sourcePosition = basesWritten + toOffset;
635 if (sourcePosition < mappedCodonStart)
638 * Found an unmapped (intron) base. First add in any preceding gaps
641 if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
643 thisAligned.append(trailingCopiedGap.toString());
644 intronLength += trailingCopiedGap.length();
645 trailingCopiedGap = new StringBuilder();
652 final boolean startOfCodon = sourcePosition == mappedCodonStart;
653 int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
654 preserveUnmappedGaps, sourceGapMappedLength, inExon,
655 trailingCopiedGap.length(), intronLength, startOfCodon);
656 for (int i = 0; i < gapsToAdd; i++)
658 thisAligned.append(myGapChar);
660 sourceGapMappedLength = 0;
663 thisAligned.append(c);
664 trailingCopiedGap = new StringBuilder();
668 if (inExon && preserveMappedGaps)
670 trailingCopiedGap.append(myGapChar);
672 else if (!inExon && preserveUnmappedGaps)
674 trailingCopiedGap.append(myGapChar);
681 * At end of model aligned sequence. Copy any remaining target sequence, optionally
682 * including (intron) gaps.
684 while (thisSeqPos < thisSeq.length)
686 final char c = thisSeq[thisSeqPos++];
687 if (c != myGapChar || preserveUnmappedGaps)
689 thisAligned.append(c);
691 sourceGapMappedLength--;
695 * finally add gaps to pad for any trailing source gaps or
696 * unmapped characters
698 if (preserveUnmappedGaps)
700 while (sourceGapMappedLength > 0)
702 thisAligned.append(myGapChar);
703 sourceGapMappedLength--;
708 * All done aligning, set the aligned sequence.
710 alignTo.setSequence(new String(thisAligned));
714 * Helper method to work out how many gaps to insert when realigning.
716 * @param preserveMappedGaps
717 * @param preserveUnmappedGaps
718 * @param sourceGapMappedLength
720 * @param trailingCopiedGap
721 * @param intronLength
722 * @param startOfCodon
725 protected static int calculateGapsToInsert(boolean preserveMappedGaps,
726 boolean preserveUnmappedGaps, int sourceGapMappedLength,
727 boolean inExon, int trailingGapLength, int intronLength,
728 final boolean startOfCodon)
734 * Reached start of codon. Ignore trailing gaps in intron unless we are
735 * preserving gaps in both exon and intron. Ignore them anyway if the
736 * protein alignment introduces a gap at least as large as the intronic
739 if (inExon && !preserveMappedGaps)
741 trailingGapLength = 0;
743 if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
745 trailingGapLength = 0;
749 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
753 if (intronLength + trailingGapLength <= sourceGapMappedLength)
755 gapsToAdd = sourceGapMappedLength - intronLength;
759 gapsToAdd = Math.min(intronLength + trailingGapLength
760 - sourceGapMappedLength, trailingGapLength);
767 * second or third base of codon; check for any gaps in dna
769 if (!preserveMappedGaps)
771 trailingGapLength = 0;
773 gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
779 * Returns a list of sequences mapped from the given sequences and aligned
780 * (gapped) in the same way. For example, the cDNA for aligned protein, where
781 * a single gap in protein generates three gaps in cDNA.
784 * @param gapCharacter
788 public static List<SequenceI> getAlignedTranslation(
789 List<SequenceI> sequences, char gapCharacter,
790 Set<AlignedCodonFrame> mappings)
792 List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
794 for (SequenceI seq : sequences)
796 List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
798 alignedSeqs.addAll(mapped);
804 * Returns sequences aligned 'like' the source sequence, as mapped by the
805 * given mappings. Normally we expect zero or one 'mapped' sequences, but this
806 * will support 1-to-many as well.
809 * @param gapCharacter
813 protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
814 char gapCharacter, Set<AlignedCodonFrame> mappings)
816 List<SequenceI> result = new ArrayList<SequenceI>();
817 for (AlignedCodonFrame mapping : mappings)
819 if (mapping.involvesSequence(seq))
821 SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
832 * Returns the translation of 'seq' (as held in the mapping) with
833 * corresponding alignment (gaps).
836 * @param gapCharacter
840 protected static SequenceI getAlignedTranslation(SequenceI seq,
841 char gapCharacter, AlignedCodonFrame mapping)
843 String gap = String.valueOf(gapCharacter);
844 boolean toDna = false;
846 SequenceI mapTo = mapping.getDnaForAaSeq(seq);
849 // mapping is from protein to nucleotide
851 // should ideally get gap count ratio from mapping
852 gap = String.valueOf(new char[] { gapCharacter, gapCharacter,
857 // mapping is from nucleotide to protein
858 mapTo = mapping.getAaForDnaSeq(seq);
861 StringBuilder newseq = new StringBuilder(seq.getLength()
864 int residueNo = 0; // in seq, base 1
865 int[] phrase = new int[fromRatio];
866 int phraseOffset = 0;
868 boolean first = true;
869 final Sequence alignedSeq = new Sequence("", "");
871 for (char c : seq.getSequence())
873 if (c == gapCharacter)
876 if (gapWidth >= fromRatio)
884 phrase[phraseOffset++] = residueNo + 1;
885 if (phraseOffset == fromRatio)
888 * Have read a whole codon (or protein residue), now translate: map
889 * source phrase to positions in target sequence add characters at
890 * these positions to newseq Note mapping positions are base 1, our
891 * sequence positions base 0.
893 SearchResults sr = new SearchResults();
894 for (int pos : phrase)
896 mapping.markMappedRegion(seq, pos, sr);
898 newseq.append(sr.getCharacters());
902 // Hack: Copy sequence dataset, name and description from
903 // SearchResults.match[0].sequence
904 // TODO? carry over sequence names from original 'complement'
906 SequenceI mappedTo = sr.getResultSequence(0);
907 alignedSeq.setName(mappedTo.getName());
908 alignedSeq.setDescription(mappedTo.getDescription());
909 alignedSeq.setDatasetSequence(mappedTo);
916 alignedSeq.setSequence(newseq.toString());
921 * Realigns the given protein to match the alignment of the dna, using codon
922 * mappings to translate aligned codon positions to protein residues.
925 * the alignment whose sequences are realigned by this method
927 * the dna alignment whose alignment we are 'copying'
928 * @return the number of sequences that were realigned
930 public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
932 List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
933 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
934 protein, dna, unmappedProtein);
935 return alignProteinAs(protein, alignedCodons, unmappedProtein);
939 * Builds a map whose key is an aligned codon position (3 alignment column
940 * numbers base 0), and whose value is a map from protein sequence to each
941 * protein's peptide residue for that codon. The map generates an ordering of
942 * the codons, and allows us to read off the peptides at each position in
943 * order to assemble 'aligned' protein sequences.
946 * the protein alignment
948 * the coding dna alignment
949 * @param unmappedProtein
950 * any unmapped proteins are added to this list
953 protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
954 AlignmentI protein, AlignmentI dna,
955 List<SequenceI> unmappedProtein)
958 * maintain a list of any proteins with no mappings - these will be
959 * rendered 'as is' in the protein alignment as we can't align them
961 unmappedProtein.addAll(protein.getSequences());
963 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
966 * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
967 * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
968 * comparator keeps the codon positions ordered.
970 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
971 new CodonComparator());
973 for (SequenceI dnaSeq : dna.getSequences())
975 for (AlignedCodonFrame mapping : mappings)
977 SequenceI prot = mapping.findAlignedSequence(
978 dnaSeq.getDatasetSequence(), protein);
981 Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
982 addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
983 seqMap, alignedCodons);
984 unmappedProtein.remove(prot);
990 * Finally add any unmapped peptide start residues (e.g. for incomplete
991 * codons) as if at the codon position before the second residue
993 int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
994 addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
996 return alignedCodons;
1000 * Scans for any protein mapped from position 2 (meaning unmapped start
1001 * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
1002 * preceding position in the alignment
1004 * @param alignedCodons
1005 * the codon-to-peptide map
1006 * @param mappedSequenceCount
1007 * the number of distinct sequences in the map
1009 protected static void addUnmappedPeptideStarts(
1010 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1011 int mappedSequenceCount)
1013 // TODO there must be an easier way! root problem is that our mapping data
1014 // model does not include phase so can't map part of a codon to a peptide
1015 List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
1016 AlignedCodon lastCodon = null;
1017 Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
1019 for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
1022 for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
1025 SequenceI seq = sequenceCodon.getKey();
1026 if (sequencesChecked.contains(seq))
1030 sequencesChecked.add(seq);
1031 AlignedCodon codon = sequenceCodon.getValue();
1032 if (codon.peptideCol > 1)
1035 .println("Problem mapping protein with >1 unmapped start positions: "
1038 else if (codon.peptideCol == 1)
1041 * first position (peptideCol == 0) was unmapped - add it
1043 if (lastCodon != null)
1045 AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
1046 lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
1048 toAdd.put(seq, firstPeptide);
1053 * unmapped residue at start of alignment (no prior column) -
1054 * 'insert' at nominal codon [0, 0, 0]
1056 AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
1057 String.valueOf(seq.getCharAt(0)), 0);
1058 toAdd.put(seq, firstPeptide);
1061 if (sequencesChecked.size() == mappedSequenceCount)
1063 // no need to check past first mapped position in all sequences
1067 lastCodon = entry.getKey();
1071 * add any new codons safely after iterating over the map
1073 for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
1075 addCodonToMap(alignedCodons, startCodon.getValue(),
1076 startCodon.getKey());
1081 * Update the aligned protein sequences to match the codon alignments given in
1085 * @param alignedCodons
1086 * an ordered map of codon positions (columns), with sequence/peptide
1087 * values present in each column
1088 * @param unmappedProtein
1091 protected static int alignProteinAs(AlignmentI protein,
1092 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1093 List<SequenceI> unmappedProtein)
1096 * Prefill aligned sequences with gaps before inserting aligned protein
1099 int alignedWidth = alignedCodons.size();
1100 char[] gaps = new char[alignedWidth];
1101 Arrays.fill(gaps, protein.getGapCharacter());
1102 String allGaps = String.valueOf(gaps);
1103 for (SequenceI seq : protein.getSequences())
1105 if (!unmappedProtein.contains(seq))
1107 seq.setSequence(allGaps);
1112 for (AlignedCodon codon : alignedCodons.keySet())
1114 final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1116 for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1118 // place translated codon at its column position in sequence
1119 entry.getKey().getSequence()[column] = entry.getValue().product
1128 * Populate the map of aligned codons by traversing the given sequence
1129 * mapping, locating the aligned positions of mapped codons, and adding those
1130 * positions and their translation products to the map.
1133 * the aligned sequence we are mapping from
1135 * the sequence to be aligned to the codons
1137 * the gap character in the dna sequence
1139 * a mapping to a sequence translation
1140 * @param alignedCodons
1141 * the map we are building up
1143 static void addCodonPositions(SequenceI dna, SequenceI protein,
1144 char gapChar, Mapping seqMap,
1145 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1147 Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1150 * add codon positions, and their peptide translations, to the alignment
1151 * map, while remembering the first codon mapped
1153 while (codons.hasNext())
1157 AlignedCodon codon = codons.next();
1158 addCodonToMap(alignedCodons, codon, protein);
1159 } catch (IncompleteCodonException e)
1161 // possible incomplete trailing codon - ignore
1167 * Helper method to add a codon-to-peptide entry to the aligned codons map
1169 * @param alignedCodons
1173 protected static void addCodonToMap(
1174 Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1175 AlignedCodon codon, SequenceI protein)
1177 Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1178 if (seqProduct == null)
1180 seqProduct = new HashMap<SequenceI, AlignedCodon>();
1181 alignedCodons.put(codon, seqProduct);
1183 seqProduct.put(protein, codon);
1187 * Returns true if a cDNA/Protein mapping either exists, or could be made,
1188 * between at least one pair of sequences in the two alignments. Currently,
1191 * <li>One alignment must be nucleotide, and the other protein</li>
1192 * <li>At least one pair of sequences must be already mapped, or mappable</li>
1193 * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1194 * <li>The translation may ignore start and stop codons if present in the
1202 public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1204 if (al1 == null || al2 == null)
1210 * Require one nucleotide and one protein
1212 if (al1.isNucleotide() == al2.isNucleotide())
1216 AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1217 AlignmentI protein = dna == al1 ? al2 : al1;
1218 List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1219 for (SequenceI dnaSeq : dna.getSequences())
1221 for (SequenceI proteinSeq : protein.getSequences())
1223 if (isMappable(dnaSeq, proteinSeq, mappings))
1233 * Returns true if the dna sequence is mapped, or could be mapped, to the
1241 protected static boolean isMappable(SequenceI dnaSeq,
1242 SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1244 if (dnaSeq == null || proteinSeq == null)
1249 SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1250 .getDatasetSequence();
1251 SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1252 : proteinSeq.getDatasetSequence();
1254 for (AlignedCodonFrame mapping : mappings)
1256 if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1266 * Just try to make a mapping (it is not yet stored), test whether
1269 return mapProteinSequenceToCdna(proteinDs, dnaDs) != null;
1273 * Finds any reference annotations associated with the sequences in
1274 * sequenceScope, that are not already added to the alignment, and adds them
1275 * to the 'candidates' map. Also populates a lookup table of annotation
1276 * labels, keyed by calcId, for use in constructing tooltips or the like.
1278 * @param sequenceScope
1279 * the sequences to scan for reference annotations
1280 * @param labelForCalcId
1281 * (optional) map to populate with label for calcId
1283 * map to populate with annotations for sequence
1285 * the alignment to check for presence of annotations
1287 public static void findAddableReferenceAnnotations(
1288 List<SequenceI> sequenceScope,
1289 Map<String, String> labelForCalcId,
1290 final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1293 if (sequenceScope == null)
1299 * For each sequence in scope, make a list of any annotations on the
1300 * underlying dataset sequence which are not already on the alignment.
1302 * Add to a map of { alignmentSequence, <List of annotations to add> }
1304 for (SequenceI seq : sequenceScope)
1306 SequenceI dataset = seq.getDatasetSequence();
1307 if (dataset == null)
1311 AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1312 if (datasetAnnotations == null)
1316 final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1317 for (AlignmentAnnotation dsann : datasetAnnotations)
1320 * Find matching annotations on the alignment. If none is found, then
1321 * add this annotation to the list of 'addable' annotations for this
1324 final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1325 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1326 if (!matchedAlignmentAnnotations.iterator().hasNext())
1329 if (labelForCalcId != null)
1331 labelForCalcId.put(dsann.getCalcId(), dsann.label);
1336 * Save any addable annotations for this sequence
1338 if (!result.isEmpty())
1340 candidates.put(seq, result);
1346 * Adds annotations to the top of the alignment annotations, in the same order
1347 * as their related sequences.
1349 * @param annotations
1350 * the annotations to add
1352 * the alignment to add them to
1353 * @param selectionGroup
1354 * current selection group (or null if none)
1356 public static void addReferenceAnnotations(
1357 Map<SequenceI, List<AlignmentAnnotation>> annotations,
1358 final AlignmentI alignment, final SequenceGroup selectionGroup)
1360 for (SequenceI seq : annotations.keySet())
1362 for (AlignmentAnnotation ann : annotations.get(seq))
1364 AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1366 int endRes = ann.annotations.length;
1367 if (selectionGroup != null)
1369 startRes = selectionGroup.getStartRes();
1370 endRes = selectionGroup.getEndRes();
1372 copyAnn.restrict(startRes, endRes);
1375 * Add to the sequence (sets copyAnn.datasetSequence), unless the
1376 * original annotation is already on the sequence.
1378 if (!seq.hasAnnotation(ann))
1380 seq.addAlignmentAnnotation(copyAnn);
1383 copyAnn.adjustForAlignment();
1384 // add to the alignment and set visible
1385 alignment.addAnnotation(copyAnn);
1386 copyAnn.visible = true;
1392 * Set visibility of alignment annotations of specified types (labels), for
1393 * specified sequences. This supports controls like
1394 * "Show all secondary structure", "Hide all Temp factor", etc.
1396 * @al the alignment to scan for annotations
1398 * the types (labels) of annotations to be updated
1399 * @param forSequences
1400 * if not null, only annotations linked to one of these sequences are
1401 * in scope for update; if null, acts on all sequence annotations
1403 * if this flag is true, 'types' is ignored (label not checked)
1405 * if true, set visibility on, else set off
1407 public static void showOrHideSequenceAnnotations(AlignmentI al,
1408 Collection<String> types, List<SequenceI> forSequences,
1409 boolean anyType, boolean doShow)
1411 for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1413 if (anyType || types.contains(aa.label))
1415 if ((aa.sequenceRef != null)
1416 && (forSequences == null || forSequences
1417 .contains(aa.sequenceRef)))
1419 aa.visible = doShow;
1426 * Returns true if either sequence has a cross-reference to the other
1432 public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1434 // Note: moved here from class CrossRef as the latter class has dependencies
1435 // not availability to the applet's classpath
1436 return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1440 * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1441 * that sequence name is structured as Source|AccessionId.
1447 public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1449 if (seq1 == null || seq2 == null)
1453 String name = seq2.getName();
1454 final DBRefEntry[] xrefs = seq1.getDBRefs();
1457 for (DBRefEntry xref : xrefs)
1459 String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1460 // case-insensitive test, consistent with DBRefEntry.equalRef()
1461 if (xrefName.equalsIgnoreCase(name))
1471 * Constructs an alignment consisting of the mapped (CDS) regions in the given
1472 * nucleotide sequences, and updates mappings to match. The new sequences are
1473 * aligned as per the original sequences (with gapped columns omitted).
1476 * aligned dna sequences
1478 * from dna to protein; these are replaced with new mappings
1480 * @return an alignment whose sequences are the cds-only parts of the dna
1481 * sequences (or null if no mappings are found)
1483 public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1484 List<AlignedCodonFrame> mappings, char gapChar)
1486 List<int[]> cdsColumns = findCdsColumns(dna);
1489 * create CDS sequences and new mappings
1490 * (from cdna to cds, and cds to peptide)
1492 List<AlignedCodonFrame> newMappings = new ArrayList<AlignedCodonFrame>();
1493 List<SequenceI> cdsSequences = new ArrayList<SequenceI>();
1495 for (SequenceI dnaSeq : dna)
1497 final SequenceI ds = dnaSeq.getDatasetSequence();
1498 List<AlignedCodonFrame> seqMappings = MappingUtils
1499 .findMappingsForSequence(ds, mappings);
1500 for (AlignedCodonFrame acf : seqMappings)
1502 AlignedCodonFrame newMapping = new AlignedCodonFrame();
1503 final List<SequenceI> mappedCds = makeCdsSequences(dnaSeq, acf,
1504 cdsColumns, newMapping, gapChar);
1505 if (!mappedCds.isEmpty())
1507 cdsSequences.addAll(mappedCds);
1508 newMappings.add(newMapping);
1512 AlignmentI al = new Alignment(
1513 cdsSequences.toArray(new SequenceI[cdsSequences.size()]));
1514 al.setGapCharacter(gapChar);
1515 al.setDataset(null);
1518 * Replace the old mappings with the new ones
1521 mappings.addAll(newMappings);
1527 * Returns a consolidated list of column ranges where at least one sequence
1528 * has a CDS feature. This assumes CDS features are on genomic sequence i.e.
1529 * are for contiguous CDS ranges (no gaps).
1534 public static List<int[]> findCdsColumns(SequenceI[] seqs)
1536 // TODO use refactored code from AlignViewController
1537 // markColumnsContainingFeatures, not reinvent the wheel!
1539 List<int[]> result = new ArrayList<int[]>();
1540 for (SequenceI seq : seqs)
1542 result.addAll(findCdsColumns(seq));
1546 * sort and compact the list into ascending, non-overlapping ranges
1548 Collections.sort(result, new Comparator<int[]>()
1551 public int compare(int[] o1, int[] o2)
1553 return Integer.compare(o1[0], o2[0]);
1556 result = MapList.coalesceRanges(result);
1561 public static List<int[]> findCdsColumns(SequenceI seq)
1563 List<int[]> result = new ArrayList<int[]>();
1564 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1565 SequenceFeature[] sfs = seq.getSequenceFeatures();
1568 for (SequenceFeature sf : sfs)
1570 if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1572 int colStart = seq.findIndex(sf.getBegin());
1573 int colEnd = seq.findIndex(sf.getEnd());
1574 result.add(new int[] { colStart, colEnd });
1582 * Answers true if all sequences have a gap at (or do not extend to) the
1583 * specified column position (base 1)
1589 public static boolean isGappedColumn(List<SequenceI> seqs, int col)
1593 for (SequenceI seq : seqs)
1595 if (!Comparison.isGap(seq.getCharAt(col - 1)))
1605 * Returns the column ranges (base 1) of each aligned sequence that are
1606 * involved in any mapping. This is a helper method for aligning protein
1607 * products of aligned transcripts.
1609 * @param mappedSequences
1610 * (possibly gapped) dna sequences
1614 protected static List<List<int[]>> getMappedColumns(
1615 List<SequenceI> mappedSequences, List<AlignedCodonFrame> mappings)
1617 List<List<int[]>> result = new ArrayList<List<int[]>>();
1618 for (SequenceI seq : mappedSequences)
1620 List<int[]> columns = new ArrayList<int[]>();
1621 List<AlignedCodonFrame> seqMappings = MappingUtils
1622 .findMappingsForSequence(seq, mappings);
1623 for (AlignedCodonFrame mapping : seqMappings)
1625 List<Mapping> maps = mapping.getMappingsForSequence(seq);
1626 for (Mapping map : maps)
1629 * Get the codon regions as { [2, 5], [7, 12], [14, 14] etc }
1630 * Find and add the overall aligned column range for each
1632 for (int[] cdsRange : map.getMap().getFromRanges())
1634 int startPos = cdsRange[0];
1635 int endPos = cdsRange[1];
1636 int startCol = seq.findIndex(startPos);
1637 int endCol = seq.findIndex(endPos);
1638 columns.add(new int[] { startCol, endCol });
1642 result.add(columns);
1648 * Helper method to make cds-only sequences and populate their mappings to
1651 * For example, if ggCCaTTcGAg has mappings [3, 4, 6, 7, 9, 10] to protein
1652 * then generate a sequence CCTTGA with mapping [1, 6] to the same protein
1655 * Typically eukaryotic dna will include cds encoding for a single peptide
1656 * sequence i.e. return a single result. Bacterial dna may have overlapping
1657 * cds mappings coding for multiple peptides so return multiple results
1658 * (example EMBL KF591215).
1661 * a dna aligned sequence
1663 * containing one or more mappings of the sequence to protein
1664 * @param ungappedCdsColumns
1665 * @param newMappings
1666 * the new mapping to populate, from the cds-only sequences to their
1667 * mapped protein sequences
1670 protected static List<SequenceI> makeCdsSequences(SequenceI dnaSeq,
1671 AlignedCodonFrame mapping, List<int[]> ungappedCdsColumns,
1672 AlignedCodonFrame newMappings, char gapChar)
1674 List<SequenceI> cdsSequences = new ArrayList<SequenceI>();
1675 List<Mapping> seqMappings = mapping.getMappingsForSequence(dnaSeq);
1677 for (Mapping seqMapping : seqMappings)
1679 SequenceI cds = makeCdsSequence(dnaSeq, seqMapping,
1680 ungappedCdsColumns, gapChar);
1681 cdsSequences.add(cds);
1684 * add new mappings, from dna to cds, and from cds to peptide
1686 MapList dnaToCds = addCdsMappings(dnaSeq.getDatasetSequence(), cds,
1687 seqMapping, newMappings);
1690 * transfer any features on dna that overlap the CDS
1692 transferFeatures(dnaSeq, cds, dnaToCds, null, SequenceOntologyI.CDS);
1694 return cdsSequences;
1698 * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1699 * feature start/end ranges, optionally omitting specified feature types.
1700 * Returns the number of features copied.
1705 * if not null, only features of this type are copied (including
1706 * subtypes in the Sequence Ontology)
1708 * the mapping from 'fromSeq' to 'toSeq'
1711 public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1712 MapList mapping, String select, String... omitting)
1714 SequenceI copyTo = toSeq;
1715 while (copyTo.getDatasetSequence() != null)
1717 copyTo = copyTo.getDatasetSequence();
1720 SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1722 SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1725 for (SequenceFeature sf : sfs)
1727 String type = sf.getType();
1728 if (select != null && !so.isA(type, select))
1732 boolean omit = false;
1733 for (String toOmit : omitting)
1735 if (type.equals(toOmit))
1746 * locate the mapped range - null if either start or end is
1747 * not mapped (no partial overlaps are calculated)
1749 int start = sf.getBegin();
1750 int end = sf.getEnd();
1751 int[] mappedTo = mapping.locateInTo(start, end);
1753 * if whole exon range doesn't map, try interpreting it
1754 * as 5' or 3' exon overlapping the CDS range
1756 if (mappedTo == null)
1758 mappedTo = mapping.locateInTo(end, end);
1759 if (mappedTo != null)
1762 * end of exon is in CDS range - 5' overlap
1763 * to a range from the start of the peptide
1768 if (mappedTo == null)
1770 mappedTo = mapping.locateInTo(start, start);
1771 if (mappedTo != null)
1774 * start of exon is in CDS range - 3' overlap
1775 * to a range up to the end of the peptide
1777 mappedTo[1] = toSeq.getLength();
1780 if (mappedTo != null)
1782 SequenceFeature copy = new SequenceFeature(sf);
1783 copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1784 copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1785 copyTo.addSequenceFeature(copy);
1794 * Creates and adds mappings
1796 * <li>from cds to peptide</li>
1797 * <li>from dna to cds</li>
1799 * and returns the dna-to-cds mapping
1804 * @param newMappings
1807 protected static MapList addCdsMappings(SequenceI dnaSeq,
1808 SequenceI cdsSeq, Mapping dnaMapping,
1809 AlignedCodonFrame newMappings)
1811 cdsSeq.createDatasetSequence();
1814 * CDS to peptide is just a contiguous 3:1 mapping, with
1815 * the peptide ranges taken unchanged from the dna mapping
1817 List<int[]> cdsRanges = new ArrayList<int[]>();
1818 SequenceI cdsDataset = cdsSeq.getDatasetSequence();
1819 cdsRanges.add(new int[] { 1, cdsDataset.getLength() });
1820 MapList cdsToPeptide = new MapList(cdsRanges, dnaMapping.getMap()
1821 .getToRanges(), 3, 1);
1822 newMappings.addMap(cdsDataset, dnaMapping.getTo(), cdsToPeptide);
1825 * dna 'from' ranges map 1:1 to the contiguous extracted CDS
1827 MapList dnaToCds = new MapList(dnaMapping.getMap().getFromRanges(),
1829 newMappings.addMap(dnaSeq, cdsDataset, dnaToCds);
1834 * Makes and returns a CDS-only sequence, where the CDS regions are identified
1835 * as the 'from' ranges of the mapping on the dna.
1838 * nucleotide sequence
1840 * mappings from CDS regions of nucleotide
1841 * @param ungappedCdsColumns
1844 protected static SequenceI makeCdsSequence(SequenceI dnaSeq,
1845 Mapping seqMapping, List<int[]> ungappedCdsColumns, char gapChar)
1847 int cdsWidth = MappingUtils.getLength(ungappedCdsColumns);
1850 * populate CDS columns with the aligned
1851 * column character if that column is mapped (which may be a gap
1852 * if an intron interrupts a codon), else with a gap
1854 List<int[]> fromRanges = seqMapping.getMap().getFromRanges();
1855 char[] cdsChars = new char[cdsWidth];
1857 for (int[] columns : ungappedCdsColumns)
1859 for (int i = columns[0]; i <= columns[1]; i++)
1861 char dnaChar = dnaSeq.getCharAt(i - 1);
1862 if (Comparison.isGap(dnaChar))
1864 cdsChars[pos] = gapChar;
1868 int seqPos = dnaSeq.findPosition(i - 1);
1869 if (MappingUtils.contains(fromRanges, seqPos))
1871 cdsChars[pos] = dnaChar;
1875 cdsChars[pos] = gapChar;
1881 SequenceI cdsSequence = new Sequence(dnaSeq.getName(),
1882 String.valueOf(cdsChars));
1884 transferDbRefs(seqMapping.getTo(), cdsSequence);
1890 * Locate any xrefs to CDS databases on the protein product and attach to the
1891 * CDS sequence. Also add as a sub-token of the sequence name.
1896 protected static void transferDbRefs(SequenceI from, SequenceI to)
1898 String cdsAccId = FeatureProperties.getCodingFeature(DBRefSource.EMBL);
1899 DBRefEntry[] cdsRefs = DBRefUtils.selectRefs(from.getDBRefs(),
1900 DBRefSource.CODINGDBS);
1901 if (cdsRefs != null)
1903 for (DBRefEntry cdsRef : cdsRefs)
1905 to.addDBRef(new DBRefEntry(cdsRef));
1906 cdsAccId = cdsRef.getAccessionId();
1909 if (!to.getName().contains(cdsAccId))
1911 to.setName(to.getName() + "|" + cdsAccId);