JAL-3438 spotless for 2.11.2.0
[jalview.git] / src / jalview / analysis / GeneticCodes.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.analysis;
22
23 import java.util.Locale;
24 import java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.util.HashMap;
29 import java.util.LinkedHashMap;
30 import java.util.Map;
31 import java.util.StringTokenizer;
32
33 import jalview.bin.Console;
34
35 /**
36  * A singleton that provides instances of genetic code translation tables
37  * 
38  * @author gmcarstairs
39  * @see https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
40  */
41 public final class GeneticCodes
42 {
43   private static final int CODON_LENGTH = 3;
44
45   private static final String QUOTE = "\"";
46
47   /*
48    * nucleotides as ordered in data file
49    */
50   private static final String NUCS = "TCAG";
51
52   private static final int NUCS_COUNT = NUCS.length();
53
54   private static final int NUCS_COUNT_SQUARED = NUCS_COUNT * NUCS_COUNT;
55
56   private static final int NUCS_COUNT_CUBED = NUCS_COUNT * NUCS_COUNT
57           * NUCS_COUNT;
58
59   private static final String AMBIGUITY_CODES_FILE = "/AmbiguityCodes.dat";
60
61   private static final String RESOURCE_FILE = "/GeneticCodes.dat";
62
63   private static GeneticCodes instance = new GeneticCodes();
64
65   private Map<String, String> ambiguityCodes;
66
67   /*
68    * loaded code tables, with keys in order of loading 
69    */
70   private Map<String, GeneticCodeI> codeTables;
71
72   /**
73    * Private constructor enforces singleton
74    */
75   private GeneticCodes()
76   {
77     if (instance == null)
78     {
79       ambiguityCodes = new HashMap<>();
80
81       /*
82        * LinkedHashMap preserves order of addition of entries,
83        * so we can assume the Standard Code Table is the first
84        */
85       codeTables = new LinkedHashMap<>();
86       loadAmbiguityCodes(AMBIGUITY_CODES_FILE);
87       loadCodes(RESOURCE_FILE);
88     }
89   }
90
91   /**
92    * Returns the singleton instance of this class
93    * 
94    * @return
95    */
96   public static GeneticCodes getInstance()
97   {
98     return instance;
99   }
100
101   /**
102    * Returns the known code tables, in order of loading.
103    * 
104    * @return
105    */
106   public Iterable<GeneticCodeI> getCodeTables()
107   {
108     return codeTables.values();
109   }
110
111   /**
112    * Answers the code table with the given id
113    * 
114    * @param id
115    * @return
116    */
117   public GeneticCodeI getCodeTable(String id)
118   {
119     return codeTables.get(id);
120   }
121
122   /**
123    * A convenience method that returns the standard code table (table 1). As
124    * implemented, this has to be the first table defined in the data file.
125    * 
126    * @return
127    */
128   public GeneticCodeI getStandardCodeTable()
129   {
130     return codeTables.values().iterator().next();
131   }
132
133   /**
134    * Loads the code tables from a data file
135    */
136   protected void loadCodes(String fileName)
137   {
138     try
139     {
140       InputStream is = getClass().getResourceAsStream(fileName);
141       if (is == null)
142       {
143         System.err.println("Resource file not found: " + fileName);
144         return;
145       }
146       BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
147
148       /*
149        * skip comments and start of table
150        */
151       String line = "";
152       while (line != null && !line.startsWith("Genetic-code-table"))
153       {
154         line = readLine(dataIn);
155       }
156       line = readLine(dataIn);
157
158       while (line.startsWith("{"))
159       {
160         line = loadOneTable(dataIn);
161       }
162     } catch (IOException | NullPointerException e)
163     {
164       Console.error("Error reading genetic codes data file " + fileName
165               + ": " + e.getMessage());
166     }
167     if (codeTables.isEmpty())
168     {
169       System.err.println(
170               "No genetic code tables loaded, check format of file "
171                       + fileName);
172     }
173   }
174
175   /**
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:
179    * <p>
180    * R&lt;tab&gt;AG
181    * <p>
182    * means that R is an ambiguity code meaning "A or G"
183    * 
184    * @param fileName
185    */
186   protected void loadAmbiguityCodes(String fileName)
187   {
188     try
189     {
190       InputStream is = getClass().getResourceAsStream(fileName);
191       if (is == null)
192       {
193         System.err.println("Resource file not found: " + fileName);
194         return;
195       }
196       BufferedReader dataIn = new BufferedReader(new InputStreamReader(is));
197       String line = "";
198       while (line != null)
199       {
200         line = readLine(dataIn);
201         if (line != null && !"DNA".equals(line.toUpperCase(Locale.ROOT)))
202         {
203           String[] tokens = line.split("\\t");
204           if (tokens.length == 2)
205           {
206             ambiguityCodes.put(tokens[0].toUpperCase(Locale.ROOT),
207                     tokens[1].toUpperCase(Locale.ROOT));
208           }
209           else
210           {
211             System.err.println(
212                     "Unexpected data in " + fileName + ": " + line);
213           }
214         }
215       }
216     } catch (IOException e)
217     {
218       Console.error("Error reading nucleotide ambiguity codes data file: "
219               + e.getMessage());
220     }
221   }
222
223   /**
224    * Reads up to and returns the next non-comment line, trimmed. Comment lines
225    * start with a #. Returns null at end of file.
226    * 
227    * @param dataIn
228    * @return
229    * @throws IOException
230    */
231   protected String readLine(BufferedReader dataIn) throws IOException
232   {
233     String line = dataIn.readLine();
234     while (line != null && line.startsWith("#"))
235     {
236       line = readLine(dataIn);
237     }
238     return line == null ? null : line.trim();
239   }
240
241   /**
242    * Reads the lines of the data file describing one translation table, and
243    * creates and stores an instance of GeneticCodeI. Returns the '{' line
244    * starting the next table, or the '}' line at end of all tables. Data format
245    * is
246    * 
247    * <pre>
248    * {
249    *   name "Vertebrate Mitochondrial" ,
250    *   name "SGC1" ,
251    *   id 2 ,
252    *   ncbieaa  "FFLLSSSSYY**CCWWLLLLPPPPHHQQRRRRIIMMTTTTNNKKSS**VVVVAAAADDEEGGGG",
253    *   sncbieaa "----------**--------------------MMMM----------**---M------------"
254    *   -- Base1  TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
255    *   -- Base2  TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
256    *   -- Base3  TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
257    * },
258    * </pre>
259    * 
260    * of which we parse the first name, the id, and the ncbieaa translations for
261    * codons as ordered by the Base1/2/3 lines. Note Base1/2/3 are included for
262    * readability and are in a fixed order, these are not parsed. The sncbieaa
263    * line marks alternative start codons, these are not parsed.
264    * 
265    * @param dataIn
266    * @return
267    * @throws IOException
268    */
269   protected String loadOneTable(BufferedReader dataIn) throws IOException
270   {
271     String name = null;
272     String id = null;
273     Map<String, String> codons = new HashMap<>();
274
275     String line = readLine(dataIn);
276
277     while (line != null && !line.startsWith("}"))
278     {
279       if (line.startsWith("name") && name == null)
280       {
281         name = line.substring(line.indexOf(QUOTE) + 1,
282                 line.lastIndexOf(QUOTE));
283       }
284       else if (line.startsWith("id"))
285       {
286         id = new StringTokenizer(line.substring(2)).nextToken();
287       }
288       else if (line.startsWith("ncbieaa"))
289       {
290         String aminos = line.substring(line.indexOf(QUOTE) + 1,
291                 line.lastIndexOf(QUOTE));
292         if (aminos.length() != NUCS_COUNT_CUBED) // 4 * 4 * 4 combinations
293         {
294           Console.error("wrong data length in code table: " + line);
295         }
296         else
297         {
298           for (int i = 0; i < aminos.length(); i++)
299           {
300             String peptide = String.valueOf(aminos.charAt(i));
301             char codon1 = NUCS.charAt(i / NUCS_COUNT_SQUARED);
302             char codon2 = NUCS
303                     .charAt((i % NUCS_COUNT_SQUARED) / NUCS_COUNT);
304             char codon3 = NUCS.charAt(i % NUCS_COUNT);
305             String codon = new String(
306                     new char[]
307                     { codon1, codon2, codon3 });
308             codons.put(codon, peptide);
309           }
310         }
311       }
312       line = readLine(dataIn);
313     }
314
315     registerCodeTable(id, name, codons);
316     return readLine(dataIn);
317   }
318
319   /**
320    * Constructs and registers a GeneticCodeI instance with the codon
321    * translations as defined in the data file. For all instances except the
322    * first, any undeclared translations default to those in the standard code
323    * table.
324    * 
325    * @param id
326    * @param name
327    * @param codons
328    */
329   protected void registerCodeTable(final String id, final String name,
330           final Map<String, String> codons)
331   {
332     codeTables.put(id, new GeneticCodeI()
333     {
334       /*
335        * map of ambiguous codons to their 'product'
336        * (null if not all possible translations match)
337        */
338       Map<String, String> ambiguous = new HashMap<>();
339
340       @Override
341       public String translateCanonical(String codon)
342       {
343         return codons.get(codon.toUpperCase(Locale.ROOT));
344       }
345
346       @Override
347       public String translate(String codon)
348       {
349         String upper = codon.toUpperCase(Locale.ROOT);
350         String peptide = translateCanonical(upper);
351
352         /*
353          * if still not translated, check for ambiguity codes
354          */
355         if (peptide == null)
356         {
357           peptide = getAmbiguousTranslation(upper, ambiguous, this);
358         }
359         return peptide;
360       }
361
362       @Override
363       public String getId()
364       {
365         return id;
366       }
367
368       @Override
369       public String getName()
370       {
371         return name;
372       }
373     });
374   }
375
376   /**
377    * Computes all possible translations of a codon including one or more
378    * ambiguity codes, and stores and returns the result (null if not all
379    * translations match). If the codon includes no ambiguity codes, simply
380    * returns null.
381    * 
382    * @param codon
383    * @param ambiguous
384    * @param codeTable
385    * @return
386    */
387   protected String getAmbiguousTranslation(String codon,
388           Map<String, String> ambiguous, GeneticCodeI codeTable)
389   {
390     if (codon.length() != CODON_LENGTH)
391     {
392       return null;
393     }
394
395     boolean isAmbiguous = false;
396
397     char[][] expanded = new char[CODON_LENGTH][];
398     for (int i = 0; i < CODON_LENGTH; i++)
399     {
400       String base = String.valueOf(codon.charAt(i));
401       if (ambiguityCodes.containsKey(base))
402       {
403         isAmbiguous = true;
404         base = ambiguityCodes.get(base);
405       }
406       expanded[i] = base.toCharArray();
407     }
408
409     if (!isAmbiguous)
410     {
411       // no ambiguity code involved here
412       return null;
413     }
414
415     /*
416      * generate and translate all permutations of the ambiguous codon
417      * only return the translation if they all agree, else null
418      */
419     String peptide = null;
420     for (char c1 : expanded[0])
421     {
422       for (char c2 : expanded[1])
423       {
424         for (char c3 : expanded[2])
425         {
426           char[] cdn = new char[] { c1, c2, c3 };
427           String possibleCodon = String.valueOf(cdn);
428           String pep = codeTable.translate(possibleCodon);
429           if (pep == null || (peptide != null && !pep.equals(peptide)))
430           {
431             ambiguous.put(codon, null);
432             return null;
433           }
434           peptide = pep;
435         }
436       }
437     }
438
439     /*
440      * all translations of ambiguous codons matched!
441      */
442     ambiguous.put(codon, peptide);
443     return peptide;
444   }
445 }