JAL-3855 update EBI Alphafold barcoded URL generation to v2.cif/json URLs
[jalview.git] / src / jalview / ws / dbsources / EBIAlfaFold.java
1
2 /*
3  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
4  * Copyright (C) $$Year-Rel$$ The Jalview Authors
5  * 
6  * This file is part of Jalview.
7  * 
8  * Jalview is free software: you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License 
10  * as published by the Free Software Foundation, either version 3
11  * of the License, or (at your option) any later version.
12  *  
13  * Jalview is distributed in the hope that it will be useful, but 
14  * WITHOUT ANY WARRANTY; without even the implied warranty 
15  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
16  * PURPOSE.  See the GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
20  * The Jalview Authors are detailed in the 'AUTHORS' file.
21  */
22 package jalview.ws.dbsources;
23
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.bin.Cache;
26 import jalview.bin.Console;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ContactMatrix;
30 import jalview.datamodel.ContactMatrixI;
31 import jalview.datamodel.DBRefEntry;
32 import jalview.datamodel.DBRefSource;
33 import jalview.datamodel.PDBEntry;
34 import jalview.datamodel.PDBEntry.Type;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceI;
37 import jalview.datamodel.features.SequenceFeaturesI;
38 import jalview.io.DataSourceType;
39 import jalview.io.FileFormat;
40 import jalview.io.FileFormatI;
41 import jalview.io.FormatAdapter;
42 import jalview.io.PDBFeatureSettings;
43 import jalview.javascript.json.JSON;
44 import jalview.structure.StructureImportSettings;
45 import jalview.util.HttpUtils;
46 import jalview.util.MessageManager;
47 import jalview.util.Platform;
48 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
49 import jalview.ws.ebi.EBIFetchClient;
50 import jalview.ws.utils.UrlDownloadClient;
51
52 import java.io.BufferedReader;
53 import java.io.File;
54 import java.io.FileInputStream;
55 import java.util.ArrayList;
56 import java.util.List;
57 import java.util.Map;
58
59 import org.jmol.adapter.readers.simple.JSONReader;
60
61 import com.stevesoft.pat.Regex;
62
63 /**
64  * @author JimP
65  * 
66  */
67 public class EBIAlfaFold extends EbiFileRetrievedProxy
68 {
69   private static final String SEPARATOR = "|";
70
71   private static final String COLON = ":";
72
73   private static final int PDB_ID_LENGTH = 4;
74
75   private static String AF_VERSION = "2";
76
77   public EBIAlfaFold()
78   {
79     super();
80   }
81
82   /*
83    * (non-Javadoc)
84    * 
85    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
86    */
87   @Override
88   public String getAccessionSeparator()
89   {
90     return null;
91   }
92
93   /*
94    * (non-Javadoc)
95    * 
96    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
97    */
98   @Override
99   public Regex getAccessionValidator()
100   {
101     Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
102     validator.setIgnoreCase(true);
103     return validator;
104   }
105
106   /*
107    * (non-Javadoc)
108    * 
109    * @see jalview.ws.DbSourceProxy#getDbSource()
110    */
111   @Override
112   public String getDbSource()
113   {
114     return "ALPHAFOLD";
115   }
116
117   /*
118    * (non-Javadoc)
119    * 
120    * @see jalview.ws.DbSourceProxy#getDbVersion()
121    */
122   @Override
123   public String getDbVersion()
124   {
125     return "1";
126   }
127
128   public static String getAlphaFoldCifDownloadUrl(String id, String vnum)
129   {
130     if (vnum == null || vnum.length() == 0)
131     {
132       vnum = AF_VERSION;
133     }
134     return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v" + vnum
135             + ".cif";
136   }
137
138   public static String getAlphaFoldPaeDownloadUrl(String id, String vnum)
139   {
140     if (vnum == null || vnum.length() == 0)
141     {
142       vnum = AF_VERSION;
143     }
144     return "https://alphafold.ebi.ac.uk/files/" + id
145             + "-predicted_aligned_error_v" + vnum + ".json";
146   }
147
148   /*
149    * (non-Javadoc)
150    * 
151    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
152    */
153   @Override
154   public AlignmentI getSequenceRecords(String queries) throws Exception
155   {
156     return getSequenceRecords(queries, null);
157   }
158
159   public AlignmentI getSequenceRecords(String queries, String retrievalUrl)
160           throws Exception
161   {
162     AlignmentI pdbAlignment = null;
163     String chain = null;
164     String id = null;
165     if (queries.indexOf(COLON) > -1)
166     {
167       chain = queries.substring(queries.indexOf(COLON) + 1);
168       id = queries.substring(0, queries.indexOf(COLON));
169     }
170     else
171     {
172       id = queries;
173     }
174
175     if (!isValidReference(id))
176     {
177       System.err.println(
178               "(AFClient) Ignoring invalid alphafold query: '" + id + "'");
179       stopQuery();
180       return null;
181     }
182     String alphaFoldCif = getAlphaFoldCifDownloadUrl(id, AF_VERSION);
183     if (retrievalUrl != null)
184     {
185       alphaFoldCif = retrievalUrl;
186     }
187
188     try
189     {
190       File tmpFile = File.createTempFile(id, ".cif");
191       Console.debug("Retrieving structure file for "+id+" from "+alphaFoldCif);
192       UrlDownloadClient.download(alphaFoldCif, tmpFile);
193
194       // may not need this check ?
195       file = tmpFile.getAbsolutePath();
196       if (file == null)
197       {
198         return null;
199       }
200
201       pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile,
202               id, chain, getDbSource(), getDbVersion());
203
204       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
205       {
206         throw new Exception(MessageManager.formatMessage(
207                 "exception.no_pdb_records_for_chain", new String[]
208                 { id, ((chain == null) ? "' '" : chain) }));
209       }
210
211       // import PAE as contact matrix - assume this will work if there was a
212       // model
213       File pae = File.createTempFile(id, "pae_json");
214       String paeURL = getAlphaFoldPaeDownloadUrl(id, AF_VERSION);
215
216       if (retrievalUrl != null)
217       {
218         // manufacture the PAE url from a url like ...-model-vN.cif
219         paeURL = retrievalUrl.replace("model","predicted_aligned_error").replace(".cif",".json");
220       }
221       Console.debug("Downloading pae from " + paeURL
222               + " to " + pae.toString() + "");
223
224       try {
225         UrlDownloadClient.download(paeURL, pae);        
226       if (!importPaeJSONAsContactMatrix(pdbAlignment, pae))
227       {
228         Console.warn("Couln't import contact matrix from " + paeURL
229                 + " (stored in " + pae.toString() + ")");
230       }
231       } catch (Exception pae_ex) {
232         Console.debug("Couldn't download PAE",pae_ex);
233       }
234
235     } catch (Exception ex) // Problem parsing PDB file
236     {
237       stopQuery();
238       throw (ex);
239     }
240     return pdbAlignment;
241   }
242
243   private boolean importPaeJSONAsContactMatrix(AlignmentI pdbAlignment,
244           File pae) throws Exception
245   {
246     FileInputStream pae_input = new FileInputStream(pae);
247
248     List<Object> pae_obj = (List<Object>) Platform
249             .parseJSON(pae_input);
250     if (pae_obj == null)
251     {
252       return false;
253     }
254     ContactMatrixI matrix = new PAEContactMatrix(
255             pdbAlignment.getSequenceAt(0), (Map<String, Object>)pae_obj.get(0));
256
257     pdbAlignment.getSequenceAt(0).addAlignmentAnnotation(pdbAlignment.addContactList(matrix));
258     return true;
259   }
260
261   /**
262    * general purpose structure importer - designed to yield alignment useful for
263    * transfer of annotation to associated sequences
264    * 
265    * @param alphaFoldCif
266    * @param tmpFile
267    * @param id
268    * @param chain
269    * @param dbSource
270    * @param dbVersion
271    * @return
272    * @throws Exception
273    */
274   public static AlignmentI importDownloadedStructureFromUrl(
275           String alphaFoldCif, File tmpFile, String id, String chain,
276           String dbSource, String dbVersion) throws Exception
277   {
278     String file = tmpFile.getAbsolutePath();
279     // todo get rid of Type and use FileFormatI instead?
280     FileFormatI fileFormat = FileFormat.MMCif;
281     AlignmentI pdbAlignment = new FormatAdapter().readFile(tmpFile,
282             DataSourceType.FILE, fileFormat);
283     if (pdbAlignment != null)
284     {
285       List<SequenceI> toremove = new ArrayList<SequenceI>();
286       for (SequenceI pdbcs : pdbAlignment.getSequences())
287       {
288         String chid = null;
289         // Mapping map=null;
290         for (PDBEntry pid : pdbcs.getAllPDBEntries())
291         {
292           if (pid.getFile() == file)
293           {
294             chid = pid.getChainCode();
295
296           }
297         }
298         if (chain == null || (chid != null && (chid.equals(chain)
299                 || chid.trim().equals(chain.trim())
300                 || (chain.trim().length() == 0 && chid.equals("_")))))
301         {
302           // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
303           // TODO: suggest simplify naming to 1qip|A as default name defined
304           pdbcs.setName(id + SEPARATOR + pdbcs.getName());
305           // Might need to add more metadata to the PDBEntry object
306           // like below
307           /*
308            * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
309            * entry.setId(id); if (entry.getProperty() == null)
310            * entry.setProperty(new Hashtable());
311            * entry.getProperty().put("chains", pdbchain.id + "=" +
312            * sq.getStart() + "-" + sq.getEnd());
313            * sq.getDatasetSequence().addPDBId(entry);
314            */
315           // Add PDB DB Refs
316           // We make a DBRefEtntry because we have obtained the PDB file from
317           // a
318           // verifiable source
319           // JBPNote - PDB DBRefEntry should also carry the chain and mapping
320           // information
321           if (dbSource != null)
322           {
323             DBRefEntry dbentry = new DBRefEntry(dbSource,
324
325                     dbVersion, (chid == null ? id : id + chid));
326             // dbentry.setMap()
327             pdbcs.addDBRef(dbentry);
328             // update any feature groups
329             List<SequenceFeature> allsf = pdbcs.getFeatures()
330                     .getAllFeatures();
331             List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
332             if (allsf != null && allsf.size() > 0)
333             {
334               for (SequenceFeature f : allsf)
335               {
336                 if (file.equals(f.getFeatureGroup()))
337                 {
338                   f = new SequenceFeature(f, f.type, f.begin, f.end, id,
339                           f.score);
340                 }
341                 newsf.add(f);
342               }
343               pdbcs.setSequenceFeatures(newsf);
344             }
345           }
346         }
347         else
348         {
349           // mark this sequence to be removed from the alignment
350           // - since it's not from the right chain
351           toremove.add(pdbcs);
352         }
353       }
354       // now remove marked sequences
355       for (SequenceI pdbcs : toremove)
356       {
357         pdbAlignment.deleteSequence(pdbcs);
358         if (pdbcs.getAnnotation() != null)
359         {
360           for (AlignmentAnnotation aa : pdbcs.getAnnotation())
361           {
362             pdbAlignment.deleteAnnotation(aa);
363           }
364         }
365       }
366     }
367     return pdbAlignment;
368   }
369
370   /*
371    * (non-Javadoc)
372    * 
373    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
374    */
375   @Override
376   public boolean isValidReference(String accession)
377   {
378     Regex r = getAccessionValidator();
379     return r.search(accession.trim());
380   }
381
382   /**
383    * human glyoxalase
384    */
385   @Override
386   public String getTestQuery()
387   {
388     return "AF-O15552-F1";
389   }
390
391   @Override
392   public String getDbName()
393   {
394     return "ALPHAFOLD"; // getDbSource();
395   }
396
397   @Override
398   public int getTier()
399   {
400     return 0;
401   }
402
403   /**
404    * Returns a descriptor for suitable feature display settings with
405    * <ul>
406    * <li>ResNums or insertions features visible</li>
407    * <li>insertions features coloured red</li>
408    * <li>ResNum features coloured by label</li>
409    * <li>Insertions displayed above (on top of) ResNums</li>
410    * </ul>
411    */
412   @Override
413   public FeatureSettingsModelI getFeatureColourScheme()
414   {
415     return new PDBFeatureSettings();
416   }
417
418 }