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