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