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.Comparator;
26 import java.util.List;
29 import jalview.api.AlignViewportI;
30 import jalview.datamodel.AlignedCodon;
31 import jalview.datamodel.AlignedCodonFrame;
32 import jalview.datamodel.Alignment;
33 import jalview.datamodel.AlignmentAnnotation;
34 import jalview.datamodel.AlignmentI;
35 import jalview.datamodel.Annotation;
36 import jalview.datamodel.DBRefEntry;
37 import jalview.datamodel.DBRefSource;
38 import jalview.datamodel.FeatureProperties;
39 import jalview.datamodel.GraphLine;
40 import jalview.datamodel.Mapping;
41 import jalview.datamodel.Sequence;
42 import jalview.datamodel.SequenceFeature;
43 import jalview.datamodel.SequenceI;
44 import jalview.schemes.ResidueProperties;
45 import jalview.util.Comparison;
46 import jalview.util.DBRefUtils;
47 import jalview.util.MapList;
48 import jalview.util.ShiftList;
52 private static final String STOP_X = "X";
54 private static final Comparator<AlignedCodon> comparator = new CodonComparator();
57 * 'final' variables describe the inputs to the translation, which should not
60 final private List<SequenceI> selection;
62 final private String[] seqstring;
64 final private int[] contigs;
66 final private char gapChar;
68 final private AlignmentAnnotation[] annotations;
70 final private int dnaWidth;
72 final private Alignment 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, 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, AlignedCodon ac2)
139 if (ac1 == null || ac2 == null || (ac1.equals(ac2)))
143 if (ac1.pos1 < ac2.pos1 || ac1.pos2 < ac2.pos2 || ac1.pos3 < ac2.pos3)
145 // one base in cdp1 precedes the corresponding base in the other codon
148 // one base in cdp1 appears after the corresponding base in the other codon.
156 public AlignmentI translateCdna()
158 AlignedCodonFrame acf = new AlignedCodonFrame();
160 alignedCodons = new AlignedCodon[dnaWidth];
163 int sSize = selection.size();
164 List<SequenceI> pepseqs = new ArrayList<SequenceI>();
165 for (s = 0; s < sSize; s++)
167 SequenceI newseq = translateCodingRegion(selection.get(s),
168 seqstring[s], acf, pepseqs);
173 SequenceI ds = newseq;
176 while (ds.getDatasetSequence() != null)
178 ds = ds.getDatasetSequence();
180 dataset.addSequence(ds);
185 SequenceI[] newseqs = pepseqs.toArray(new SequenceI[pepseqs.size()]);
186 AlignmentI al = new Alignment(newseqs);
187 // ensure we look aligned.
189 // link the protein translation to the DNA dataset
190 al.setDataset(dataset);
191 translateAlignedAnnotations(al, acf);
192 al.addCodonFrame(acf);
197 * fake the collection of DbRefs with associated exon mappings to identify if
198 * a translation would generate distinct product in the currently selected
205 public static boolean canTranslate(SequenceI[] selection,
208 for (int gd = 0; gd < selection.length; gd++)
210 SequenceI dna = selection[gd];
211 DBRefEntry[] dnarefs = DBRefUtils
212 .selectRefs(dna.getDBRef(),
213 jalview.datamodel.DBRefSource.DNACODINGDBS);
216 // intersect with pep
217 List<DBRefEntry> mappedrefs = new ArrayList<DBRefEntry>();
218 DBRefEntry[] refs = dna.getDBRef();
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
306 if (annotation.hasScore)
308 aa.setScore(annotation.getScore());
311 final SequenceI seqRef = annotation.sequenceRef;
314 SequenceI aaSeq = acf.getAaForDnaSeq(seqRef);
317 // aa.compactAnnotationArray(); // throw away alignment annotation
319 aa.setSequenceRef(aaSeq);
321 aa.createSequenceMapping(aaSeq, aaSeq.getStart(), true);
322 aa.adjustForAlignment();
323 aaSeq.addAlignmentAnnotation(aa);
326 al.addAnnotation(aa);
331 private static Annotation getCodonAnnotation(AlignedCodon is,
332 Annotation[] annotations)
334 // Have a look at all the codon positions for annotation and put the first
335 // one found into the translated annotation pos.
337 Annotation annot = null;
338 for (int p = 1; p <= 3; p++)
340 int dnaCol = is.getBaseColumn(p);
341 if (annotations[dnaCol] != null)
345 annot = new Annotation(annotations[dnaCol]);
351 Annotation cpy = new Annotation(annotations[dnaCol]);
352 if (annot.colour == null)
354 annot.colour = cpy.colour;
356 if (annot.description == null || annot.description.length() == 0)
358 annot.description = cpy.description;
360 if (annot.displayCharacter == null)
362 annot.displayCharacter = cpy.displayCharacter;
364 if (annot.secondaryStructure == 0)
366 annot.secondaryStructure = cpy.secondaryStructure;
368 annot.value += cpy.value;
375 annot.value /= contrib;
381 * Translate a na sequence
384 * sequence displayed under viscontigs visible columns
386 * ORF read in some global alignment reference frame
388 * Definition of global ORF alignment reference frame
390 * @return sequence ready to be added to alignment.
392 protected SequenceI translateCodingRegion(SequenceI selection,
393 String seqstring, AlignedCodonFrame acf,
394 List<SequenceI> proteinSeqs)
396 List<int[]> skip = new ArrayList<int[]>();
397 int skipint[] = null;
398 ShiftList vismapping = new ShiftList(); // map from viscontigs to seqstring
401 int[] scontigs = new int[contigs.length];
403 for (vc = 0; vc < contigs.length; vc += 2)
407 vismapping.addShift(npos, contigs[vc]);
412 vismapping.addShift(npos, contigs[vc] - contigs[vc - 1] + 1);
414 scontigs[vc] = contigs[vc];
415 scontigs[vc + 1] = contigs[vc + 1];
418 // allocate a roughly sized buffer for the protein sequence
419 StringBuilder protein = new StringBuilder(seqstring.length() / 2);
420 String seq = seqstring.replace('U', 'T').replace('u', 'T');
421 char codon[] = new char[3];
422 int cdp[] = new int[3];
428 for (npos = 0, nend = seq.length(); npos < nend; npos++)
430 if (!Comparison.isGap(seq.charAt(npos)))
432 cdp[rf] = npos; // store position
433 codon[rf++] = seq.charAt(npos); // store base
438 * Filled up a reading frame...
440 AlignedCodon alignedCodon = new AlignedCodon(cdp[0], cdp[1], cdp[2]);
441 String aa = ResidueProperties.codonTranslate(new String(codon));
443 final String gapString = String.valueOf(gapChar);
450 { alignedCodon.pos1, alignedCodon.pos3 /* cdp[0], cdp[2] */};
452 skipint[1] = alignedCodon.pos3; // cdp[2];
459 skipint[0] = vismapping.shift(skipint[0]);
460 skipint[1] = vismapping.shift(skipint[1]);
461 for (vc = 0; vc < scontigs.length;)
463 if (scontigs[vc + 1] < skipint[0])
465 // before skipint starts
469 if (scontigs[vc] > skipint[1])
471 // finished editing so
474 // Edit the contig list to include the skipped region which did
477 // from : s1 e1 s2 e2 s3 e3
478 // to s: s1 e1 s2 k0 k1 e2 s3 e3
479 // list increases by one unless one boundary (s2==k0 or e2==k1)
480 // matches, and decreases by one if skipint intersects whole
482 if (scontigs[vc] <= skipint[0])
484 if (skipint[0] == scontigs[vc])
486 // skipint at start of contig
487 // shift the start of this contig
488 if (scontigs[vc + 1] > skipint[1])
490 scontigs[vc] = skipint[1];
495 if (scontigs[vc + 1] == skipint[1])
498 t = new int[scontigs.length - 2];
501 System.arraycopy(scontigs, 0, t, 0, vc - 1);
503 if (vc + 2 < t.length)
505 System.arraycopy(scontigs, vc + 2, t, vc, t.length
512 // truncate contig to before the skipint region
513 scontigs[vc + 1] = skipint[0] - 1;
520 // scontig starts before start of skipint
521 if (scontigs[vc + 1] < skipint[1])
523 // skipint truncates end of scontig
524 scontigs[vc + 1] = skipint[0] - 1;
529 // divide region to new contigs
530 t = new int[scontigs.length + 2];
531 System.arraycopy(scontigs, 0, t, 0, vc + 1);
532 t[vc + 1] = skipint[0];
533 t[vc + 2] = skipint[1];
534 System.arraycopy(scontigs, vc + 1, t, vc + 3,
535 scontigs.length - (vc + 1));
545 if (aa.equals("STOP"))
551 boolean findpos = true;
555 * Compare this codon's base positions with those currently aligned to
556 * this column in the translation.
558 final int compareCodonPos = compareCodonPos(alignedCodon,
559 alignedCodons[aspos]);
560 switch (compareCodonPos)
565 * This codon should precede the mapped positions - need to insert a
566 * gap in all prior sequences.
568 insertAAGap(aspos, proteinSeqs);
575 * This codon belongs after the aligned codons at aspos. Prefix it
576 * with a gap and try the next position.
585 * Exact match - codon 'belongs' at this translated position.
592 if (alignedCodons[aspos] == null)
594 // mark this column as aligning to this aligned reading frame
595 alignedCodons[aspos] = alignedCodon;
597 else if (!alignedCodons[aspos].equals(alignedCodon))
599 throw new IllegalStateException("Tried to coalign "
600 + alignedCodons[aspos].toString() + " with "
601 + alignedCodon.toString());
603 if (aspos >= aaWidth)
605 // update maximum alignment width
608 // ready for next translated reading frame alignment position (if any)
614 SequenceI newseq = new Sequence(selection.getName(),
618 final String errMsg = "trimming contigs for incomplete terminal codon.";
619 System.err.println(errMsg);
620 // map and trim contigs to ORF region
621 vc = scontigs.length - 1;
622 lastnpos = vismapping.shift(lastnpos); // place npos in context of
623 // whole dna alignment (rather
624 // than visible contigs)
625 // incomplete ORF could be broken over one or two visible contig
627 while (vc >= 0 && scontigs[vc] > lastnpos)
629 if (vc > 0 && scontigs[vc - 1] > lastnpos)
635 // correct last interval in list.
636 scontigs[vc] = lastnpos;
640 if (vc > 0 && (vc + 1) < scontigs.length)
642 // truncate map list to just vc elements
643 int t[] = new int[vc + 1];
644 System.arraycopy(scontigs, 0, t, 0, vc + 1);
652 if (scontigs != null)
655 // map scontigs to actual sequence positions on selection
656 for (vc = 0; vc < scontigs.length; vc += 2)
658 scontigs[vc] = selection.findPosition(scontigs[vc]); // not from 1!
659 scontigs[vc + 1] = selection.findPosition(scontigs[vc + 1]); // exclusive
660 if (scontigs[vc + 1] == selection.getEnd())
665 // trim trailing empty intervals.
666 if ((vc + 2) < scontigs.length)
668 int t[] = new int[vc + 2];
669 System.arraycopy(scontigs, 0, t, 0, vc + 2);
673 * delete intervals in scontigs which are not translated. 1. map skip
674 * into sequence position intervals 2. truncate existing ranges and add
675 * new ranges to exclude untranslated regions. if (skip.size()>0) {
676 * Vector narange = new Vector(); for (vc=0; vc<scontigs.length; vc++) {
677 * narange.addElement(new int[] {scontigs[vc]}); } int sint=0,iv[]; vc =
678 * 0; while (sint<skip.size()) { skipint = (int[]) skip.elementAt(sint);
679 * do { iv = (int[]) narange.elementAt(vc); if (iv[0]>=skipint[0] &&
680 * iv[0]<=skipint[1]) { if (iv[0]==skipint[0]) { // delete beginning of
681 * range } else { // truncate range and create new one if necessary iv =
682 * (int[]) narange.elementAt(vc+1); if (iv[0]<=skipint[1]) { // truncate
683 * range iv[0] = skipint[1]; } else { } } } else if (iv[0]<skipint[0]) {
684 * iv = (int[]) narange.elementAt(vc+1); } } while (iv[0]) } }
686 MapList map = new MapList(scontigs, new int[]
687 { 1, resSize }, 3, 1);
689 transferCodedFeatures(selection, newseq, map, null, null);
692 * Construct a dataset sequence for our new peptide.
694 SequenceI rseq = newseq.deriveSequence();
697 * Store a mapping (between the dataset sequences for the two
700 // SIDE-EFFECT: acf stores the aligned sequence reseq; to remove!
701 acf.addMap(selection, rseq, map);
705 // register the mapping somehow
711 * Insert a gap into the aligned proteins and the codon mapping array.
717 protected void insertAAGap(int pos,
718 List<SequenceI> proteinSeqs)
721 for (SequenceI seq : proteinSeqs)
723 seq.insertCharAt(pos, gapChar);
726 checkCodonFrameWidth();
732 * Shift from [pos] to the end one to the right, and null out [pos]
734 System.arraycopy(alignedCodons, pos, alignedCodons, pos + 1,
735 alignedCodons.length - pos - 1);
736 alignedCodons[pos] = null;
741 * Check the codons array can accommodate a single insertion, if not resize
744 protected void checkCodonFrameWidth()
746 if (alignedCodons[alignedCodons.length - 1] != null)
749 * arraycopy insertion would bump a filled slot off the end, so expand.
751 AlignedCodon[] c = new AlignedCodon[alignedCodons.length + 10];
752 System.arraycopy(alignedCodons, 0, c, 0, alignedCodons.length);
758 * Given a peptide newly translated from a dna sequence, copy over and set any
759 * features on the peptide from the DNA. If featureTypes is null, all features
760 * on the dna sequence are searched (rather than just the displayed ones), and
761 * similarly for featureGroups.
766 * @param featureTypes
767 * hash whose keys are the displayed feature type strings
768 * @param featureGroups
769 * hash where keys are feature groups and values are Boolean objects
770 * indicating if they are displayed.
772 private static void transferCodedFeatures(SequenceI dna, SequenceI pep,
773 MapList map, Map<String, Object> featureTypes,
774 Map<String, Boolean> featureGroups)
776 SequenceFeature[] sfs = dna.getSequenceFeatures();
778 DBRefEntry[] dnarefs = DBRefUtils.selectRefs(dna.getDBRef(),
779 DBRefSource.DNACODINGDBS);
782 // intersect with pep
783 for (int d = 0; d < dnarefs.length; d++)
785 Mapping mp = dnarefs[d].getMap();
793 for (SequenceFeature sf : sfs)
795 fgstate = (featureGroups == null) ? null : featureGroups
796 .get(sf.featureGroup);
797 if ((featureTypes == null || featureTypes.containsKey(sf.getType()))
798 && (fgstate == null || fgstate.booleanValue()))
800 if (FeatureProperties.isCodingFeature(null, sf.getType()))
802 // if (map.intersectsFrom(sf[f].begin, sf[f].end))