JAL-2679 reinstating changes lost in VCF merge
[jalview.git] / src / jalview / ext / ensembl / EnsemblLookup.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.ext.ensembl;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.GeneLociI;
26 import jalview.util.MapList;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.net.MalformedURLException;
31 import java.net.URL;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.List;
35
36 import org.json.simple.JSONObject;
37 import org.json.simple.parser.JSONParser;
38 import org.json.simple.parser.ParseException;
39
40 /**
41  * A client for the Ensembl /lookup REST endpoint, used to find the gene
42  * identifier given a gene, transcript or protein identifier, or to extract the
43  * species or chromosomal coordinates from the same service response
44  * 
45  * @author gmcarstairs
46  */
47 public class EnsemblLookup extends EnsemblRestClient
48 {
49   private static final String SPECIES = "species";
50
51   /**
52    * keep track of last identifier retrieved to break loops
53    */
54   private String lastId;
55
56   /**
57    * Default constructor (to use rest.ensembl.org)
58    */
59   public EnsemblLookup()
60   {
61     super();
62   }
63
64   /**
65    * Constructor given the target domain to fetch data from
66    * 
67    * @param
68    */
69   public EnsemblLookup(String d)
70   {
71     super(d);
72   }
73
74   @Override
75   public String getDbName()
76   {
77     return "ENSEMBL";
78   }
79
80   @Override
81   public AlignmentI getSequenceRecords(String queries) throws Exception
82   {
83     return null;
84   }
85
86   @Override
87   protected URL getUrl(List<String> ids) throws MalformedURLException
88   {
89     String identifier = ids.get(0);
90     return getUrl(identifier, null);
91   }
92
93   /**
94    * Gets the url for lookup of the given identifier, optionally with objectType
95    * also specified in the request
96    * 
97    * @param identifier
98    * @param objectType
99    * @return
100    */
101   protected URL getUrl(String identifier, String objectType)
102   {
103     String url = getDomain() + "/lookup/id/" + identifier
104             + CONTENT_TYPE_JSON;
105     if (objectType != null)
106     {
107       url += "&" + OBJECT_TYPE + "=" + objectType;
108     }
109
110     try
111     {
112       return new URL(url);
113     } catch (MalformedURLException e)
114     {
115       return null;
116     }
117   }
118
119   @Override
120   protected boolean useGetRequest()
121   {
122     return true;
123   }
124
125   @Override
126   protected String getRequestMimeType(boolean multipleIds)
127   {
128     return "application/json";
129   }
130
131   @Override
132   protected String getResponseMimeType()
133   {
134     return "application/json";
135   }
136
137   /**
138    * Returns the gene id related to the given identifier (which may be for a
139    * gene, transcript or protein)
140    * 
141    * @param identifier
142    * @return
143    */
144   public String getGeneId(String identifier)
145   {
146     return getGeneId(identifier, null);
147   }
148
149   /**
150    * Returns the gene id related to the given identifier (which may be for a
151    * gene, transcript or protein)
152    * 
153    * @param identifier
154    * @param objectType
155    * @return
156    */
157   public String getGeneId(String identifier, String objectType)
158   {
159     List<String> ids = Arrays.asList(new String[] { identifier });
160
161     BufferedReader br = null;
162     try
163     {
164       URL url = getUrl(identifier, objectType);
165       if (url != null)
166       {
167         br = getHttpResponse(url, ids);
168       }
169       return br == null ? null : parseResponse(br);
170     } catch (IOException e)
171     {
172       // ignore
173       return null;
174     } finally
175     {
176       if (br != null)
177       {
178         try
179         {
180           br.close();
181         } catch (IOException e)
182         {
183           // ignore
184         }
185       }
186     }
187   }
188
189   /**
190    * Parses the JSON response and returns the gene identifier, or null if not
191    * found. If the returned object_type is Gene, returns the id, if Transcript
192    * returns the Parent. If it is Translation (peptide identifier), then the
193    * Parent is the transcript identifier, so we redo the search with this value.
194    * 
195    * @param br
196    * @return
197    * @throws IOException
198    */
199   protected String parseResponse(BufferedReader br) throws IOException
200   {
201     String geneId = null;
202     JSONParser jp = new JSONParser();
203     try
204     {
205       JSONObject val = (JSONObject) jp.parse(br);
206       String type = val.get(OBJECT_TYPE).toString();
207       if (OBJECT_TYPE_GENE.equalsIgnoreCase(type))
208       {
209         // got the gene - just returns its id
210         geneId = val.get(JSON_ID).toString();
211       }
212       else if (OBJECT_TYPE_TRANSCRIPT.equalsIgnoreCase(type))
213       {
214         // got the transcript - return its (Gene) Parent
215         geneId = val.get(PARENT).toString();
216       }
217       else if (OBJECT_TYPE_TRANSLATION.equalsIgnoreCase(type))
218       {
219         // got the protein - get its Parent, restricted to type Transcript
220         String transcriptId = val.get(PARENT).toString();
221         geneId = getGeneId(transcriptId, OBJECT_TYPE_TRANSCRIPT);
222       }
223     } catch (ParseException e)
224     {
225       // ignore
226     }
227     return geneId;
228   }
229
230   /**
231    * Calls the Ensembl lookup REST endpoint and retrieves the 'species' for the
232    * given identifier, or null if not found
233    * 
234    * @param identifier
235    * @return
236    */
237   public String getSpecies(String identifier)
238   {
239     String species = null;
240     JSONObject json = getResult(identifier, null);
241     if (json != null)
242     {
243       Object o = json.get(SPECIES);
244       if (o != null)
245       {
246         species = o.toString();
247       }
248     }
249     return species;
250   }
251
252   /**
253    * Calls the /lookup/id rest service and returns the response as a JSONObject,
254    * or null if any error
255    * 
256    * @param identifier
257    * @param objectType
258    *          (optional)
259    * @return
260    */
261   protected JSONObject getResult(String identifier, String objectType)
262   {
263     List<String> ids = Arrays.asList(new String[] { identifier });
264
265     BufferedReader br = null;
266     try
267     {
268
269       URL url = getUrl(identifier, objectType);
270
271       if (identifier.equals(lastId))
272       {
273         System.err.println("** Ensembl lookup " + url.toString()
274                 + " looping on Parent!");
275         return null;
276       }
277
278       lastId = identifier;
279
280       if (url != null)
281       {
282         br = getHttpResponse(url, ids);
283       }
284       return br == null ? null : (JSONObject) (new JSONParser().parse(br));
285     } catch (IOException | ParseException e)
286     {
287       System.err.println("Error parsing " + identifier + " lookup response "
288               + e.getMessage());
289       return null;
290     } finally
291     {
292       if (br != null)
293       {
294         try
295         {
296           br.close();
297         } catch (IOException e)
298         {
299           // ignore
300         }
301       }
302     }
303   }
304
305   /**
306    * Parses the JSON response and returns the gene identifier, or null if not
307    * found. If the returned object_type is Gene, returns the id, if Transcript
308    * returns the Parent. If it is Translation (peptide identifier), then the
309    * Parent is the transcript identifier, so we redo the search with this value,
310    * specifying that object_type should be Transcript.
311    * 
312    * @param jsonObject
313    * @return
314    */
315   protected String parseGeneId(JSONObject json)
316   {
317     if (json == null)
318     {
319       // e.g. lookup failed with 404 not found
320       return null;
321     }
322
323     String geneId = null;
324     String type = json.get(OBJECT_TYPE).toString();
325     if (OBJECT_TYPE_GENE.equalsIgnoreCase(type))
326     {
327       // got the gene - just returns its id
328       geneId = json.get(JSON_ID).toString();
329     }
330     else if (OBJECT_TYPE_TRANSCRIPT.equalsIgnoreCase(type))
331     {
332       // got the transcript - return its (Gene) Parent
333       geneId = json.get(PARENT).toString();
334     }
335     else if (OBJECT_TYPE_TRANSLATION.equalsIgnoreCase(type))
336     {
337       // got the protein - look up its Parent, restricted to type Transcript
338       String transcriptId = json.get(PARENT).toString();
339       geneId = parseGeneId(getResult(transcriptId, OBJECT_TYPE_TRANSCRIPT));
340     }
341
342     return geneId;
343   }
344
345   /**
346    * Calls the /lookup/id rest service for the given id, and if successful,
347    * parses and returns the gene's chromosomal coordinates
348    * 
349    * @param geneId
350    * @return
351    */
352   public GeneLociI getGeneLoci(String geneId)
353   {
354     return parseGeneLoci(getResult(geneId, OBJECT_TYPE_GENE));
355   }
356
357   /**
358    * Parses the /lookup/id response for species, asssembly_name,
359    * seq_region_name, start, end and returns an object that wraps them, or null
360    * if unsuccessful
361    * 
362    * @param json
363    * @return
364    */
365   GeneLociI parseGeneLoci(JSONObject json)
366   {
367     if (json == null)
368     {
369       return null;
370     }
371
372     try
373     {
374       final String species = json.get("species").toString();
375       final String assembly = json.get("assembly_name").toString();
376       final String chromosome = json.get("seq_region_name").toString();
377       String strand = json.get("strand").toString();
378       int start = Integer.parseInt(json.get("start").toString());
379       int end = Integer.parseInt(json.get("end").toString());
380       int fromEnd = end - start + 1;
381       boolean reverseStrand = "-1".equals(strand);
382       int toStart = reverseStrand ? end : start;
383       int toEnd = reverseStrand ? start : end;
384       List<int[]> fromRange = Collections.singletonList(new int[] { 1,
385           fromEnd });
386       List<int[]> toRange = Collections.singletonList(new int[] { toStart,
387           toEnd });
388       final MapList map = new MapList(fromRange, toRange, 1, 1);
389       return new GeneLociI()
390       {
391
392         @Override
393         public String getSpeciesId()
394         {
395           return species == null ? "" : species;
396         }
397
398         @Override
399         public String getAssemblyId()
400         {
401           return assembly;
402         }
403
404         @Override
405         public String getChromosomeId()
406         {
407           return chromosome;
408         }
409
410         @Override
411         public MapList getMap()
412         {
413           return map;
414         }
415       };
416     } catch (NullPointerException | NumberFormatException e)
417     {
418       Cache.log.error("Error looking up gene loci: " + e.getMessage());
419       e.printStackTrace();
420     }
421     return null;
422   }
423
424 }