1 package jalview.analysis;
3 import jalview.bin.Cache;
5 import java.io.BufferedReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.util.HashMap;
10 import java.util.LinkedHashMap;
12 import java.util.StringTokenizer;
15 * A singleton that provides instances of genetic code translation tables
18 * @see https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
20 public final class GeneticCodes
22 private static final int CODON_LENGTH = 3;
24 private static final String QUOTE = "\"";
27 * nucleotides as ordered in data file
29 private static final String NUCS = "TCAG";
31 private static final int NUCS_COUNT = NUCS.length();
33 private static final int NUCS_COUNT_SQUARED = NUCS_COUNT * NUCS_COUNT;
35 private static final int NUCS_COUNT_CUBED = NUCS_COUNT * NUCS_COUNT
38 private static final String AMBIGUITY_CODES_FILE = "/AmbiguityCodes.dat";
40 private static final String RESOURCE_FILE = "/GeneticCodes.dat";
42 private static GeneticCodes instance = new GeneticCodes();
44 private Map<String, String> ambiguityCodes;
47 * loaded code tables, with keys in order of loading
49 private Map<String, GeneticCodeI> codeTables;
52 * Private constructor enforces singleton
54 private GeneticCodes()
58 ambiguityCodes = new HashMap<>();
61 * LinkedHashMap preserves order of addition of entries,
62 * so we can assume the Standard Code Table is the first
64 codeTables = new LinkedHashMap<>();
65 loadAmbiguityCodes(AMBIGUITY_CODES_FILE);
66 loadCodes(RESOURCE_FILE);
71 * Returns the singleton instance of this class
75 public static GeneticCodes getInstance()
81 * Returns the known code tables, in order of loading.
85 public Iterable<GeneticCodeI> getCodeTables()
87 return codeTables.values();
91 * Answers the code table with the given id
96 public GeneticCodeI getCodeTable(String id)
98 return codeTables.get(id);
102 * A convenience method that returns the standard code table (table 1). As
103 * implemented, this has to be the first table defined in the data file.
107 public GeneticCodeI getStandardCodeTable()
109 return codeTables.values().iterator().next();
113 * Loads the code tables from a data file
115 protected void loadCodes(String fileName)
119 InputStream is = getClass().getResourceAsStream(fileName);
120 BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
123 * skip comments and start of table
126 while (line != null && !line.startsWith("Genetic-code-table"))
128 line = readLine(dataIn);
130 line = readLine(dataIn);
132 while (line.startsWith("{"))
134 line = loadOneTable(dataIn);
136 } catch (IOException | NullPointerException e)
139 "Error reading genetic codes data file: "
145 * Reads and saves Nucleotide ambiguity codes from a data file. The file may
146 * include comment lines (starting with #), a header 'DNA', and one line per
147 * ambiguity code, for example:
151 * means that R is an ambiguity code meaning "A or G"
155 protected void loadAmbiguityCodes(String fileName)
159 InputStream is = getClass().getResourceAsStream(fileName);
160 BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
164 line = readLine(dataIn);
165 if (line != null && !"DNA".equals(line.toUpperCase()))
167 String[] tokens = line.split("\\t");
168 ambiguityCodes.put(tokens[0].toUpperCase(),
169 tokens[1].toUpperCase());
172 } catch (IOException e)
175 "Error reading nucleotide ambiguity codes data file: "
181 * Reads up to and returns the next non-comment line, trimmed. Comment lines
182 * start with a #. Returns null at end of file.
186 * @throws IOException
188 protected String readLine(BufferedReader dataIn) throws IOException
190 String line = dataIn.readLine();
191 while (line != null && line.startsWith("#"))
193 line = readLine(dataIn);
195 return line == null ? null : line.trim();
199 * Reads the lines of the data file describing one translation table, and
200 * creates and stores an instance of GeneticCodeI. Returns the '{' line
201 * starting the next table, or the '}' line at end of all tables. Data format
206 * name "Vertebrate Mitochondrial" ,
209 * ncbieaa "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG",
210 * sncbieaa "----------**--------------------MMMM----------**---M------------"
211 * -- Base1 TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
212 * -- Base2 TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
213 * -- Base3 TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
217 * of which we parse the first name, the id, and the ncbieaa translations for
218 * codons as ordered by the Base1/2/3 lines. Note Base1/2/3 are included for
219 * readability and are in a fixed order, these are not parsed. The sncbieaa
220 * line marks alternative start codons, these are not parsed.
224 * @throws IOException
226 protected String loadOneTable(BufferedReader dataIn) throws IOException
230 Map<String, String> codons = new HashMap<>();
232 String line = readLine(dataIn);
234 while (line != null && !line.startsWith("}"))
236 if (line.startsWith("name") && name == null)
238 name = line.substring(line.indexOf(QUOTE) + 1,
239 line.lastIndexOf(QUOTE));
241 else if (line.startsWith("id"))
243 id = new StringTokenizer(line.substring(2)).nextToken();
245 else if (line.startsWith("ncbieaa"))
247 String aminos = line.substring(line.indexOf(QUOTE) + 1,
248 line.lastIndexOf(QUOTE));
249 if (aminos.length() != NUCS_COUNT_CUBED) // 4 * 4 * 4 combinations
251 Cache.log.error("wrong data length in code table: " + line);
255 for (int i = 0; i < aminos.length(); i++)
257 String peptide = String.valueOf(aminos.charAt(i));
258 char codon1 = NUCS.charAt(i / NUCS_COUNT_SQUARED);
260 .charAt((i % NUCS_COUNT_SQUARED) / NUCS_COUNT);
261 char codon3 = NUCS.charAt(i % NUCS_COUNT);
262 String codon = new String(
264 { codon1, codon2, codon3 });
265 codons.put(codon, peptide);
269 line = readLine(dataIn);
272 registerCodeTable(id, name, codons);
273 return readLine(dataIn);
277 * Constructs and registers a GeneticCodeI instance with the codon
278 * translations as defined in the data file. For all instances except the
279 * first, any undeclared translations default to those in the standard code
286 protected void registerCodeTable(final String id, final String name,
287 final Map<String, String> codons)
289 codeTables.put(id, new GeneticCodeI()
292 * map of ambiguous codons to their 'product'
293 * (null if not all possible translations match)
295 Map<String, String> ambiguous = new HashMap<>();
298 public String translateCanonical(String codon)
300 return codons.get(codon.toUpperCase());
304 public String translate(String codon)
306 String upper = codon.toUpperCase();
307 String peptide = translateCanonical(upper);
310 * if still not translated, check for ambiguity codes
314 peptide = getAmbiguousTranslation(upper, ambiguous, this);
320 public String getId()
326 public String getName()
334 * Computes all possible translations of a codon including one or more
335 * ambiguity codes, and stores and returns the result (null if not all
336 * translations match). If the codon includes no ambiguity codes, simply
344 protected String getAmbiguousTranslation(String codon,
345 Map<String, String> ambiguous, GeneticCodeI codeTable)
347 if (codon.length() != CODON_LENGTH)
352 boolean isAmbiguous = false;
354 char[][] expanded = new char[CODON_LENGTH][];
355 for (int i = 0; i < CODON_LENGTH; i++)
357 String base = String.valueOf(codon.charAt(i));
358 if (ambiguityCodes.containsKey(base))
361 base = ambiguityCodes.get(base);
363 expanded[i] = base.toCharArray();
368 // no ambiguity code involved here
373 * generate and translate all permutations of the ambiguous codon
374 * only return the translation if they all agree, else null
376 String peptide = null;
377 for (char c1 : expanded[0])
379 for (char c2 : expanded[1])
381 for (char c3 : expanded[2])
383 char[] cdn = new char[] { c1, c2, c3 };
384 String possibleCodon = String.valueOf(cdn);
385 String pep = codeTable.translate(possibleCodon);
386 if (pep == null || (peptide != null && !pep.equals(peptide)))
388 ambiguous.put(codon, null);
397 * all translations of ambiguous codons matched!
399 ambiguous.put(codon, peptide);