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.bin.Cache;
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
32 import java.util.StringTokenizer;
35 * A singleton that provides instances of genetic code translation tables
38 * @see https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
40 public final class GeneticCodes
42 private static final int CODON_LENGTH = 3;
44 private static final String QUOTE = "\"";
47 * nucleotides as ordered in data file
49 private static final String NUCS = "TCAG";
51 private static final int NUCS_COUNT = NUCS.length();
53 private static final int NUCS_COUNT_SQUARED = NUCS_COUNT * NUCS_COUNT;
55 private static final int NUCS_COUNT_CUBED = NUCS_COUNT * NUCS_COUNT
58 private static final String AMBIGUITY_CODES_FILE = "/AmbiguityCodes.dat";
60 private static final String RESOURCE_FILE = "/GeneticCodes.dat";
62 private static GeneticCodes instance = new GeneticCodes();
64 private Map<String, String> ambiguityCodes;
67 * loaded code tables, with keys in order of loading
69 private Map<String, GeneticCodeI> codeTables;
72 * Private constructor enforces singleton
74 private GeneticCodes()
78 ambiguityCodes = new HashMap<>();
81 * LinkedHashMap preserves order of addition of entries,
82 * so we can assume the Standard Code Table is the first
84 codeTables = new LinkedHashMap<>();
85 loadAmbiguityCodes(AMBIGUITY_CODES_FILE);
86 loadCodes(RESOURCE_FILE);
91 * Returns the singleton instance of this class
95 public static GeneticCodes getInstance()
101 * Returns the known code tables, in order of loading.
105 public Iterable<GeneticCodeI> getCodeTables()
107 return codeTables.values();
111 * Answers the code table with the given id
116 public GeneticCodeI getCodeTable(String id)
118 return codeTables.get(id);
122 * A convenience method that returns the standard code table (table 1). As
123 * implemented, this has to be the first table defined in the data file.
127 public GeneticCodeI getStandardCodeTable()
129 return codeTables.values().iterator().next();
133 * Loads the code tables from a data file
135 protected void loadCodes(String fileName)
139 InputStream is = getClass().getResourceAsStream(fileName);
142 System.err.println("Resource file not found: " + fileName);
145 BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
148 * skip comments and start of table
151 while (line != null && !line.startsWith("Genetic-code-table"))
153 line = readLine(dataIn);
155 line = readLine(dataIn);
157 while (line.startsWith("{"))
159 line = loadOneTable(dataIn);
161 } catch (IOException | NullPointerException e)
164 "Error reading genetic codes data file " + fileName + ": "
167 if (codeTables.isEmpty())
170 "No genetic code tables loaded, check format of file "
176 * Reads and saves Nucleotide ambiguity codes from a data file. The file may
177 * include comment lines (starting with #), a header 'DNA', and one line per
178 * ambiguity code, for example:
182 * means that R is an ambiguity code meaning "A or G"
186 protected void loadAmbiguityCodes(String fileName)
190 InputStream is = getClass().getResourceAsStream(fileName);
193 System.err.println("Resource file not found: " + fileName);
196 BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
200 line = readLine(dataIn);
201 if (line != null && !"DNA".equals(line.toUpperCase()))
203 String[] tokens = line.split("\\t");
204 if (tokens.length == 2)
206 ambiguityCodes.put(tokens[0].toUpperCase(),
207 tokens[1].toUpperCase());
212 "Unexpected data in " + fileName + ": " + line);
216 } catch (IOException e)
219 "Error reading nucleotide ambiguity codes data file: "
225 * Reads up to and returns the next non-comment line, trimmed. Comment lines
226 * start with a #. Returns null at end of file.
230 * @throws IOException
232 protected String readLine(BufferedReader dataIn) throws IOException
234 String line = dataIn.readLine();
235 while (line != null && line.startsWith("#"))
237 line = readLine(dataIn);
239 return line == null ? null : line.trim();
243 * Reads the lines of the data file describing one translation table, and
244 * creates and stores an instance of GeneticCodeI. Returns the '{' line
245 * starting the next table, or the '}' line at end of all tables. Data format
250 * name "Vertebrate Mitochondrial" ,
253 * ncbieaa "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG",
254 * sncbieaa "----------**--------------------MMMM----------**---M------------"
255 * -- Base1 TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
256 * -- Base2 TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
257 * -- Base3 TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
261 * of which we parse the first name, the id, and the ncbieaa translations for
262 * codons as ordered by the Base1/2/3 lines. Note Base1/2/3 are included for
263 * readability and are in a fixed order, these are not parsed. The sncbieaa
264 * line marks alternative start codons, these are not parsed.
268 * @throws IOException
270 protected String loadOneTable(BufferedReader dataIn) throws IOException
274 Map<String, String> codons = new HashMap<>();
276 String line = readLine(dataIn);
278 while (line != null && !line.startsWith("}"))
280 if (line.startsWith("name") && name == null)
282 name = line.substring(line.indexOf(QUOTE) + 1,
283 line.lastIndexOf(QUOTE));
285 else if (line.startsWith("id"))
287 id = new StringTokenizer(line.substring(2)).nextToken();
289 else if (line.startsWith("ncbieaa"))
291 String aminos = line.substring(line.indexOf(QUOTE) + 1,
292 line.lastIndexOf(QUOTE));
293 if (aminos.length() != NUCS_COUNT_CUBED) // 4 * 4 * 4 combinations
295 Cache.log.error("wrong data length in code table: " + line);
299 for (int i = 0; i < aminos.length(); i++)
301 String peptide = String.valueOf(aminos.charAt(i));
302 char codon1 = NUCS.charAt(i / NUCS_COUNT_SQUARED);
304 .charAt((i % NUCS_COUNT_SQUARED) / NUCS_COUNT);
305 char codon3 = NUCS.charAt(i % NUCS_COUNT);
306 String codon = new String(
308 { codon1, codon2, codon3 });
309 codons.put(codon, peptide);
313 line = readLine(dataIn);
316 registerCodeTable(id, name, codons);
317 return readLine(dataIn);
321 * Constructs and registers a GeneticCodeI instance with the codon
322 * translations as defined in the data file. For all instances except the
323 * first, any undeclared translations default to those in the standard code
330 protected void registerCodeTable(final String id, final String name,
331 final Map<String, String> codons)
333 codeTables.put(id, new GeneticCodeI()
336 * map of ambiguous codons to their 'product'
337 * (null if not all possible translations match)
339 Map<String, String> ambiguous = new HashMap<>();
342 public String translateCanonical(String codon)
344 return codons.get(codon.toUpperCase());
348 public String translate(String codon)
350 String upper = codon.toUpperCase();
351 String peptide = translateCanonical(upper);
354 * if still not translated, check for ambiguity codes
358 peptide = getAmbiguousTranslation(upper, ambiguous, this);
364 public String getId()
370 public String getName()
378 * Computes all possible translations of a codon including one or more
379 * ambiguity codes, and stores and returns the result (null if not all
380 * translations match). If the codon includes no ambiguity codes, simply
388 protected String getAmbiguousTranslation(String codon,
389 Map<String, String> ambiguous, GeneticCodeI codeTable)
391 if (codon.length() != CODON_LENGTH)
396 boolean isAmbiguous = false;
398 char[][] expanded = new char[CODON_LENGTH][];
399 for (int i = 0; i < CODON_LENGTH; i++)
401 String base = String.valueOf(codon.charAt(i));
402 if (ambiguityCodes.containsKey(base))
405 base = ambiguityCodes.get(base);
407 expanded[i] = base.toCharArray();
412 // no ambiguity code involved here
417 * generate and translate all permutations of the ambiguous codon
418 * only return the translation if they all agree, else null
420 String peptide = null;
421 for (char c1 : expanded[0])
423 for (char c2 : expanded[1])
425 for (char c3 : expanded[2])
427 char[] cdn = new char[] { c1, c2, c3 };
428 String possibleCodon = String.valueOf(cdn);
429 String pep = codeTable.translate(possibleCodon);
430 if (pep == null || (peptide != null && !pep.equals(peptide)))
432 ambiguous.put(codon, null);
441 * all translations of ambiguous codons matched!
443 ambiguous.put(codon, peptide);