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