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