JAL-2232 extract EMBLCDS refs from EMBL refs on 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.datamodel.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.DBRefSource;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.UniprotEntry;
32 import jalview.datamodel.UniprotFile;
33 import jalview.util.DBRefUtils;
34 import jalview.ws.ebi.EBIFetchClient;
35 import jalview.ws.seqfetcher.DbSourceProxyImpl;
36
37 import java.io.File;
38 import java.io.FileReader;
39 import java.io.Reader;
40 import java.net.URL;
41 import java.util.ArrayList;
42 import java.util.Vector;
43
44 import org.exolab.castor.mapping.Mapping;
45 import org.exolab.castor.xml.Unmarshaller;
46
47 import com.stevesoft.pat.Regex;
48
49 /**
50  * @author JimP
51  * 
52  */
53 public class Uniprot extends DbSourceProxyImpl
54 {
55   private static final String BAR_DELIMITER = "|";
56
57   /*
58    * Castor mapping loaded from uniprot_mapping.xml
59    */
60   private static Mapping map;
61
62   /**
63    * Constructor
64    */
65   public Uniprot()
66   {
67     super();
68   }
69
70   /*
71    * (non-Javadoc)
72    * 
73    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
74    */
75   @Override
76   public String getAccessionSeparator()
77   {
78     return null;
79   }
80
81   /*
82    * (non-Javadoc)
83    * 
84    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
85    */
86   @Override
87   public Regex getAccessionValidator()
88   {
89     return new Regex("([A-Z]+[0-9]+[A-Z0-9]+|[A-Z0-9]+_[A-Z0-9]+)");
90   }
91
92   /*
93    * (non-Javadoc)
94    * 
95    * @see jalview.ws.DbSourceProxy#getDbSource()
96    */
97   @Override
98   public String getDbSource()
99   {
100     return DBRefSource.UNIPROT;
101   }
102
103   /*
104    * (non-Javadoc)
105    * 
106    * @see jalview.ws.DbSourceProxy#getDbVersion()
107    */
108   @Override
109   public String getDbVersion()
110   {
111     return "0"; // we really don't know what version we're on.
112   }
113
114   /**
115    * Reads a file containing the reply to the EBI Fetch Uniprot data query,
116    * unmarshals it to a UniprotFile object, and returns the list of UniprotEntry
117    * data models (mapped from &lt;entry&gt; elements)
118    * 
119    * @param fileReader
120    * @return
121    */
122   public Vector<UniprotEntry> getUniprotEntries(Reader fileReader)
123   {
124     UniprotFile uni = new UniprotFile();
125     try
126     {
127       if (map == null)
128       {
129         // 1. Load the mapping information from the file
130         map = new Mapping(uni.getClass().getClassLoader());
131         URL url = getClass().getResource("/uniprot_mapping.xml");
132         map.loadMapping(url);
133       }
134
135       // 2. Unmarshal the data
136       Unmarshaller unmar = new Unmarshaller(uni);
137       unmar.setIgnoreExtraElements(true);
138       unmar.setMapping(map);
139       if (fileReader != null)
140       {
141         uni = (UniprotFile) unmar.unmarshal(fileReader);
142       }
143     } catch (Exception e)
144     {
145       System.out.println("Error getUniprotEntries() " + e);
146     }
147
148     return uni.getUniprotEntries();
149   }
150
151   /*
152    * (non-Javadoc)
153    * 
154    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
155    */
156   @Override
157   public AlignmentI getSequenceRecords(String queries) throws Exception
158   {
159     startQuery();
160     try
161     {
162       queries = queries.toUpperCase().replaceAll(
163               "(UNIPROT\\|?|UNIPROT_|UNIREF\\d+_|UNIREF\\d+\\|?)", "");
164       AlignmentI al = null;
165       EBIFetchClient ebi = new EBIFetchClient();
166       // uniprotxml parameter required since december 2007
167       // uniprotkb dbname changed introduced december 2008
168       File file = ebi.fetchDataAsFile("uniprotkb:" + queries, "uniprotxml",
169               ".xml");
170       Vector<UniprotEntry> entries = getUniprotEntries(new FileReader(file));
171
172       if (entries != null)
173       {
174         ArrayList<SequenceI> seqs = new ArrayList<SequenceI>();
175         for (UniprotEntry entry : entries)
176         {
177           seqs.add(uniprotEntryToSequenceI(entry));
178         }
179         al = new Alignment(seqs.toArray(new SequenceI[0]));
180
181       }
182       stopQuery();
183       return al;
184     } catch (Exception e)
185     {
186       stopQuery();
187       throw (e);
188     }
189   }
190
191   /**
192    * 
193    * @param entry
194    *          UniprotEntry
195    * @return SequenceI instance created from the UniprotEntry instance
196    */
197   public SequenceI uniprotEntryToSequenceI(UniprotEntry entry){
198     String id = getUniprotEntryId(entry);
199     SequenceI sequence = new Sequence(id, entry.getUniprotSequence()
200             .getContent());
201     sequence.setDescription(getUniprotEntryDescription(entry));
202
203     final String dbVersion = getDbVersion();
204     ArrayList<DBRefEntry> dbRefs = new ArrayList<DBRefEntry>();
205     for (String accessionId : entry.getAccession())
206     {
207       DBRefEntry dbRef = new DBRefEntry(DBRefSource.UNIPROT, dbVersion,
208               accessionId);
209
210       // mark dbRef as a primary reference for this sequence
211       dbRefs.add(dbRef);
212     }
213
214     Vector<PDBEntry> onlyPdbEntries = new Vector<PDBEntry>();
215     for (PDBEntry pdb : entry.getDbReference())
216     {
217       DBRefEntry dbr = new DBRefEntry();
218       dbr.setSource(pdb.getType());
219       dbr.setAccessionId(pdb.getId());
220       dbr.setVersion(DBRefSource.UNIPROT + ":" + dbVersion);
221       dbRefs.add(dbr);
222       if ("PDB".equals(pdb.getType()))
223       {
224         onlyPdbEntries.addElement(pdb);
225       }
226       if ("EMBL".equals(pdb.getType()))
227       {
228         // look for a CDS reference and add it, too.
229         String cdsId = (String) pdb.getProperty()
230                 .get("protein sequence ID");
231         if (cdsId != null && cdsId.trim().length() > 0)
232         {
233           dbr = new DBRefEntry(DBRefSource.EMBLCDS, DBRefSource.UNIPROT
234                   + ":"
235                   + dbVersion, cdsId.trim());
236           dbRefs.add(dbr);
237         }
238       }
239     }
240
241     sequence.setPDBId(onlyPdbEntries);
242     if (entry.getFeature() != null)
243     {
244       for (SequenceFeature sf : entry.getFeature())
245       {
246         sf.setFeatureGroup("Uniprot");
247         sequence.addSequenceFeature(sf);
248       }
249     }
250     // we use setDBRefs to assign refs quickly.
251     sequence.setDBRefs(dbRefs.toArray(new DBRefEntry[0]));
252     // need to use ensurePrimaries to reify any refs that should become primary
253     // refs
254     DBRefUtils.ensurePrimaries(sequence); // promote any direct refs to primary
255                                           // source dbs
256     return sequence;
257   }
258
259   /**
260    * 
261    * @param entry
262    *          UniportEntry
263    * @return protein name(s) delimited by a white space character
264    */
265   public static String getUniprotEntryDescription(UniprotEntry entry)
266   {
267     StringBuilder desc = new StringBuilder(32);
268     if (entry.getProtein() != null && entry.getProtein().getName() != null)
269     {
270       boolean first = true;
271       for (String nm : entry.getProtein().getName())
272       {
273         if (!first)
274         {
275           desc.append(" ");
276         }
277         first = false;
278         desc.append(nm);
279       }
280     }
281     return desc.toString();
282   }
283
284   /**
285    *
286    * @param entry
287    *          UniportEntry
288    * @return The accession id(s) and name(s) delimited by '|'.
289    */
290   public static String getUniprotEntryId(UniprotEntry entry)
291   {
292     StringBuilder name = new StringBuilder(32);
293     // name.append("UniProt/Swiss-Prot");
294     // use 'canonicalised' name for optimal id matching
295     name.append(DBRefSource.UNIPROT);
296     for (String accessionId : entry.getAccession())
297     {
298       name.append(BAR_DELIMITER);
299       name.append(accessionId);
300     }
301     for (String n : entry.getName())
302     {
303       name.append(BAR_DELIMITER);
304       name.append(n);
305     }
306     return name.toString();
307   }
308
309   /*
310    * (non-Javadoc)
311    * 
312    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
313    */
314   @Override
315   public boolean isValidReference(String accession)
316   {
317     // TODO: make the following a standard validator
318     return (accession == null || accession.length() < 2) ? false
319             : getAccessionValidator().search(accession);
320   }
321
322   /**
323    * return LDHA_CHICK uniprot entry
324    */
325   @Override
326   public String getTestQuery()
327   {
328     return "P00340";
329   }
330
331   @Override
332   public String getDbName()
333   {
334     return "Uniprot"; // getDbSource();
335   }
336
337   @Override
338   public int getTier()
339   {
340     return 0;
341   }
342 }