Merge branch 'alpha/JAL-3362_Jalview_212_alpha' into alpha/merge_212_JalviewJS_2112
[jalview.git] / src / jalview / ws / dbsources / Uniprot.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.ws.dbsources;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32 import jalview.schemes.ResidueProperties;
33 import jalview.util.StringUtils;
34 import jalview.ws.seqfetcher.DbSourceProxyImpl;
35 import jalview.xml.binding.uniprot.DbReferenceType;
36 import jalview.xml.binding.uniprot.Entry;
37 import jalview.xml.binding.uniprot.FeatureType;
38 import jalview.xml.binding.uniprot.LocationType;
39 import jalview.xml.binding.uniprot.PositionType;
40 import jalview.xml.binding.uniprot.PropertyType;
41
42 import java.io.InputStream;
43 import java.net.URL;
44 import java.net.URLConnection;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.Vector;
48
49 import javax.xml.bind.JAXBContext;
50 import javax.xml.bind.JAXBElement;
51 import javax.xml.bind.JAXBException;
52 import javax.xml.stream.FactoryConfigurationError;
53 import javax.xml.stream.XMLInputFactory;
54 import javax.xml.stream.XMLStreamException;
55 import javax.xml.stream.XMLStreamReader;
56
57 import com.stevesoft.pat.Regex;
58
59 /**
60  * This class queries the Uniprot database for sequence data, unmarshals the
61  * returned XML, and converts it to Jalview Sequence records (including attached
62  * database references and sequence features)
63  * 
64  * @author JimP
65  * 
66  */
67 public class Uniprot extends DbSourceProxyImpl
68 {
69   private static final String DEFAULT_UNIPROT_DOMAIN = "https://www.uniprot.org";
70
71   private static final String BAR_DELIMITER = "|";
72
73   /**
74    * Constructor
75    */
76   public Uniprot()
77   {
78     super();
79   }
80
81   private String getDomain()
82   {
83     return Cache.getDefault("UNIPROT_DOMAIN", DEFAULT_UNIPROT_DOMAIN);
84   }
85
86   /*
87    * (non-Javadoc)
88    * 
89    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
90    */
91   @Override
92   public String getAccessionSeparator()
93   {
94     return null;
95   }
96
97   /*
98    * (non-Javadoc)
99    * 
100    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
101    */
102   @Override
103   public Regex getAccessionValidator()
104   {
105     return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
106   }
107
108   /*
109    * (non-Javadoc)
110    * 
111    * @see jalview.ws.DbSourceProxy#getDbSource()
112    */
113   @Override
114   public String getDbSource()
115   {
116     return DBRefSource.UNIPROT;
117   }
118
119   /*
120    * (non-Javadoc)
121    * 
122    * @see jalview.ws.DbSourceProxy#getDbVersion()
123    */
124   @Override
125   public String getDbVersion()
126   {
127     return "0"; // we really don't know what version we're on.
128   }
129
130   /*
131    * (non-Javadoc)
132    * 
133    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
134    */
135   @Override
136   public AlignmentI getSequenceRecords(String queries) throws Exception
137   {
138     startQuery();
139     try
140     {
141       queries = queries.toUpperCase().replaceAll(
142               "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
143       AlignmentI al = null;
144
145       String downloadstring = getDomain() + "/uniprot/" + queries
146               + ".xml";
147
148       URL url = new URL(downloadstring);
149       URLConnection urlconn = url.openConnection();
150       InputStream istr = urlconn.getInputStream();
151       List<Entry> entries = getUniprotEntries(istr);
152       if (entries != null)
153       {
154         List<SequenceI> seqs = new ArrayList<>();
155         for (Entry entry : entries)
156         {
157           seqs.add(uniprotEntryToSequence(entry));
158         }
159         al = new Alignment(seqs.toArray(new SequenceI[seqs.size()]));
160       }
161
162       stopQuery();
163       return al;
164     } catch (Exception e)
165     {
166       throw (e);
167     } finally
168     {
169       stopQuery();
170     }
171   }
172
173   /**
174    * Converts an Entry object (bound from Uniprot XML) to a Jalview Sequence
175    * 
176    * @param entry
177    * @return
178    */
179   SequenceI uniprotEntryToSequence(Entry entry)
180   {
181     String id = getUniprotEntryId(entry);
182     /*
183      * Sequence should not include any whitespace, but JAXB leaves these in
184      */
185     String seqString = entry.getSequence().getValue().replaceAll("\\s*",
186             "");
187
188     SequenceI sequence = new Sequence(id,
189             seqString);
190     sequence.setDescription(getUniprotEntryDescription(entry));
191
192     /*
193      * add a 'self' DBRefEntry for each accession
194      */
195     final String dbVersion = getDbVersion();
196     List<DBRefEntry> dbRefs = new ArrayList<>();
197     for (String accessionId : entry.getAccession())
198     {
199       DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT, dbVersion,
200               accessionId);
201       dbRefs.add(dbRef);
202     }
203
204     /*
205      * add a DBRefEntry for each dbReference element in the XML;
206      * also add a PDBEntry if type="PDB";
207      * also add an EMBLCDS dbref if protein sequence id is given
208      * also add an Ensembl dbref " " " " " "
209      */
210     Vector<PDBEntry> pdbRefs = new Vector<>();
211     for (DbReferenceType dbref : entry.getDbReference())
212     {
213       String type = dbref.getType();
214       DBRefEntry dbr = new DBRefEntry(type,
215               DBRefSource.UNIPROT + ":" + dbVersion, dbref.getId());
216       dbRefs.add(dbr);
217       if ("PDB".equals(type))
218       {
219         pdbRefs.add(new PDBEntry(dbr));
220       }
221       if ("EMBL".equals(type))
222       {
223         /*
224          * e.g. Uniprot accession Q9BXM7 has
225          * <dbReference type="EMBL" id="M19359">
226          *   <property type="protein sequence ID" value="AAA40981.1"/>
227          *   <property type="molecule type" value="Genomic_DNA"/>
228          * </dbReference> 
229          */
230         String cdsId = getProperty(dbref.getProperty(),
231                 "protein sequence ID");
232         if (cdsId != null && cdsId.trim().length() > 0)
233         {
234           // remove version
235           String[] vrs = cdsId.split("\\.");
236           String version = vrs.length > 1 ? vrs[1]
237                   : DBRefSource.UNIPROT + ":" + dbVersion;
238           dbr = new DBRefEntry(DBRefSource.EMBLCDS, version, vrs[0]);
239           dbRefs.add(dbr);
240         }
241       }
242       if ("Ensembl".equals(type))
243       {
244         /*
245          * e.g. Uniprot accession Q9BXM7 has
246          * <dbReference type="Ensembl" id="ENST00000321556">
247          *   <molecule id="Q9BXM7-1"/>
248          *   <property type="protein sequence ID" value="ENSP00000364204"/>
249          *   <property type="gene ID" value="ENSG00000158828"/>
250          * </dbReference> 
251          */
252         String cdsId = getProperty(dbref.getProperty(),
253                 "protein sequence ID");
254         if (cdsId != null && cdsId.trim().length() > 0)
255         {
256           dbr = new DBRefEntry(DBRefSource.ENSEMBL,
257                   DBRefSource.UNIPROT + ":" + dbVersion, cdsId.trim());
258           dbRefs.add(dbr);
259         }
260       }
261     }
262
263     /*
264      * create features; they have either begin and end, or position, in XML
265      */
266     sequence.setPDBId(pdbRefs);
267     if (entry.getFeature() != null)
268     {
269       for (FeatureType uf : entry.getFeature())
270       {
271         LocationType location = uf.getLocation();
272         int start = 0;
273         int end = 0;
274         if (location.getPosition() != null)
275         {
276           start = location.getPosition().getPosition().intValue();
277           end = start;
278         }
279         else
280         {
281           start = location.getBegin().getPosition().intValue();
282           end = location.getEnd().getPosition().intValue();
283         }
284         SequenceFeature sf = new SequenceFeature(uf.getType(),
285                 getDescription(uf), start, end, "Uniprot");
286         sf.setStatus(uf.getStatus());
287         sequence.addSequenceFeature(sf);
288       }
289     }
290     for (DBRefEntry dbr : dbRefs)
291     {
292       sequence.addDBRef(dbr);
293     }
294     return sequence;
295   }
296
297   /**
298    * A helper method that builds a sequence feature description
299    * 
300    * @param feature
301    * @return
302    */
303   static String getDescription(FeatureType feature)
304   {
305     String orig = feature.getOriginal();
306     List<String> variants = feature.getVariation();
307     StringBuilder sb = new StringBuilder();
308
309     /*
310      * append variant in standard format if present
311      * e.g. p.Arg59Lys
312      * multiple variants are split over lines using <br>
313      */
314     boolean asHtml = false;
315     if (orig != null && !orig.isEmpty() && variants != null
316             && !variants.isEmpty())
317     {
318       int p = 0;
319       for (String var : variants)
320       {
321         // TODO proper HGVS nomenclature for delins structural variations
322         // http://varnomen.hgvs.org/recommendations/protein/variant/delins/
323         // for now we are pragmatic - any orig/variant sequence longer than
324         // three characters is shown with single-character notation rather than
325         // three-letter notation
326         sb.append("p.");
327         if (orig.length() < 4)
328         {
329           for (int c = 0, clen = orig.length(); c < clen; c++)
330           {
331             char origchar = orig.charAt(c);
332             String orig3 = ResidueProperties.aa2Triplet.get("" + origchar);
333             sb.append(orig3 == null ? origchar
334                     : StringUtils.toSentenceCase(orig3));
335           }
336         }
337         else
338         {
339           sb.append(orig);
340         }
341
342         LocationType location = feature.getLocation();
343         PositionType start = location.getPosition() == null
344                 ? location.getBegin()
345                 : location.getPosition();
346         sb.append(Integer.toString(start.getPosition().intValue()));
347
348         if (var.length() < 4)
349         {
350           for (int c = 0, clen = var.length(); c < clen; c++)
351           {
352             char varchar = var.charAt(c);
353             String var3 = ResidueProperties.aa2Triplet.get("" + varchar);
354
355             sb.append(var3 != null ? StringUtils.toSentenceCase(var3)
356                     : "" + varchar);
357           }
358         }
359         else
360         {
361           sb.append(var);
362         }
363         if (++p != variants.size())
364         {
365           sb.append("<br/>&nbsp;&nbsp;");
366           asHtml = true;
367         }
368         else
369         {
370           sb.append(" ");
371         }
372       }
373     }
374     String description = feature.getDescription();
375     if (description != null)
376     {
377       sb.append(description);
378     }
379     if (asHtml)
380     {
381       sb.insert(0, "<html>");
382       sb.append("</html>");
383     }
384
385     return sb.toString();
386   }
387
388   /**
389    * A helper method that searches the list of properties for one with the given
390    * key, and if found returns the property value, else returns null
391    * 
392    * @param properties
393    * @param key
394    * @return
395    */
396   static String getProperty(List<PropertyType> properties, String key)
397   {
398     String value = null;
399     if (properties != null)
400     {
401       for (PropertyType prop : properties)
402       {
403         if (key.equals(prop.getType()))
404         {
405           value = prop.getValue();
406           break;
407         }
408       }
409     }
410     return value;
411   }
412
413   /**
414    * Extracts xml element entry/protein/recommendedName/fullName
415    * 
416    * @param entry
417    * @return
418    */
419   static String getUniprotEntryDescription(Entry entry)
420   {
421     String desc = "";
422     if (entry.getProtein() != null
423             && entry.getProtein().getRecommendedName() != null)
424     {
425       // fullName is mandatory if recommendedName is present
426       desc = entry.getProtein().getRecommendedName().getFullName()
427               .getValue();
428     }
429     return desc;
430   }
431
432   /**
433    * Constructs a sequence id by concatenating all entry/name elements with '|'
434    * separator
435    * 
436    * @param entry
437    * @return
438    */
439   static String getUniprotEntryId(Entry entry)
440   {
441     StringBuilder name = new StringBuilder(32);
442     for (String n : entry.getName())
443     {
444       if (name.length() > 0)
445       {
446         name.append(BAR_DELIMITER);
447       }
448       name.append(n);
449     }
450     return name.toString();
451   }
452
453   /*
454    * (non-Javadoc)
455    * 
456    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
457    */
458   @Override
459   public boolean isValidReference(String accession)
460   {
461     // TODO: make the following a standard validator
462     return (accession == null || accession.length() < 2) ? false
463             : getAccessionValidator().search(accession);
464   }
465
466   /**
467    * return LDHA_CHICK uniprot entry
468    */
469   @Override
470   public String getTestQuery()
471   {
472     return "P00340";
473   }
474
475   @Override
476   public String getDbName()
477   {
478     return "Uniprot"; // getDbSource();
479   }
480
481   @Override
482   public int getTier()
483   {
484     return 0;
485   }
486
487   /**
488    * Reads the reply to the EBI Fetch Uniprot data query, unmarshals it to an
489    * Uniprot object, and returns the enclosed Entry objects, or null on any
490    * failure
491    * 
492    * @param is
493    * @return
494    */
495   public List<Entry> getUniprotEntries(InputStream is)
496   {
497     List<Entry> entries = null;
498     try
499     {
500       JAXBContext jc = JAXBContext
501               .newInstance("jalview.xml.binding.uniprot");
502       XMLStreamReader streamReader = XMLInputFactory.newInstance()
503               .createXMLStreamReader(is);
504       javax.xml.bind.Unmarshaller um = jc.createUnmarshaller();
505       JAXBElement<jalview.xml.binding.uniprot.Uniprot> uniprotElement = 
506                   um.unmarshal(streamReader, jalview.xml.binding.uniprot.Uniprot.class);
507       jalview.xml.binding.uniprot.Uniprot uniprot = uniprotElement.getValue();
508       
509       if (uniprot != null && !uniprot.getEntry().isEmpty())
510       {
511         entries = uniprot.getEntry();
512       }
513     } catch (JAXBException | XMLStreamException
514             | FactoryConfigurationError e)
515     {
516       e.printStackTrace();
517     }
518     return entries;
519   }
520 }