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.api.AlignViewportI;
24 import jalview.datamodel.AlignedCodon;
25 import jalview.datamodel.AlignedCodonFrame;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.Annotation;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.DBRefSource;
32 import jalview.datamodel.FeatureProperties;
33 import jalview.datamodel.GraphLine;
34 import jalview.datamodel.Mapping;
35 import jalview.datamodel.Sequence;
36 import jalview.datamodel.SequenceFeature;
37 import jalview.datamodel.SequenceI;
38 import jalview.schemes.ResidueProperties;
39 import jalview.util.Comparison;
40 import jalview.util.DBRefUtils;
41 import jalview.util.MapList;
42 import jalview.util.ShiftList;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Comparator;
47 import java.util.Iterator;
48 import java.util.List;
52 private static final String STOP_ASTERIX = "*";
54 private static final Comparator<AlignedCodon> comparator = new CodonComparator();
57 * 'final' variables describe the inputs to the translation, which should not
60 private final List<SequenceI> selection;
62 private final String[] seqstring;
64 private final Iterator<int[]> contigs;
66 private final char gapChar;
68 private final AlignmentAnnotation[] annotations;
70 private final int dnaWidth;
72 private final AlignmentI dataset;
75 * Working variables for the translation.
77 * The width of the translation-in-progress protein alignment.
79 private int aaWidth = 0;
82 * This array will be built up so that position i holds the codon positions
83 * e.g. [7, 9, 10] that match column i (base 0) in the aligned translation.
84 * Note this implies a contract that if two codons do not align exactly, their
85 * translated products must occupy different column positions.
87 private AlignedCodon[] alignedCodons;
90 * Constructor given a viewport and the visible contigs.
93 * @param visibleContigs
95 public Dna(AlignViewportI viewport, Iterator<int[]> visibleContigs)
97 this.selection = Arrays.asList(viewport.getSequenceSelection());
98 this.seqstring = viewport.getViewAsString(true);
99 this.contigs = visibleContigs;
100 this.gapChar = viewport.getGapCharacter();
101 this.annotations = viewport.getAlignment().getAlignmentAnnotation();
102 this.dnaWidth = viewport.getAlignment().getWidth();
103 this.dataset = viewport.getAlignment().getDataset();
107 * Test whether codon positions cdp1 should align before, with, or after cdp2.
108 * Returns zero if all positions match (or either argument is null). Returns
109 * -1 if any position in the first codon precedes the corresponding position
110 * in the second codon. Else returns +1 (some position in the second codon
111 * precedes the corresponding position in the first).
113 * Note this is not necessarily symmetric, for example:
115 * <li>compareCodonPos([2,5,6], [3,4,5]) returns -1</li>
116 * <li>compareCodonPos([3,4,5], [2,5,6]) also returns -1</li>
123 public static final int compareCodonPos(AlignedCodon ac1, AlignedCodon ac2)
125 return comparator.compare(ac1, ac2);
126 // return jalview_2_8_2compare(ac1, ac2);
130 * Codon comparison up to Jalview 2.8.2. This rule is sequence order dependent
131 * - see http://issues.jalview.org/browse/JAL-1635
137 private static int jalview_2_8_2compare(AlignedCodon ac1,
140 if (ac1 == null || ac2 == null || (ac1.equals(ac2)))
144 if (ac1.pos1 < ac2.pos1 || ac1.pos2 < ac2.pos2 || ac1.pos3 < ac2.pos3)
146 // one base in cdp1 precedes the corresponding base in the other codon
149 // one base in cdp1 appears after the corresponding base in the other codon.
157 public AlignmentI translateCdna()
159 AlignedCodonFrame acf = new AlignedCodonFrame();
161 alignedCodons = new AlignedCodon[dnaWidth];
164 int sSize = selection.size();
165 List<SequenceI> pepseqs = new ArrayList<>();
166 for (s = 0; s < sSize; s++)
168 SequenceI newseq = translateCodingRegion(selection.get(s),
169 seqstring[s], acf, pepseqs);
174 SequenceI ds = newseq;
177 while (ds.getDatasetSequence() != null)
179 ds = ds.getDatasetSequence();
181 dataset.addSequence(ds);
186 SequenceI[] newseqs = pepseqs.toArray(new SequenceI[pepseqs.size()]);
187 AlignmentI al = new Alignment(newseqs);
188 // ensure we look aligned.
190 // link the protein translation to the DNA dataset
191 al.setDataset(dataset);
192 translateAlignedAnnotations(al, acf);
193 al.addCodonFrame(acf);
198 * fake the collection of DbRefs with associated exon mappings to identify if
199 * a translation would generate distinct product in the currently selected
206 public static boolean canTranslate(SequenceI[] selection,
209 for (int gd = 0; gd < selection.length; gd++)
211 SequenceI dna = selection[gd];
212 DBRefEntry[] dnarefs = DBRefUtils.selectRefs(dna.getDBRefs(),
213 jalview.datamodel.DBRefSource.DNACODINGDBS);
216 // intersect with pep
217 List<DBRefEntry> mappedrefs = new ArrayList<>();
218 DBRefEntry[] refs = dna.getDBRefs();
219 for (int d = 0; d < refs.length; d++)
221 if (refs[d].getMap() != null && refs[d].getMap().getMap() != null
222 && refs[d].getMap().getMap().getFromRatio() == 3
223 && refs[d].getMap().getMap().getToRatio() == 1)
225 mappedrefs.add(refs[d]); // add translated protein maps
228 dnarefs = mappedrefs.toArray(new DBRefEntry[mappedrefs.size()]);
229 for (int d = 0; d < dnarefs.length; d++)
231 Mapping mp = dnarefs[d].getMap();
234 for (int vc = 0; vc < viscontigs.length; vc += 2)
236 int[] mpr = mp.locateMappedRange(viscontigs[vc],
251 * Translate nucleotide alignment annotations onto translated amino acid
252 * alignment using codon mapping codons
255 * the translated protein alignment
257 protected void translateAlignedAnnotations(AlignmentI al,
258 AlignedCodonFrame acf)
260 // Can only do this for columns with consecutive codons, or where
261 // annotation is sequence associated.
263 if (annotations != null)
265 for (AlignmentAnnotation annotation : annotations)
268 * Skip hidden or autogenerated annotation. Also (for now), RNA
269 * secondary structure annotation. If we want to show this against
270 * protein we need a smarter way to 'translate' without generating
271 * invalid (unbalanced) structure annotation.
273 if (annotation.autoCalculated || !annotation.visible
274 || annotation.isRNA())
280 Annotation[] anots = (annotation.annotations == null) ? null
281 : new Annotation[aSize];
284 for (int a = 0; a < aSize; a++)
286 // process through codon map.
287 if (a < alignedCodons.length && alignedCodons[a] != null
288 && alignedCodons[a].pos1 == (alignedCodons[a].pos3 - 2))
290 anots[a] = getCodonAnnotation(alignedCodons[a],
291 annotation.annotations);
296 AlignmentAnnotation aa = new AlignmentAnnotation(annotation.label,
297 annotation.description, anots);
298 aa.graph = annotation.graph;
299 aa.graphGroup = annotation.graphGroup;
300 aa.graphHeight = annotation.graphHeight;
301 if (annotation.getThreshold() != null)
303 aa.setThreshold(new GraphLine(annotation.getThreshold()));
305 if (annotation.hasScore)
307 aa.setScore(annotation.getScore());
310 final SequenceI seqRef = annotation.sequenceRef;
313 SequenceI aaSeq = acf.getAaForDnaSeq(seqRef);
316 // aa.compactAnnotationArray(); // throw away alignment annotation
318 aa.setSequenceRef(aaSeq);
320 aa.createSequenceMapping(aaSeq, aaSeq.getStart(), true);
321 aa.adjustForAlignment();
322 aaSeq.addAlignmentAnnotation(aa);
325 al.addAnnotation(aa);
330 private static Annotation getCodonAnnotation(AlignedCodon is,
331 Annotation[] annotations)
333 // Have a look at all the codon positions for annotation and put the first
334 // one found into the translated annotation pos.
336 Annotation annot = null;
337 for (int p = 1; p <= 3; p++)
339 int dnaCol = is.getBaseColumn(p);
340 if (annotations[dnaCol] != null)
344 annot = new Annotation(annotations[dnaCol]);
350 Annotation cpy = new Annotation(annotations[dnaCol]);
351 if (annot.colour == null)
353 annot.colour = cpy.colour;
355 if (annot.description == null || annot.description.length() == 0)
357 annot.description = cpy.description;
359 if (annot.displayCharacter == null)
361 annot.displayCharacter = cpy.displayCharacter;
363 if (annot.secondaryStructure == 0)
365 annot.secondaryStructure = cpy.secondaryStructure;
367 annot.value += cpy.value;
374 annot.value /= contrib;
380 * Translate a na sequence
383 * sequence displayed under viscontigs visible columns
385 * ORF read in some global alignment reference frame
387 * Definition of global ORF alignment reference frame
389 * @return sequence ready to be added to alignment.
391 protected SequenceI translateCodingRegion(SequenceI selection,
392 String seqstring, AlignedCodonFrame acf,
393 List<SequenceI> proteinSeqs)
395 List<int[]> skip = new ArrayList<>();
396 int skipint[] = null;
397 ShiftList vismapping = new ShiftList(); // map from viscontigs to seqstring
402 int[] lastregion = null;
403 while (contigs.hasNext())
405 int[] region = contigs.next();
406 if (lastregion == null)
408 vismapping.addShift(npos, region[0]);
413 vismapping.addShift(npos, region[0] - lastregion[1] + 1);
419 int[] scontigs = new int[vc];
421 while (contigs.hasNext())
423 int[] region = contigs.next();
424 scontigs[vc] = region[0];
425 scontigs[vc + 1] = region[1];
429 // allocate a roughly sized buffer for the protein sequence
430 StringBuilder protein = new StringBuilder(seqstring.length() / 2);
431 String seq = seqstring.replace('U', 'T').replace('u', 'T');
432 char codon[] = new char[3];
433 int cdp[] = new int[3];
439 for (npos = 0, nend = seq.length(); npos < nend; npos++)
441 if (!Comparison.isGap(seq.charAt(npos)))
443 cdp[rf] = npos; // store position
444 codon[rf++] = seq.charAt(npos); // store base
449 * Filled up a reading frame...
451 AlignedCodon alignedCodon = new AlignedCodon(cdp[0], cdp[1],
453 String aa = ResidueProperties.codonTranslate(new String(codon));
455 final String gapString = String.valueOf(gapChar);
461 skipint = new int[] { alignedCodon.pos1,
467 skipint[1] = alignedCodon.pos3; // cdp[2];
474 skipint[0] = vismapping.shift(skipint[0]);
475 skipint[1] = vismapping.shift(skipint[1]);
476 for (vc = 0; vc < scontigs.length;)
478 if (scontigs[vc + 1] < skipint[0])
480 // before skipint starts
484 if (scontigs[vc] > skipint[1])
486 // finished editing so
489 // Edit the contig list to include the skipped region which did
492 // from : s1 e1 s2 e2 s3 e3
493 // to s: s1 e1 s2 k0 k1 e2 s3 e3
494 // list increases by one unless one boundary (s2==k0 or e2==k1)
495 // matches, and decreases by one if skipint intersects whole
497 if (scontigs[vc] <= skipint[0])
499 if (skipint[0] == scontigs[vc])
501 // skipint at start of contig
502 // shift the start of this contig
503 if (scontigs[vc + 1] > skipint[1])
505 scontigs[vc] = skipint[1];
510 if (scontigs[vc + 1] == skipint[1])
513 t = new int[scontigs.length - 2];
516 System.arraycopy(scontigs, 0, t, 0, vc - 1);
518 if (vc + 2 < t.length)
520 System.arraycopy(scontigs, vc + 2, t, vc,
527 // truncate contig to before the skipint region
528 scontigs[vc + 1] = skipint[0] - 1;
535 // scontig starts before start of skipint
536 if (scontigs[vc + 1] < skipint[1])
538 // skipint truncates end of scontig
539 scontigs[vc + 1] = skipint[0] - 1;
544 // divide region to new contigs
545 t = new int[scontigs.length + 2];
546 System.arraycopy(scontigs, 0, t, 0, vc + 1);
547 t[vc + 1] = skipint[0];
548 t[vc + 2] = skipint[1];
549 System.arraycopy(scontigs, vc + 1, t, vc + 3,
550 scontigs.length - (vc + 1));
560 if (aa.equals("STOP"))
566 boolean findpos = true;
570 * Compare this codon's base positions with those currently aligned to
571 * this column in the translation.
573 final int compareCodonPos = compareCodonPos(alignedCodon,
574 alignedCodons[aspos]);
575 switch (compareCodonPos)
580 * This codon should precede the mapped positions - need to insert a
581 * gap in all prior sequences.
583 insertAAGap(aspos, proteinSeqs);
590 * This codon belongs after the aligned codons at aspos. Prefix it
591 * with a gap and try the next position.
600 * Exact match - codon 'belongs' at this translated position.
607 if (alignedCodons[aspos] == null)
609 // mark this column as aligning to this aligned reading frame
610 alignedCodons[aspos] = alignedCodon;
612 else if (!alignedCodons[aspos].equals(alignedCodon))
614 throw new IllegalStateException(
615 "Tried to coalign " + alignedCodons[aspos].toString()
616 + " with " + alignedCodon.toString());
618 if (aspos >= aaWidth)
620 // update maximum alignment width
623 // ready for next translated reading frame alignment position (if any)
629 SequenceI newseq = new Sequence(selection.getName(),
633 final String errMsg = "trimming contigs for incomplete terminal codon.";
634 System.err.println(errMsg);
635 // map and trim contigs to ORF region
636 vc = scontigs.length - 1;
637 lastnpos = vismapping.shift(lastnpos); // place npos in context of
638 // whole dna alignment (rather
639 // than visible contigs)
640 // incomplete ORF could be broken over one or two visible contig
642 while (vc >= 0 && scontigs[vc] > lastnpos)
644 if (vc > 0 && scontigs[vc - 1] > lastnpos)
650 // correct last interval in list.
651 scontigs[vc] = lastnpos;
655 if (vc > 0 && (vc + 1) < scontigs.length)
657 // truncate map list to just vc elements
658 int t[] = new int[vc + 1];
659 System.arraycopy(scontigs, 0, t, 0, vc + 1);
667 if (scontigs != null)
670 // map scontigs to actual sequence positions on selection
671 for (vc = 0; vc < scontigs.length; vc += 2)
673 scontigs[vc] = selection.findPosition(scontigs[vc]); // not from 1!
674 scontigs[vc + 1] = selection.findPosition(scontigs[vc + 1]); // exclusive
675 if (scontigs[vc + 1] == selection.getEnd())
680 // trim trailing empty intervals.
681 if ((vc + 2) < scontigs.length)
683 int t[] = new int[vc + 2];
684 System.arraycopy(scontigs, 0, t, 0, vc + 2);
688 * delete intervals in scontigs which are not translated. 1. map skip
689 * into sequence position intervals 2. truncate existing ranges and add
690 * new ranges to exclude untranslated regions. if (skip.size()>0) {
691 * Vector narange = new Vector(); for (vc=0; vc<scontigs.length; vc++) {
692 * narange.addElement(new int[] {scontigs[vc]}); } int sint=0,iv[]; vc =
693 * 0; while (sint<skip.size()) { skipint = (int[]) skip.elementAt(sint);
694 * do { iv = (int[]) narange.elementAt(vc); if (iv[0]>=skipint[0] &&
695 * iv[0]<=skipint[1]) { if (iv[0]==skipint[0]) { // delete beginning of
696 * range } else { // truncate range and create new one if necessary iv =
697 * (int[]) narange.elementAt(vc+1); if (iv[0]<=skipint[1]) { // truncate
698 * range iv[0] = skipint[1]; } else { } } } else if (iv[0]<skipint[0]) {
699 * iv = (int[]) narange.elementAt(vc+1); } } while (iv[0]) } }
701 MapList map = new MapList(scontigs, new int[] { 1, resSize }, 3, 1);
703 transferCodedFeatures(selection, newseq, map);
706 * Construct a dataset sequence for our new peptide.
708 SequenceI rseq = newseq.deriveSequence();
711 * Store a mapping (between the dataset sequences for the two
714 // SIDE-EFFECT: acf stores the aligned sequence reseq; to remove!
715 acf.addMap(selection, rseq, map);
719 // register the mapping somehow
725 * Insert a gap into the aligned proteins and the codon mapping array.
731 protected void insertAAGap(int pos, List<SequenceI> proteinSeqs)
734 for (SequenceI seq : proteinSeqs)
736 seq.insertCharAt(pos, gapChar);
739 checkCodonFrameWidth();
745 * Shift from [pos] to the end one to the right, and null out [pos]
747 System.arraycopy(alignedCodons, pos, alignedCodons, pos + 1,
748 alignedCodons.length - pos - 1);
749 alignedCodons[pos] = null;
754 * Check the codons array can accommodate a single insertion, if not resize
757 protected void checkCodonFrameWidth()
759 if (alignedCodons[alignedCodons.length - 1] != null)
762 * arraycopy insertion would bump a filled slot off the end, so expand.
764 AlignedCodon[] c = new AlignedCodon[alignedCodons.length + 10];
765 System.arraycopy(alignedCodons, 0, c, 0, alignedCodons.length);
771 * Given a peptide newly translated from a dna sequence, copy over and set any
772 * features on the peptide from the DNA.
778 private static void transferCodedFeatures(SequenceI dna, SequenceI pep,
781 DBRefEntry[] dnarefs = DBRefUtils.selectRefs(dna.getDBRefs(),
782 DBRefSource.DNACODINGDBS);
785 // intersect with pep
786 for (int d = 0; d < dnarefs.length; d++)
788 Mapping mp = dnarefs[d].getMap();
794 for (SequenceFeature sf : dna.getFeatures().getAllFeatures())
796 if (FeatureProperties.isCodingFeature(null, sf.getType()))
798 // if (map.intersectsFrom(sf[f].begin, sf[f].end))
807 * Returns an alignment consisting of the reversed (and optionally
808 * complemented) sequences set in this object's constructor
813 public AlignmentI reverseCdna(boolean complement)
815 int sSize = selection.size();
816 List<SequenceI> reversed = new ArrayList<>();
817 for (int s = 0; s < sSize; s++)
819 SequenceI newseq = reverseSequence(selection.get(s).getName(),
820 seqstring[s], complement);
824 reversed.add(newseq);
828 SequenceI[] newseqs = reversed.toArray(new SequenceI[reversed.size()]);
829 AlignmentI al = new Alignment(newseqs);
830 ((Alignment) al).createDatasetAlignment();
835 * Returns a reversed, and optionally complemented, sequence. The new
836 * sequence's name is the original name with "|rev" or "|revcomp" appended.
837 * aAcCgGtT and DNA ambiguity codes are complemented, any other characters are
844 public static SequenceI reverseSequence(String seqName, String sequence,
847 String newName = seqName + "|rev" + (complement ? "comp" : "");
848 char[] originalSequence = sequence.toCharArray();
849 int length = originalSequence.length;
850 char[] reversedSequence = new char[length];
852 for (int i = 0; i < length; i++)
854 char c = complement ? getComplement(originalSequence[i])
855 : originalSequence[i];
856 reversedSequence[length - i - 1] = c;
857 if (!Comparison.isGap(c))
862 SequenceI reversed = new Sequence(newName, reversedSequence, 1, bases);
867 * Returns dna complement (preserving case) for aAcCgGtTuU. Ambiguity codes
868 * are treated as on http://reverse-complement.com/. Anything else is left
874 public static char getComplement(char c)