JAL-3143 fetch Ensembl(Genomes) features as JSON not GFF
[jalview.git] / src / jalview / ext / ensembl / EnsemblFeatures.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.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.Sequence;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.io.gff.SequenceOntologyI;
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.ArrayList;
35 import java.util.Iterator;
36 import java.util.List;
37
38 import org.json.simple.JSONArray;
39 import org.json.simple.JSONObject;
40 import org.json.simple.parser.JSONParser;
41 import org.json.simple.parser.ParseException;
42
43 /**
44  * A client for fetching and processing Ensembl feature data in GFF format by
45  * calling the overlap REST service
46  * 
47  * @author gmcarstairs
48  * @see http://rest.ensembl.org/documentation/info/overlap_id
49  */
50 class EnsemblFeatures extends EnsemblRestClient
51 {
52   /*
53    * The default features to retrieve from Ensembl
54    * can override in getSequenceRecords parameter
55    */
56   private EnsemblFeatureType[] featuresWanted = { EnsemblFeatureType.cds,
57       EnsemblFeatureType.exon, EnsemblFeatureType.variation };
58
59   /**
60    * Default constructor (to use rest.ensembl.org)
61    */
62   public EnsemblFeatures()
63   {
64     super();
65   }
66
67   /**
68    * Constructor given the target domain to fetch data from
69    * 
70    * @param d
71    */
72   public EnsemblFeatures(String d)
73   {
74     super(d);
75   }
76
77   @Override
78   public String getDbName()
79   {
80     return "ENSEMBL (features)";
81   }
82
83   /**
84    * Makes a query to the REST overlap endpoint for the given sequence
85    * identifier. This returns an 'alignment' consisting of one 'dummy sequence'
86    * (the genomic sequence for which overlap features are returned by the
87    * service). This sequence will have on it sequence features which are the
88    * real information of interest, such as CDS regions or sequence variations.
89    */
90   @Override
91   public AlignmentI getSequenceRecords(String query) throws IOException
92   {
93     // TODO: use a vararg String... for getSequenceRecords instead?
94     List<String> queries = new ArrayList<>();
95     queries.add(query);
96     BufferedReader fp = getSequenceReader(queries);
97     if (fp == null)
98     {
99       return null;
100     }
101
102     SequenceI seq = parseFeaturesJson(fp);
103     return new Alignment(new SequenceI[] { seq });
104   }
105
106   /**
107    * Parses the JSON response into Jalview sequence features and attaches them
108    * to a dummy sequence
109    * 
110    * @param br
111    * @return
112    */
113   private SequenceI parseFeaturesJson(BufferedReader br)
114   {
115     SequenceI seq = new Sequence("Dummy", "");
116
117     JSONParser jp = new JSONParser();
118     try
119     {
120       JSONArray responses = (JSONArray) jp.parse(br);
121       Iterator rvals = responses.iterator();
122       while (rvals.hasNext())
123       {
124         try
125         {
126           JSONObject obj = (JSONObject) rvals.next();
127           String type = obj.get("feature_type").toString();
128           int start = Integer.parseInt(obj.get("start").toString());
129           int end = Integer.parseInt(obj.get("end").toString());
130           String source = obj.get("source").toString();
131           String strand = obj.get("strand").toString();
132           Object value = obj.get("consequence_type");
133           value = obj.get("alleles");
134           JSONArray allelesArray = (JSONArray) value;
135           String alleles = allelesArray == null ? null
136                   : allelesArray.toString(); // todo need as a List?
137           value = obj.get("clinical_significance");
138           JSONArray clinSigArray = (JSONArray) value;
139           String clinSig = clinSigArray == null ? null
140                   : clinSigArray.toString();
141
142           /*
143            * convert 'variation' to 'sequence_variant', and 'cds' to 'CDS'
144            * so as to have a valid SO term for the feature type
145            * ('gene', 'exon', 'transcript' don't need any conversion)
146            */
147           if ("variation".equals(type))
148           {
149             type = SequenceOntologyI.SEQUENCE_VARIANT;
150           }
151           else if (SequenceOntologyI.CDS.equalsIgnoreCase((type)))
152           {
153             type = SequenceOntologyI.CDS;
154           }
155           
156           String desc = getFirstNotNull(obj, "alleles", "external_name",
157                   JSON_ID);
158           SequenceFeature sf = new SequenceFeature(type, desc, start, end,
159                   source);
160           sf.setStrand("1".equals(strand) ? "+" : "-");
161           setFeatureAttribute(sf, obj, "id");
162           setFeatureAttribute(sf, obj, "Parent");
163           setFeatureAttribute(sf, obj, "consequence_type");
164           sf.setValue("alleles", alleles);
165           sf.setValue("clinical_significance", clinSig);
166
167           seq.addSequenceFeature(sf);
168         } catch (Throwable t)
169         {
170           // ignore - keep trying other features
171         }
172       }
173     } catch (ParseException | IOException e)
174     {
175       // ignore
176     }
177
178     return seq;
179   }
180
181   /**
182    * Returns the first non-null attribute found (if any) as a string
183    * 
184    * @param obj
185    * @param keys
186    * @return
187    */
188   protected String getFirstNotNull(JSONObject obj, String... keys)
189   {
190     String desc = null;
191
192     for (String key : keys)
193     {
194       Object val = obj.get(key);
195       if (val != null)
196       {
197         String s = val.toString();
198         if (!s.isEmpty())
199         {
200           return s;
201         }
202       }
203     }
204     return desc;
205   }
206
207   /**
208    * A helper method that reads the 'key' entry in the JSON object, and if not
209    * null, sets its string value as an attribute on the sequence feature
210    * 
211    * @param sf
212    * @param obj
213    * @param key
214    */
215   protected void setFeatureAttribute(SequenceFeature sf, JSONObject obj,
216           String key)
217   {
218     Object object = obj.get(key);
219     if (object != null)
220     {
221       sf.setValue(key, object.toString());
222     }
223   }
224
225   /**
226    * Returns a URL for the REST overlap endpoint
227    * 
228    * @param ids
229    * @return
230    */
231   @Override
232   protected URL getUrl(List<String> ids) throws MalformedURLException
233   {
234     StringBuffer urlstring = new StringBuffer(128);
235     urlstring.append(getDomain()).append("/overlap/id/").append(ids.get(0));
236
237     // @see https://github.com/Ensembl/ensembl-rest/wiki/Output-formats
238     urlstring.append("?content-type=" + getResponseMimeType());
239
240     /*
241      * specify object_type=gene in case is shared by transcript and/or protein;
242      * currently only fetching features for gene sequences;
243      * refactor in future if needed to fetch for transcripts
244      */
245     urlstring.append("&").append(OBJECT_TYPE).append("=")
246             .append(OBJECT_TYPE_GENE);
247
248     /*
249      * specify  features to retrieve
250      * @see http://rest.ensembl.org/documentation/info/overlap_id
251      * could make the list a configurable entry in .jalview_properties
252      */
253     for (EnsemblFeatureType feature : featuresWanted)
254     {
255       urlstring.append("&feature=").append(feature.name());
256     }
257
258     return new URL(urlstring.toString());
259   }
260
261   @Override
262   protected boolean useGetRequest()
263   {
264     return true;
265   }
266
267   /**
268    * Returns the MIME type for GFF3. For GET requests the Content-type header
269    * describes the required encoding of the response.
270    */
271   @Override
272   protected String getRequestMimeType()
273   {
274     return "application/json";
275   }
276
277   /**
278    * Returns the MIME type wanted for the response
279    */
280   @Override
281   protected String getResponseMimeType()
282   {
283     return "application/json";
284   }
285
286   /**
287    * Overloaded method that allows a list of features to retrieve to be
288    * specified
289    * 
290    * @param accId
291    * @param features
292    * @return
293    * @throws IOException
294    */
295   protected AlignmentI getSequenceRecords(String accId,
296           EnsemblFeatureType[] features) throws IOException
297   {
298     featuresWanted = features;
299     return getSequenceRecords(accId);
300   }
301 }