Merge branch 'features/r2_11_2_alphafold/JAL-2349_JAL-3855' into develop
[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   public EBIAlfaFold()
76   {
77     super();
78   }
79
80   /*
81    * (non-Javadoc)
82    * 
83    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
84    */
85   @Override
86   public String getAccessionSeparator()
87   {
88     return null;
89   }
90
91   /*
92    * (non-Javadoc)
93    * 
94    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
95    */
96   @Override
97   public Regex getAccessionValidator()
98   {
99     Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
100     validator.setIgnoreCase(true);
101     return validator;
102   }
103
104   /*
105    * (non-Javadoc)
106    * 
107    * @see jalview.ws.DbSourceProxy#getDbSource()
108    */
109   @Override
110   public String getDbSource()
111   {
112     return "ALPHAFOLD";
113   }
114
115   /*
116    * (non-Javadoc)
117    * 
118    * @see jalview.ws.DbSourceProxy#getDbVersion()
119    */
120   @Override
121   public String getDbVersion()
122   {
123     return "1";
124   }
125
126   public static String getAlphaFoldCifDownloadUrl(String id)
127   {
128     return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v1.cif";
129   }
130
131   public static String getAlphaFoldPaeDownloadUrl(String id)
132   {
133     return "https://alphafold.ebi.ac.uk/files/" + id
134             + "-predicted_aligned_error_v1.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);
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 "+alphaFoldCif);
181       UrlDownloadClient.download(alphaFoldCif, tmpFile);
182
183       // may not need this check ?
184       file = tmpFile.getAbsolutePath();
185       if (file == null)
186       {
187         return null;
188       }
189
190       pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile,
191               id, chain, getDbSource(), getDbVersion());
192
193       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
194       {
195         throw new Exception(MessageManager.formatMessage(
196                 "exception.no_pdb_records_for_chain", new String[]
197                 { id, ((chain == null) ? "' '" : chain) }));
198       }
199
200       // import PAE as contact matrix - assume this will work if there was a
201       // model
202       File pae = File.createTempFile(id, "pae_json");
203       String paeURL = getAlphaFoldPaeDownloadUrl(id);
204       
205       if (retrievalUrl!=null) {
206         // manufacture the PAE url from a url like ...-model-vN.cif
207         paeURL = retrievalUrl.replace("model","predicted_aligned_error").replace(".cif",".json");
208       }
209       Console.debug("Downloading pae from " + paeURL
210               + " to " + pae.toString() + "");
211
212       try {
213         UrlDownloadClient.download(paeURL, pae);        
214       if (!importPaeJSONAsContactMatrix(pdbAlignment, pae))
215       {
216         Console.warn("Couln't import contact matrix from " + paeURL
217                 + " (stored in " + pae.toString() + ")");
218       }
219       } catch (Exception pae_ex) {
220         Console.debug("Couldn't download PAE",pae_ex);
221       }
222
223     } catch (Exception ex) // Problem parsing PDB file
224     {
225       stopQuery();
226       throw (ex);
227     }
228     return pdbAlignment;
229   }
230
231   private boolean importPaeJSONAsContactMatrix(AlignmentI pdbAlignment,
232           File pae) throws Exception
233   {
234     FileInputStream pae_input = new FileInputStream(pae);
235
236     List<Object> pae_obj = (List<Object>) Platform
237             .parseJSON(pae_input);
238     if (pae_obj == null)
239     {
240       return false;
241     }
242     ContactMatrixI matrix = new PAEContactMatrix(
243             pdbAlignment.getSequenceAt(0), (Map<String, Object>)pae_obj.get(0));
244
245     pdbAlignment.getSequenceAt(0).addAlignmentAnnotation(pdbAlignment.addContactList(matrix));
246     return true;
247   }
248
249   /**
250    * general purpose structure importer - designed to yield alignment useful for
251    * transfer of annotation to associated sequences
252    * 
253    * @param alphaFoldCif
254    * @param tmpFile
255    * @param id
256    * @param chain
257    * @param dbSource
258    * @param dbVersion
259    * @return
260    * @throws Exception
261    */
262   public static AlignmentI importDownloadedStructureFromUrl(
263           String alphaFoldCif, File tmpFile, String id, String chain,
264           String dbSource, String dbVersion) throws Exception
265   {
266     String file = tmpFile.getAbsolutePath();
267     // todo get rid of Type and use FileFormatI instead?
268     FileFormatI fileFormat = FileFormat.MMCif;
269     AlignmentI pdbAlignment = new FormatAdapter().readFile(tmpFile,
270             DataSourceType.FILE, fileFormat);
271     if (pdbAlignment != null)
272     {
273       List<SequenceI> toremove = new ArrayList<SequenceI>();
274       for (SequenceI pdbcs : pdbAlignment.getSequences())
275       {
276         String chid = null;
277         // Mapping map=null;
278         for (PDBEntry pid : pdbcs.getAllPDBEntries())
279         {
280           if (pid.getFile() == file)
281           {
282             chid = pid.getChainCode();
283
284           }
285         }
286         if (chain == null || (chid != null && (chid.equals(chain)
287                 || chid.trim().equals(chain.trim())
288                 || (chain.trim().length() == 0 && chid.equals("_")))))
289         {
290           // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
291           // TODO: suggest simplify naming to 1qip|A as default name defined
292           pdbcs.setName(id + SEPARATOR + pdbcs.getName());
293           // Might need to add more metadata to the PDBEntry object
294           // like below
295           /*
296            * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
297            * entry.setId(id); if (entry.getProperty() == null)
298            * entry.setProperty(new Hashtable());
299            * entry.getProperty().put("chains", pdbchain.id + "=" +
300            * sq.getStart() + "-" + sq.getEnd());
301            * sq.getDatasetSequence().addPDBId(entry);
302            */
303           // Add PDB DB Refs
304           // We make a DBRefEtntry because we have obtained the PDB file from
305           // a
306           // verifiable source
307           // JBPNote - PDB DBRefEntry should also carry the chain and mapping
308           // information
309           if (dbSource != null)
310           {
311             DBRefEntry dbentry = new DBRefEntry(dbSource,
312
313                     dbVersion, (chid == null ? id : id + chid));
314             // dbentry.setMap()
315             pdbcs.addDBRef(dbentry);
316             // update any feature groups
317             List<SequenceFeature> allsf = pdbcs.getFeatures()
318                     .getAllFeatures();
319             List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
320             if (allsf != null && allsf.size() > 0)
321             {
322               for (SequenceFeature f : allsf)
323               {
324                 if (file.equals(f.getFeatureGroup()))
325                 {
326                   f = new SequenceFeature(f, f.type, f.begin, f.end, id,
327                           f.score);
328                 }
329                 newsf.add(f);
330               }
331               pdbcs.setSequenceFeatures(newsf);
332             }
333           }
334         }
335         else
336         {
337           // mark this sequence to be removed from the alignment
338           // - since it's not from the right chain
339           toremove.add(pdbcs);
340         }
341       }
342       // now remove marked sequences
343       for (SequenceI pdbcs : toremove)
344       {
345         pdbAlignment.deleteSequence(pdbcs);
346         if (pdbcs.getAnnotation() != null)
347         {
348           for (AlignmentAnnotation aa : pdbcs.getAnnotation())
349           {
350             pdbAlignment.deleteAnnotation(aa);
351           }
352         }
353       }
354     }
355     return pdbAlignment;
356   }
357
358   /*
359    * (non-Javadoc)
360    * 
361    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
362    */
363   @Override
364   public boolean isValidReference(String accession)
365   {
366     Regex r = getAccessionValidator();
367     return r.search(accession.trim());
368   }
369
370   /**
371    * human glyoxalase
372    */
373   @Override
374   public String getTestQuery()
375   {
376     return "AF-O15552-F1";
377   }
378
379   @Override
380   public String getDbName()
381   {
382     return "ALPHAFOLD"; // getDbSource();
383   }
384
385   @Override
386   public int getTier()
387   {
388     return 0;
389   }
390
391   /**
392    * Returns a descriptor for suitable feature display settings with
393    * <ul>
394    * <li>ResNums or insertions features visible</li>
395    * <li>insertions features coloured red</li>
396    * <li>ResNum features coloured by label</li>
397    * <li>Insertions displayed above (on top of) ResNums</li>
398    * </ul>
399    */
400   @Override
401   public FeatureSettingsModelI getFeatureColourScheme()
402   {
403     return new PDBFeatureSettings();
404   }
405
406 }