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