Clover icon

Coverage Report

  1. Project Clover database Thu Aug 13 2020 12:04:21 BST
  2. Package jalview.ext.ensembl

File EnsemblMap.java

 

Coverage histogram

../../../img/srcFileCovDistChart0.png
56% of files have more coverage

Code metrics

26
82
14
1
388
212
33
0.4
5.86
14
2.36

Classes

Class Line # Actions
EnsemblMap 53 82 33
0.00%
 

Contributing tests

No tests hitting this source file were found.

Source view

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  0 toggle public EnsemblMap()
67    {
68  0 super();
69    }
70   
71    /**
72    * Constructor given the target domain to fetch data from
73    *
74    * @param
75    */
 
76  0 toggle public EnsemblMap(String domain)
77    {
78  0 super(domain);
79    }
80   
 
81  0 toggle @Override
82    public String getDbName()
83    {
84  0 return DBRefSource.ENSEMBL;
85    }
86   
 
87  0 toggle @Override
88    public AlignmentI getSequenceRecords(String queries) throws Exception
89    {
90  0 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  0 toggle 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  0 boolean forward = startPos <= endPos;
115  0 int start = forward ? startPos : endPos;
116  0 int end = forward ? endPos : startPos;
117  0 String strand = forward ? "1" : "-1";
118  0 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  0 return new URL(url);
123    }
124   
 
125  0 toggle @Override
126    protected boolean useGetRequest()
127    {
128  0 return true;
129    }
130   
 
131  0 toggle @Override
132    protected URL getUrl(List<String> ids) throws MalformedURLException
133    {
134  0 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  0 toggle public int[] getAssemblyMapping(String species, String chromosome,
150    String fromRef, String toRef, int[] queryRange)
151    {
152  0 URL url = null;
153  0 try
154    {
155  0 url = getAssemblyMapUrl(species, chromosome, fromRef, toRef, queryRange[0],
156    queryRange[1]);
157  0 return (parseAssemblyMappingResponse(url));
158    } catch (Throwable t)
159    {
160  0 System.out.println("Error calling " + url + ": " + t.getMessage());
161  0 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  0 toggle @SuppressWarnings("unchecked")
181    protected int[] parseAssemblyMappingResponse(URL url)
182    {
183  0 int[] result = null;
184   
185  0 try
186    {
187  0 Iterator<Object> rvals = (Iterator<Object>) getJSON(url, null, -1, MODE_ITERATOR, MAPPINGS);
188  0 if (rvals == null)
189    {
190  0 return null;
191    }
192  0 while (rvals.hasNext())
193    {
194    // todo check for "mapped"
195  0 Map<String, Object> val = (Map<String, Object>) rvals.next();
196  0 Map<String, Object> mapped = (Map<String, Object>) val.get(MAPPED);
197  0 int start = Integer.parseInt(mapped.get("start").toString());
198  0 int end = Integer.parseInt(mapped.get("end").toString());
199  0 String strand = mapped.get("strand").toString();
200  0 if ("1".equals(strand))
201    {
202  0 result = new int[] { start, end };
203    }
204    else
205    {
206  0 result = new int[] { end, start };
207    }
208    }
209    } catch (IOException | ParseException | NumberFormatException e)
210    {
211    // ignore
212    }
213  0 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  0 toggle public GeneLociI getCdsMapping(String division, String accession,
229    int start, int end)
230    {
231  0 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  0 toggle public GeneLociI getCdnaMapping(String division, String accession,
247    int start, int end)
248    {
249  0 return getIdMapping(division, accession, start, end, CDNA);
250    }
251   
 
252  0 toggle GeneLociI getIdMapping(String division, String accession, int start,
253    int end, String cdsOrCdna)
254    {
255  0 URL url = null;
256  0 try
257    {
258  0 String domain = new EnsemblInfo().getDomain(division);
259  0 if (domain != null)
260    {
261  0 url = getIdMapUrl(domain, accession, start, end, cdsOrCdna);
262  0 return (parseIdMappingResponse(url, accession, domain));
263    }
264  0 return null;
265    } catch (Throwable t)
266    {
267  0 System.out.println("Error calling " + url + ": " + t.getMessage());
268  0 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  0 toggle URL getIdMapUrl(String domain, String accession, int start, int end,
286    String cdsOrCdna) throws MalformedURLException
287    {
288  0 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  0 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  0 toggle @SuppressWarnings("unchecked")
315    GeneLociI parseIdMappingResponse(URL url, String accession,
316    String domain)
317    {
318   
319  0 try
320    {
321  0 Iterator<Object> rvals = (Iterator<Object>) getJSON(url, null, -1, MODE_ITERATOR, MAPPINGS);
322  0 if (rvals == null)
323    {
324  0 return null;
325    }
326  0 String assembly = null;
327  0 String chromosome = null;
328  0 int fromEnd = 0;
329  0 List<int[]> regions = new ArrayList<>();
330   
331  0 while (rvals.hasNext())
332    {
333  0 Map<String, Object> val = (Map<String, Object>) rvals.next();
334  0 Map<String, Object> original = (Map<String, Object>) val.get("original");
335  0 fromEnd = Integer.parseInt(original.get("end").toString());
336   
337  0 Map<String, Object> mapped = (Map<String, Object>) val.get(MAPPED);
338  0 int start = Integer.parseInt(mapped.get("start").toString());
339  0 int end = Integer.parseInt(mapped.get("end").toString());
340  0 String ass = mapped.get("assembly_name").toString();
341  0 if (assembly != null && !assembly.equals(ass))
342    {
343  0 System.err
344    .println("EnsemblMap found multiple assemblies - can't resolve");
345  0 return null;
346    }
347  0 assembly = ass;
348  0 String chr = mapped.get("seq_region_name").toString();
349  0 if (chromosome != null && !chromosome.equals(chr))
350    {
351  0 System.err
352    .println("EnsemblMap found multiple chromosomes - can't resolve");
353  0 return null;
354    }
355  0 chromosome = chr;
356  0 String strand = mapped.get("strand").toString();
357  0 if ("-1".equals(strand))
358    {
359  0 regions.add(new int[] { end, start });
360    }
361    else
362    {
363  0 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  0 final String species = new EnsemblLookup(domain)
372    .getSpecies(accession);
373  0 final String as = assembly;
374  0 final String chr = chromosome;
375  0 List<int[]> fromRange = Collections.singletonList(new int[] { 1,
376    fromEnd });
377  0 Mapping mapping = new Mapping(new MapList(fromRange, regions, 1, 1));
378  0 return new GeneLocus(species == null ? "" : species, as, chr,
379    mapping);
380    } catch (IOException | ParseException | NumberFormatException e)
381    {
382    // ignore
383    }
384   
385  0 return null;
386    }
387   
388    }