JAL-3855 JAL-2349 download PAE matrix along with alpha fold structure from EBI and...
[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.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ContactMatrix;
29 import jalview.datamodel.ContactMatrixI;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.DBRefSource;
32 import jalview.datamodel.PDBEntry;
33 import jalview.datamodel.PDBEntry.Type;
34 import jalview.datamodel.SequenceI;
35 import jalview.io.DataSourceType;
36 import jalview.io.FileFormat;
37 import jalview.io.FileFormatI;
38 import jalview.io.FormatAdapter;
39 import jalview.io.PDBFeatureSettings;
40 import jalview.javascript.json.JSON;
41 import jalview.structure.StructureImportSettings;
42 import jalview.util.HttpUtils;
43 import jalview.util.MessageManager;
44 import jalview.util.Platform;
45 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
46 import jalview.ws.ebi.EBIFetchClient;
47 import jalview.ws.utils.UrlDownloadClient;
48
49 import java.io.BufferedReader;
50 import java.io.File;
51 import java.io.FileInputStream;
52 import java.util.ArrayList;
53 import java.util.List;
54 import java.util.Map;
55
56 import org.jmol.adapter.readers.simple.JSONReader;
57
58 import com.stevesoft.pat.Regex;
59
60 /**
61  * @author JimP
62  * 
63  */
64 public class EBIAlfaFold extends EbiFileRetrievedProxy
65 {
66   private static final String SEPARATOR = "|";
67
68   private static final String COLON = ":";
69
70   private static final int PDB_ID_LENGTH = 4;
71
72   public EBIAlfaFold()
73   {
74     super();
75   }
76
77   /*
78    * (non-Javadoc)
79    * 
80    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
81    */
82   @Override
83   public String getAccessionSeparator()
84   {
85     return null;
86   }
87
88   /*
89    * (non-Javadoc)
90    * 
91    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
92    */
93   @Override
94   public Regex getAccessionValidator()
95   {
96     return new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
97   }
98
99   /*
100    * (non-Javadoc)
101    * 
102    * @see jalview.ws.DbSourceProxy#getDbSource()
103    */
104   @Override
105   public String getDbSource()
106   {
107     return "ALPHAFOLD";
108   }
109
110   /*
111    * (non-Javadoc)
112    * 
113    * @see jalview.ws.DbSourceProxy#getDbVersion()
114    */
115   @Override
116   public String getDbVersion()
117   {
118     return "1";
119   }
120
121   public static String getAlphaFoldCifDownloadUrl(String id)
122   {
123     return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v1.cif";
124   }
125
126   public static String getAlphaFoldPaeDownloadUrl(String id)
127   {
128     return "https://alphafold.ebi.ac.uk/files/" + id
129             + "-predicted_aligned_error_v1.json";
130   }
131
132   /*
133    * (non-Javadoc)
134    * 
135    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
136    */
137   @Override
138   public AlignmentI getSequenceRecords(String queries) throws Exception
139   {
140     AlignmentI pdbAlignment = null;
141     String chain = null;
142     String id = null;
143     if (queries.indexOf(COLON) > -1)
144     {
145       chain = queries.substring(queries.indexOf(COLON) + 1);
146       id = queries.substring(0, queries.indexOf(COLON));
147     }
148     else
149     {
150       id = queries;
151     }
152
153     if (!isValidReference(id))
154     {
155       System.err.println(
156               "(AFClient) Ignoring invalid alphafold query: '" + id + "'");
157       stopQuery();
158       return null;
159     }
160     String alphaFoldCif = getAlphaFoldCifDownloadUrl(id);
161
162     try
163     {
164       File tmpFile = File.createTempFile(id, "cif");
165       UrlDownloadClient.download(alphaFoldCif, tmpFile);
166       file = tmpFile.getAbsolutePath();
167       if (file == null)
168       {
169         return null;
170       }
171
172       // todo get rid of Type and use FileFormatI instead?
173       FileFormatI fileFormat = FileFormat.MMCif;
174       pdbAlignment = new FormatAdapter().readFile(tmpFile,
175               DataSourceType.FILE, fileFormat);
176       if (pdbAlignment != null)
177       {
178         List<SequenceI> toremove = new ArrayList<SequenceI>();
179         for (SequenceI pdbcs : pdbAlignment.getSequences())
180         {
181           String chid = null;
182           // Mapping map=null;
183           for (PDBEntry pid : pdbcs.getAllPDBEntries())
184           {
185             if (pid.getFile() == file)
186             {
187               chid = pid.getChainCode();
188
189             }
190           }
191           if (chain == null || (chid != null && (chid.equals(chain)
192                   || chid.trim().equals(chain.trim())
193                   || (chain.trim().length() == 0 && chid.equals("_")))))
194           {
195             // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
196             // TODO: suggest simplify naming to 1qip|A as default name defined
197             pdbcs.setName(id + SEPARATOR + pdbcs.getName());
198             // Might need to add more metadata to the PDBEntry object
199             // like below
200             /*
201              * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
202              * entry.setId(id); if (entry.getProperty() == null)
203              * entry.setProperty(new Hashtable());
204              * entry.getProperty().put("chains", pdbchain.id + "=" +
205              * sq.getStart() + "-" + sq.getEnd());
206              * sq.getDatasetSequence().addPDBId(entry);
207              */
208             // Add PDB DB Refs
209             // We make a DBRefEtntry because we have obtained the PDB file from
210             // a
211             // verifiable source
212             // JBPNote - PDB DBRefEntry should also carry the chain and mapping
213             // information
214             DBRefEntry dbentry = new DBRefEntry(getDbSource(),
215                     getDbVersion(), (chid == null ? id : id + chid));
216             // dbentry.setMap()
217             pdbcs.addDBRef(dbentry);
218           }
219           else
220           {
221             // mark this sequence to be removed from the alignment
222             // - since it's not from the right chain
223             toremove.add(pdbcs);
224           }
225         }
226         // now remove marked sequences
227         for (SequenceI pdbcs : toremove)
228         {
229           pdbAlignment.deleteSequence(pdbcs);
230           if (pdbcs.getAnnotation() != null)
231           {
232             for (AlignmentAnnotation aa : pdbcs.getAnnotation())
233             {
234               pdbAlignment.deleteAnnotation(aa);
235             }
236           }
237         }
238       }
239
240       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
241       {
242         throw new Exception(MessageManager.formatMessage(
243                 "exception.no_pdb_records_for_chain", new String[]
244                 { id, ((chain == null) ? "' '" : chain) }));
245       }
246
247       // import PAE as contact matrix - assume this will work if there was a
248       // model
249       File pae = File.createTempFile(id, "pae_json");
250       String paeURL = getAlphaFoldPaeDownloadUrl(id);
251       UrlDownloadClient.download(paeURL, pae);
252       if (!importPaeJSONAsContactMatrix(pdbAlignment, pae))
253       {
254         Cache.log.debug("Couln't import contact matrix from " + paeURL
255                 + " (stored in " + pae.toString() + ")");
256       }
257
258     } catch (Exception ex) // Problem parsing PDB file
259     {
260       stopQuery();
261       throw (ex);
262     }
263     return pdbAlignment;
264   }
265
266   private boolean importPaeJSONAsContactMatrix(AlignmentI pdbAlignment,
267           File pae) throws Exception
268   {
269     FileInputStream pae_input = new FileInputStream(pae);
270
271     List<Object> pae_obj = (List<Object>) Platform
272             .parseJSON(pae_input);
273     if (pae_obj == null)
274     {
275       return false;
276     }
277     ContactMatrixI matrix = new PAEContactMatrix(
278             pdbAlignment.getSequenceAt(0), (Map<String, Object>)pae_obj.get(0));
279
280     pdbAlignment.getSequenceAt(0).addAlignmentAnnotation(pdbAlignment.addContactList(matrix));
281     return true;
282   }
283
284   /*
285    * (non-Javadoc)
286    * 
287    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
288    */
289   @Override
290   public boolean isValidReference(String accession)
291   {
292     Regex r = getAccessionValidator();
293     return r.search(accession.trim());
294   }
295
296   /**
297    * human glyoxalase
298    */
299   @Override
300   public String getTestQuery()
301   {
302     return "AF-O15552-F1";
303   }
304
305   @Override
306   public String getDbName()
307   {
308     return "ALPHAFOLD"; // getDbSource();
309   }
310
311   @Override
312   public int getTier()
313   {
314     return 0;
315   }
316
317   /**
318    * Returns a descriptor for suitable feature display settings with
319    * <ul>
320    * <li>ResNums or insertions features visible</li>
321    * <li>insertions features coloured red</li>
322    * <li>ResNum features coloured by label</li>
323    * <li>Insertions displayed above (on top of) ResNums</li>
324    * </ul>
325    */
326   @Override
327   public FeatureSettingsModelI getFeatureColourScheme()
328   {
329     return new PDBFeatureSettings();
330   }
331 }