cfc679cd05bc61b25bc4b05a0309b14cc478b7e4
[jalview.git] / src / jalview / ext / ensembl / EnsemblMap.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.datamodel.AlignmentI;
24 import jalview.datamodel.DBRefSource;
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.ArrayList;
34 import java.util.Collections;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Map;
38
39 import org.json.simple.parser.ParseException;
40
41 /**
42  * A client for the Ensembl REST service /map endpoint, to convert from
43  * coordinates of one genome assembly to another.
44  * <p>
45  * Note that species and assembly identifiers passed to this class must be valid
46  * in Ensembl. They are not case sensitive.
47  * 
48  * @author gmcarstairs
49  * @see https://rest.ensembl.org/documentation/info/assembly_map
50  * @see https://rest.ensembl.org/info/assembly/human?content-type=text/xml
51  * @see https://rest.ensembl.org/info/species?content-type=text/xml
52  */
53 public class EnsemblMap extends EnsemblRestClient
54 {
55   private static final String MAPPED = "mapped";
56
57   private static final String MAPPINGS = "mappings";
58
59   private static final String CDS = "cds";
60
61   private static final String CDNA = "cdna";
62
63   /**
64    * Default constructor (to use rest.ensembl.org)
65    */
66   public EnsemblMap()
67   {
68     super();
69   }
70
71   /**
72    * Constructor given the target domain to fetch data from
73    * 
74    * @param
75    */
76   public EnsemblMap(String domain)
77   {
78     super(domain);
79   }
80
81   @Override
82   public String getDbName()
83   {
84     return DBRefSource.ENSEMBL;
85   }
86
87   @Override
88   public AlignmentI getSequenceRecords(String queries) throws Exception
89   {
90     return null; // not used
91   }
92
93   /**
94    * Constructs a URL of the format <code>
95    * http://rest.ensembl.org/map/human/GRCh38/17:45051610..45109016:1/GRCh37?content-type=application/json
96    * </code>
97    * 
98    * @param species
99    * @param chromosome
100    * @param fromRef
101    * @param toRef
102    * @param startPos
103    * @param endPos
104    * @return
105    * @throws MalformedURLException
106    */
107   protected URL getAssemblyMapUrl(String species, String chromosome, String fromRef,
108           String toRef, int startPos, int endPos)
109           throws MalformedURLException
110   {
111     /*
112      * start-end might be reverse strand - present forwards to the service
113      */
114     boolean forward = startPos <= endPos;
115     int start = forward ? startPos : endPos;
116     int end = forward ? endPos : startPos;
117     String strand = forward ? "1" : "-1";
118     String url = String.format(
119             "%s/map/%s/%s/%s:%d..%d:%s/%s?content-type=application/json",
120             getDomain(), species, fromRef, chromosome, start, end, strand,
121             toRef);
122     return new URL(url);
123   }
124
125   @Override
126   protected boolean useGetRequest()
127   {
128     return true;
129   }
130
131   @Override
132   protected URL getUrl(List<String> ids) throws MalformedURLException
133   {
134     return null; // not used
135   }
136
137   /**
138    * Calls the REST /map service to get the chromosomal coordinates (start/end)
139    * in 'toRef' that corresponding to the (start/end) queryRange in 'fromRef'
140    * 
141    * @param species
142    * @param chromosome
143    * @param fromRef
144    * @param toRef
145    * @param queryRange
146    * @return
147    * @see http://rest.ensemblgenomes.org/documentation/info/assembly_map
148    */
149   public int[] getAssemblyMapping(String species, String chromosome,
150           String fromRef, String toRef, int[] queryRange)
151   {
152     URL url = null;
153     try
154     {
155       url = getAssemblyMapUrl(species, chromosome, fromRef, toRef, queryRange[0],
156               queryRange[1]);
157       return (parseAssemblyMappingResponse(url));
158     } catch (Throwable t)
159     {
160       System.out.println("Error calling " + url + ": " + t.getMessage());
161       return null;
162     }
163   }
164
165   /**
166    * Parses the JSON response from the /map/&lt;species&gt;/ REST service. The
167    * format is (with some fields omitted)
168    * 
169    * <pre>
170    *  {"mappings": 
171    *    [{
172    *       "original": {"end":45109016,"start":45051610},
173    *       "mapped"  : {"end":43186384,"start":43128978} 
174    *  }] }
175    * </pre>
176    * 
177    * @param br
178    * @return
179    */
180   @SuppressWarnings("unchecked")
181   protected int[] parseAssemblyMappingResponse(URL url)
182   {
183     int[] result = null;
184
185     try
186     {
187       Iterator<Object> rvals = (Iterator<Object>) getJSON(url, null, -1, MODE_ITERATOR, MAPPINGS);
188       if (rvals == null)
189       {
190         return null;
191       }
192       while (rvals.hasNext())
193       {
194         // todo check for "mapped"
195         Map<String, Object> val = (Map<String, Object>) rvals.next();
196         Map<String, Object> mapped = (Map<String, Object>) val.get(MAPPED);
197         int start = Integer.parseInt(mapped.get("start").toString());
198         int end = Integer.parseInt(mapped.get("end").toString());
199         String strand = mapped.get("strand").toString();
200         if ("1".equals(strand))
201         {
202           result = new int[] { start, end };
203         }
204         else
205         {
206           result = new int[] { end, start };
207         }
208       }
209     } catch (IOException | ParseException | NumberFormatException e)
210     {
211       // ignore
212     }
213     return result;
214   }
215
216   /**
217    * Calls the REST /map/cds/id service, and returns a DBRefEntry holding the
218    * returned chromosomal coordinates, or returns null if the call fails
219    * 
220    * @param division
221    *          e.g. Ensembl, EnsemblMetazoa
222    * @param accession
223    *          e.g. ENST00000592782, Y55B1AR.1.1
224    * @param start
225    * @param end
226    * @return
227    */
228   public GeneLociI getCdsMapping(String division, String accession,
229           int start, int end)
230   {
231     return getIdMapping(division, accession, start, end, CDS);
232   }
233
234   /**
235    * Calls the REST /map/cdna/id service, and returns a DBRefEntry holding the
236    * returned chromosomal coordinates, or returns null if the call fails
237    * 
238    * @param division
239    *          e.g. Ensembl, EnsemblMetazoa
240    * @param accession
241    *          e.g. ENST00000592782, Y55B1AR.1.1
242    * @param start
243    * @param end
244    * @return
245    */
246   public GeneLociI getCdnaMapping(String division, String accession,
247           int start, int end)
248   {
249     return getIdMapping(division, accession, start, end, CDNA);
250   }
251
252   GeneLociI getIdMapping(String division, String accession, int start,
253           int end, String cdsOrCdna)
254   {
255     URL url = null;
256     try
257     {
258       String domain = new EnsemblInfo().getDomain(division);
259       if (domain != null)
260       {
261         url = getIdMapUrl(domain, accession, start, end, cdsOrCdna);
262         return (parseIdMappingResponse(url, accession, domain));
263       }
264       return null;
265     } catch (Throwable t)
266     {
267       System.out.println("Error calling " + url + ": " + t.getMessage());
268       return null;
269     }
270   }
271
272   /**
273    * Constructs a URL to the /map/cds/<id> or /map/cdna/<id> REST service. The
274    * REST call is to either ensembl or ensemblgenomes, as determined from the
275    * division, e.g. Ensembl or EnsemblProtists.
276    * 
277    * @param domain
278    * @param accession
279    * @param start
280    * @param end
281    * @param cdsOrCdna
282    * @return
283    * @throws MalformedURLException
284    */
285   URL getIdMapUrl(String domain, String accession, int start, int end,
286           String cdsOrCdna) throws MalformedURLException
287   {
288     String url = String
289             .format("%s/map/%s/%s/%d..%d?include_original_region=1&content-type=application/json",
290                     domain, cdsOrCdna, accession, start, end);
291     return new URL(url);
292   }
293
294   /**
295    * Parses the JSON response from the /map/cds/ or /map/cdna REST service. The
296    * format is
297    * 
298    * <pre>
299    * {"mappings":
300    *   [
301    *    {"assembly_name":"TAIR10","end":2501311,"seq_region_name":"1","gap":0,
302    *     "strand":-1,"coord_system":"chromosome","rank":0,"start":2501114},
303    *    {"assembly_name":"TAIR10","end":2500815,"seq_region_name":"1","gap":0,
304    *     "strand":-1,"coord_system":"chromosome","rank":0,"start":2500714}
305    *   ]
306    * }
307    * </pre>
308    * 
309    * @param br
310    * @param accession
311    * @param domain
312    * @return
313    */
314   @SuppressWarnings("unchecked")
315 GeneLociI parseIdMappingResponse(URL url, String accession,
316           String domain)
317   {
318
319     try
320     {
321       Iterator<Object> rvals = (Iterator<Object>) getJSON(url, null, -1, MODE_ITERATOR, MAPPINGS);
322       if (rvals == null)
323       {
324         return null;
325       }
326       String assembly = null;
327       String chromosome = null;
328       int fromEnd = 0;
329       List<int[]> regions = new ArrayList<>();
330
331       while (rvals.hasNext())
332       {
333         Map<String, Object> val = (Map<String, Object>) rvals.next();
334         Map<String, Object> original = (Map<String, Object>) val.get("original");
335         fromEnd = Integer.parseInt(original.get("end").toString());
336
337         Map<String, Object> mapped = (Map<String, Object>) val.get(MAPPED);
338         int start = Integer.parseInt(mapped.get("start").toString());
339         int end = Integer.parseInt(mapped.get("end").toString());
340         String ass = mapped.get("assembly_name").toString();
341         if (assembly != null && !assembly.equals(ass))
342         {
343           System.err
344                   .println("EnsemblMap found multiple assemblies - can't resolve");
345           return null;
346         }
347         assembly = ass;
348         String chr = mapped.get("seq_region_name").toString();
349         if (chromosome != null && !chromosome.equals(chr))
350         {
351           System.err
352                   .println("EnsemblMap found multiple chromosomes - can't resolve");
353           return null;
354         }
355         chromosome = chr;
356         String strand = mapped.get("strand").toString();
357         if ("-1".equals(strand))
358         {
359           regions.add(new int[] { end, start });
360         }
361         else
362         {
363           regions.add(new int[] { start, end });
364         }
365       }
366
367       /*
368        * processed all mapped regions on chromosome, assemble the result,
369        * having first fetched the species id for the accession
370        */
371       final String species = new EnsemblLookup(domain)
372               .getSpecies(accession);
373       final String as = assembly;
374       final String chr = chromosome;
375       List<int[]> fromRange = Collections.singletonList(new int[] { 1,
376           fromEnd });
377       Mapping mapping = new Mapping(new MapList(fromRange, regions, 1, 1));
378       return new GeneLocus(species == null ? "" : species, as, chr,
379               mapping);
380     } catch (IOException | ParseException | NumberFormatException e)
381     {
382       // ignore
383     }
384
385     return null;
386   }
387
388 }