JAL-2738 use GeneLocus extends DBRefEntry to hold chromosomal mappings
[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.datamodel.GeneLocus;
27 import jalview.datamodel.Mapping;
28 import jalview.util.MapList;
29
30 import java.io.BufferedReader;
31 import java.io.IOException;
32 import java.net.MalformedURLException;
33 import java.net.URL;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.List;
37
38 import org.json.simple.JSONObject;
39 import org.json.simple.parser.JSONParser;
40 import org.json.simple.parser.ParseException;
41
42 /**
43  * A client for the Ensembl /lookup REST endpoint, used to find the gene
44  * identifier given a gene, transcript or protein identifier, or to extract the
45  * species or chromosomal coordinates from the same service response
46  * 
47  * @author gmcarstairs
48  */
49 public class EnsemblLookup extends EnsemblRestClient
50 {
51   private static final String SPECIES = "species";
52
53   /**
54    * Default constructor (to use rest.ensembl.org)
55    */
56   public EnsemblLookup()
57   {
58     super();
59   }
60
61   /**
62    * Constructor given the target domain to fetch data from
63    * 
64    * @param
65    */
66   public EnsemblLookup(String d)
67   {
68     super(d);
69   }
70
71   @Override
72   public String getDbName()
73   {
74     return "ENSEMBL";
75   }
76
77   @Override
78   public AlignmentI getSequenceRecords(String queries) throws Exception
79   {
80     return null;
81   }
82
83   @Override
84   protected URL getUrl(List<String> ids) throws MalformedURLException
85   {
86     String identifier = ids.get(0);
87     return getUrl(identifier, null);
88   }
89
90   /**
91    * Gets the url for lookup of the given identifier, optionally with objectType
92    * also specified in the request
93    * 
94    * @param identifier
95    * @param objectType
96    * @return
97    */
98   protected URL getUrl(String identifier, String objectType)
99   {
100     String url = getDomain() + "/lookup/id/" + identifier
101             + CONTENT_TYPE_JSON;
102     if (objectType != null)
103     {
104       url += "&" + OBJECT_TYPE + "=" + objectType;
105     }
106
107     try
108     {
109       return new URL(url);
110     } catch (MalformedURLException e)
111     {
112       return null;
113     }
114   }
115
116   @Override
117   protected boolean useGetRequest()
118   {
119     return true;
120   }
121
122   /**
123    * Returns the gene id related to the given identifier (which may be for a
124    * gene, transcript or protein), or null if none is found
125    * 
126    * @param identifier
127    * @return
128    */
129   public String getGeneId(String identifier)
130   {
131     return getGeneId(identifier, null);
132   }
133
134   /**
135    * Returns the gene id related to the given identifier (which may be for a
136    * gene, transcript or protein), or null if none is found
137    * 
138    * @param identifier
139    * @param objectType
140    * @return
141    */
142   public String getGeneId(String identifier, String objectType)
143   {
144     return parseGeneId(getResult(identifier, objectType));
145   }
146
147   /**
148    * Parses the JSON response and returns the gene identifier, or null if not
149    * found. If the returned object_type is Gene, returns the id, if Transcript
150    * returns the Parent. If it is Translation (peptide identifier), then the
151    * Parent is the transcript identifier, so we redo the search with this value.
152    * 
153    * @param br
154    * @return
155    */
156   protected String parseGeneId(JSONObject val)
157   {
158     if (val == null)
159     {
160       return null;
161     }
162     String geneId = null;
163     String type = val.get(OBJECT_TYPE).toString();
164     if (OBJECT_TYPE_GENE.equalsIgnoreCase(type))
165     {
166       // got the gene - just returns its id
167       geneId = val.get(JSON_ID).toString();
168     }
169     else if (OBJECT_TYPE_TRANSCRIPT.equalsIgnoreCase(type))
170     {
171       // got the transcript - return its (Gene) Parent
172       geneId = val.get(PARENT).toString();
173     }
174     else if (OBJECT_TYPE_TRANSLATION.equalsIgnoreCase(type))
175     {
176       // got the protein - get its Parent, restricted to type Transcript
177       String transcriptId = val.get(PARENT).toString();
178       geneId = getGeneId(transcriptId, OBJECT_TYPE_TRANSCRIPT);
179     }
180
181     return geneId;
182   }
183
184   /**
185    * Calls the Ensembl lookup REST endpoint and retrieves the 'species' for the
186    * given identifier, or null if not found
187    * 
188    * @param identifier
189    * @return
190    */
191   public String getSpecies(String identifier)
192   {
193     String species = null;
194     JSONObject json = getResult(identifier, null);
195     if (json != null)
196     {
197       Object o = json.get(SPECIES);
198       if (o != null)
199       {
200         species = o.toString();
201       }
202     }
203     return species;
204   }
205
206   /**
207    * Calls the /lookup/id rest service and returns the response as a JSONObject,
208    * or null if any error
209    * 
210    * @param identifier
211    * @param objectType
212    *          (optional)
213    * @return
214    */
215   protected JSONObject getResult(String identifier, String objectType)
216   {
217     List<String> ids = Arrays.asList(new String[] { identifier });
218
219     BufferedReader br = null;
220     try
221     {
222       URL url = getUrl(identifier, objectType);
223
224       if (url != null)
225       {
226         br = getHttpResponse(url, ids);
227       }
228       return br == null ? null : (JSONObject) (new JSONParser().parse(br));
229     } catch (IOException | ParseException e)
230     {
231       System.err.println("Error parsing " + identifier + " lookup response "
232               + e.getMessage());
233       return null;
234     } finally
235     {
236       if (br != null)
237       {
238         try
239         {
240           br.close();
241         } catch (IOException e)
242         {
243           // ignore
244         }
245       }
246     }
247   }
248
249   /**
250    * Calls the /lookup/id rest service for the given id, and if successful,
251    * parses and returns the gene's chromosomal coordinates
252    * 
253    * @param geneId
254    * @return
255    */
256   public GeneLociI getGeneLoci(String geneId)
257   {
258     return parseGeneLoci(getResult(geneId, OBJECT_TYPE_GENE));
259   }
260
261   /**
262    * Parses the /lookup/id response for species, asssembly_name,
263    * seq_region_name, start, end and returns an object that wraps them, or null
264    * if unsuccessful
265    * 
266    * @param json
267    * @return
268    */
269   GeneLociI parseGeneLoci(JSONObject json)
270   {
271     if (json == null)
272     {
273       return null;
274     }
275
276     try
277     {
278       final String species = json.get("species").toString();
279       final String assembly = json.get("assembly_name").toString();
280       final String chromosome = json.get("seq_region_name").toString();
281       String strand = json.get("strand").toString();
282       int start = Integer.parseInt(json.get("start").toString());
283       int end = Integer.parseInt(json.get("end").toString());
284       int fromEnd = end - start + 1;
285       boolean reverseStrand = "-1".equals(strand);
286       int toStart = reverseStrand ? end : start;
287       int toEnd = reverseStrand ? start : end;
288       List<int[]> fromRange = Collections.singletonList(new int[] { 1,
289           fromEnd });
290       List<int[]> toRange = Collections.singletonList(new int[] { toStart,
291           toEnd });
292       final Mapping map = new Mapping(
293               new MapList(fromRange, toRange, 1, 1));
294       return new GeneLocus(species == null ? "" : species, assembly,
295               chromosome, map);
296     } catch (NullPointerException | NumberFormatException e)
297     {
298       Cache.log.error("Error looking up gene loci: " + e.getMessage());
299       e.printStackTrace();
300     }
301     return null;
302   }
303
304 }