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.Locale;
25 import jalview.bin.Cache;
27 import java.io.BufferedReader;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.util.HashMap;
32 import java.util.LinkedHashMap;
34 import java.util.StringTokenizer;
37 * A singleton that provides instances of genetic code translation tables
40 * @see https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
42 public final class GeneticCodes
44 private static final int CODON_LENGTH = 3;
46 private static final String QUOTE = "\"";
49 * nucleotides as ordered in data file
51 private static final String NUCS = "TCAG";
53 private static final int NUCS_COUNT = NUCS.length();
55 private static final int NUCS_COUNT_SQUARED = NUCS_COUNT * NUCS_COUNT;
57 private static final int NUCS_COUNT_CUBED = NUCS_COUNT * NUCS_COUNT
60 private static final String AMBIGUITY_CODES_FILE = "/AmbiguityCodes.dat";
62 private static final String RESOURCE_FILE = "/GeneticCodes.dat";
64 private static GeneticCodes instance = new GeneticCodes();
66 private Map<String, String> ambiguityCodes;
69 * loaded code tables, with keys in order of loading
71 private Map<String, GeneticCodeI> codeTables;
74 * Private constructor enforces singleton
76 private GeneticCodes()
80 ambiguityCodes = new HashMap<>();
83 * LinkedHashMap preserves order of addition of entries,
84 * so we can assume the Standard Code Table is the first
86 codeTables = new LinkedHashMap<>();
87 loadAmbiguityCodes(AMBIGUITY_CODES_FILE);
88 loadCodes(RESOURCE_FILE);
93 * Returns the singleton instance of this class
97 public static GeneticCodes getInstance()
103 * Returns the known code tables, in order of loading.
107 public Iterable<GeneticCodeI> getCodeTables()
109 return codeTables.values();
113 * Answers the code table with the given id
118 public GeneticCodeI getCodeTable(String id)
120 return codeTables.get(id);
124 * A convenience method that returns the standard code table (table 1). As
125 * implemented, this has to be the first table defined in the data file.
129 public GeneticCodeI getStandardCodeTable()
131 return codeTables.values().iterator().next();
135 * Loads the code tables from a data file
137 protected void loadCodes(String fileName)
141 InputStream is = getClass().getResourceAsStream(fileName);
144 System.err.println("Resource file not found: " + fileName);
147 BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
150 * skip comments and start of table
153 while (line != null && !line.startsWith("Genetic-code-table"))
155 line = readLine(dataIn);
157 line = readLine(dataIn);
159 while (line.startsWith("{"))
161 line = loadOneTable(dataIn);
163 } catch (IOException | NullPointerException e)
166 "Error reading genetic codes data file " + fileName + ": "
169 if (codeTables.isEmpty())
172 "No genetic code tables loaded, check format of file "
178 * Reads and saves Nucleotide ambiguity codes from a data file. The file may
179 * include comment lines (starting with #), a header 'DNA', and one line per
180 * ambiguity code, for example:
184 * means that R is an ambiguity code meaning "A or G"
188 protected void loadAmbiguityCodes(String fileName)
192 InputStream is = getClass().getResourceAsStream(fileName);
195 System.err.println("Resource file not found: " + fileName);
198 BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
202 line = readLine(dataIn);
203 if (line != null && !"DNA".equals(line.toUpperCase(Locale.ROOT)))
205 String[] tokens = line.split("\\t");
206 if (tokens.length == 2)
208 ambiguityCodes.put(tokens[0].toUpperCase(Locale.ROOT),
209 tokens[1].toUpperCase(Locale.ROOT));
214 "Unexpected data in " + fileName + ": " + line);
218 } catch (IOException e)
221 "Error reading nucleotide ambiguity codes data file: "
227 * Reads up to and returns the next non-comment line, trimmed. Comment lines
228 * start with a #. Returns null at end of file.
232 * @throws IOException
234 protected String readLine(BufferedReader dataIn) throws IOException
236 String line = dataIn.readLine();
237 while (line != null && line.startsWith("#"))
239 line = readLine(dataIn);
241 return line == null ? null : line.trim();
245 * Reads the lines of the data file describing one translation table, and
246 * creates and stores an instance of GeneticCodeI. Returns the '{' line
247 * starting the next table, or the '}' line at end of all tables. Data format
252 * name "Vertebrate Mitochondrial" ,
255 * ncbieaa "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG",
256 * sncbieaa "----------**--------------------MMMM----------**---M------------"
257 * -- Base1 TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
258 * -- Base2 TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
259 * -- Base3 TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
263 * of which we parse the first name, the id, and the ncbieaa translations for
264 * codons as ordered by the Base1/2/3 lines. Note Base1/2/3 are included for
265 * readability and are in a fixed order, these are not parsed. The sncbieaa
266 * line marks alternative start codons, these are not parsed.
270 * @throws IOException
272 protected String loadOneTable(BufferedReader dataIn) throws IOException
276 Map<String, String> codons = new HashMap<>();
278 String line = readLine(dataIn);
280 while (line != null && !line.startsWith("}"))
282 if (line.startsWith("name") && name == null)
284 name = line.substring(line.indexOf(QUOTE) + 1,
285 line.lastIndexOf(QUOTE));
287 else if (line.startsWith("id"))
289 id = new StringTokenizer(line.substring(2)).nextToken();
291 else if (line.startsWith("ncbieaa"))
293 String aminos = line.substring(line.indexOf(QUOTE) + 1,
294 line.lastIndexOf(QUOTE));
295 if (aminos.length() != NUCS_COUNT_CUBED) // 4 * 4 * 4 combinations
297 Cache.log.error("wrong data length in code table: " + line);
301 for (int i = 0; i < aminos.length(); i++)
303 String peptide = String.valueOf(aminos.charAt(i));
304 char codon1 = NUCS.charAt(i / NUCS_COUNT_SQUARED);
306 .charAt((i % NUCS_COUNT_SQUARED) / NUCS_COUNT);
307 char codon3 = NUCS.charAt(i % NUCS_COUNT);
308 String codon = new String(
310 { codon1, codon2, codon3 });
311 codons.put(codon, peptide);
315 line = readLine(dataIn);
318 registerCodeTable(id, name, codons);
319 return readLine(dataIn);
323 * Constructs and registers a GeneticCodeI instance with the codon
324 * translations as defined in the data file. For all instances except the
325 * first, any undeclared translations default to those in the standard code
332 protected void registerCodeTable(final String id, final String name,
333 final Map<String, String> codons)
335 codeTables.put(id, new GeneticCodeI()
338 * map of ambiguous codons to their 'product'
339 * (null if not all possible translations match)
341 Map<String, String> ambiguous = new HashMap<>();
344 public String translateCanonical(String codon)
346 return codons.get(codon.toUpperCase(Locale.ROOT));
350 public String translate(String codon)
352 String upper = codon.toUpperCase(Locale.ROOT);
353 String peptide = translateCanonical(upper);
356 * if still not translated, check for ambiguity codes
360 peptide = getAmbiguousTranslation(upper, ambiguous, this);
366 public String getId()
372 public String getName()
380 * Computes all possible translations of a codon including one or more
381 * ambiguity codes, and stores and returns the result (null if not all
382 * translations match). If the codon includes no ambiguity codes, simply
390 protected String getAmbiguousTranslation(String codon,
391 Map<String, String> ambiguous, GeneticCodeI codeTable)
393 if (codon.length() != CODON_LENGTH)
398 boolean isAmbiguous = false;
400 char[][] expanded = new char[CODON_LENGTH][];
401 for (int i = 0; i < CODON_LENGTH; i++)
403 String base = String.valueOf(codon.charAt(i));
404 if (ambiguityCodes.containsKey(base))
407 base = ambiguityCodes.get(base);
409 expanded[i] = base.toCharArray();
414 // no ambiguity code involved here
419 * generate and translate all permutations of the ambiguous codon
420 * only return the translation if they all agree, else null
422 String peptide = null;
423 for (char c1 : expanded[0])
425 for (char c2 : expanded[1])
427 for (char c3 : expanded[2])
429 char[] cdn = new char[] { c1, c2, c3 };
430 String possibleCodon = String.valueOf(cdn);
431 String pep = codeTable.translate(possibleCodon);
432 if (pep == null || (peptide != null && !pep.equals(peptide)))
434 ambiguous.put(codon, null);
443 * all translations of ambiguous codons matched!
445 ambiguous.put(codon, peptide);