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