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