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