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