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