Merge branch 'develop' into features/r2_11_2_alphafold/JAL-629
[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.Date;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34
35 import org.json.simple.JSONArray;
36 import org.json.simple.JSONObject;
37 import org.json.simple.parser.ParseException;
38
39 import com.stevesoft.pat.Regex;
40
41 import jalview.api.FeatureSettingsModelI;
42 import jalview.bin.Console;
43 import jalview.datamodel.AlignmentAnnotation;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.ContactMatrixI;
46 import jalview.datamodel.DBRefEntry;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.SequenceFeature;
49 import jalview.datamodel.SequenceI;
50 import jalview.gui.Desktop;
51 import jalview.io.DataSourceType;
52 import jalview.io.FileFormat;
53 import jalview.io.FileFormatI;
54 import jalview.io.FormatAdapter;
55 import jalview.io.PDBFeatureSettings;
56 import jalview.structure.StructureImportSettings.TFType;
57 import jalview.structure.StructureMapping;
58 import jalview.structure.StructureSelectionManager;
59 import jalview.util.MessageManager;
60 import jalview.util.Platform;
61 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
62 import jalview.ws.utils.UrlDownloadClient;
63
64 /**
65  * @author JimP
66  * 
67  */
68 public class EBIAlfaFold extends EbiFileRetrievedProxy
69 {
70   private static final String SEPARATOR = "|";
71
72   private static final String COLON = ":";
73
74   private static final int PDB_ID_LENGTH = 4;
75
76   private static String AF_VERSION = "3";
77
78   public EBIAlfaFold()
79   {
80     super();
81   }
82
83   /*
84    * (non-Javadoc)
85    * 
86    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
87    */
88   @Override
89   public String getAccessionSeparator()
90   {
91     return null;
92   }
93
94   /*
95    * (non-Javadoc)
96    * 
97    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
98    */
99   @Override
100   public Regex getAccessionValidator()
101   {
102     Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
103     validator.setIgnoreCase(true);
104     return validator;
105   }
106
107   /*
108    * (non-Javadoc)
109    * 
110    * @see jalview.ws.DbSourceProxy#getDbSource()
111    */
112   @Override
113   public String getDbSource()
114   {
115     return "ALPHAFOLD";
116   }
117
118   /*
119    * (non-Javadoc)
120    * 
121    * @see jalview.ws.DbSourceProxy#getDbVersion()
122    */
123   @Override
124   public String getDbVersion()
125   {
126     return "1";
127   }
128
129   public static String getAlphaFoldCifDownloadUrl(String id, String vnum)
130   {
131     if (vnum == null || vnum.length() == 0)
132     {
133       vnum = AF_VERSION;
134     }
135     return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v" + vnum
136             + ".cif";
137   }
138
139   public static String getAlphaFoldPaeDownloadUrl(String id, String vnum)
140   {
141     if (vnum == null || vnum.length() == 0)
142     {
143       vnum = AF_VERSION;
144     }
145     return "https://alphafold.ebi.ac.uk/files/" + id
146             + "-predicted_aligned_error_v" + vnum + ".json";
147   }
148
149   /*
150    * (non-Javadoc)
151    * 
152    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
153    */
154   @Override
155   public AlignmentI getSequenceRecords(String queries) throws Exception
156   {
157     return getSequenceRecords(queries, null);
158   }
159
160   public AlignmentI getSequenceRecords(String queries, String retrievalUrl)
161           throws Exception
162   {
163     AlignmentI pdbAlignment = null;
164     String chain = null;
165     String id = null;
166     if (queries.indexOf(COLON) > -1)
167     {
168       chain = queries.substring(queries.indexOf(COLON) + 1);
169       id = queries.substring(0, queries.indexOf(COLON));
170     }
171     else
172     {
173       id = queries;
174     }
175
176     if (!isValidReference(id))
177     {
178       System.err.println(
179               "(AFClient) Ignoring invalid alphafold query: '" + id + "'");
180       stopQuery();
181       return null;
182     }
183     String alphaFoldCif = getAlphaFoldCifDownloadUrl(id, AF_VERSION);
184     if (retrievalUrl != null)
185     {
186       alphaFoldCif = retrievalUrl;
187     }
188
189     try
190     {
191       File tmpFile = File.createTempFile(id, ".cif");
192       Console.debug("Retrieving structure file for " + id + " from "
193               + alphaFoldCif);
194       UrlDownloadClient.download(alphaFoldCif, tmpFile);
195
196       // may not need this check ?
197       file = tmpFile.getAbsolutePath();
198       if (file == null)
199       {
200         return null;
201       }
202       // TODO Get the PAE file somewhere around here and remove from JmolParser
203
204       pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile,
205               id, chain, getDbSource(), getDbVersion());
206
207       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
208       {
209         throw new Exception(MessageManager.formatMessage(
210                 "exception.no_pdb_records_for_chain", new String[]
211                 { id, ((chain == null) ? "' '" : chain) }));
212       }
213       // done during structure retrieval
214       // retrieve_AlphaFold_pAE(id, pdbAlignment, retrievalUrl);
215
216     } catch (Exception ex) // Problem parsing PDB file
217     {
218       stopQuery();
219       throw (ex);
220     }
221     return pdbAlignment;
222   }
223
224   /**
225    * get an alphafold pAE for the given id and return the File object of the
226    * downloaded (temp) file
227    * 
228    * @param id
229    * @param pdbAlignment
230    * @param retrievalUrl
231    *          - URL of .mmcif from EBI-AlphaFold - will be used to generate the
232    *          pAE URL automatically
233    * @throws IOException
234    * @throws Exception
235    */
236   public static File fetchAlphaFoldPAE(String id, String retrievalUrl)
237           throws IOException
238   {
239     // import PAE as contact matrix - assume this will work if there was a
240     // model
241     String paeURL = getAlphaFoldPaeDownloadUrl(id, AF_VERSION);
242
243     if (retrievalUrl != null)
244     {
245       // manufacture the PAE url from a url like ...-model-vN.cif
246       paeURL = retrievalUrl.replace("model", "predicted_aligned_error")
247               .replace(".cif", ".json");
248     }
249
250     // check the cache
251     File pae = paeDownloadCache.get(paeURL);
252     if (pae != null && pae.exists() && (new Date().getTime()
253             - pae.lastModified()) < PAE_CACHE_STALE_TIME)
254     {
255       Console.debug(
256               "Using existing file in PAE cache for '" + paeURL + "'");
257       return pae;
258     }
259
260     try
261     {
262       pae = File.createTempFile(id == null ? "af_pae" : id, "pae_json");
263     } catch (IOException e)
264     {
265       e.printStackTrace();
266     }
267     Console.debug("Downloading pae from " + paeURL + " to " + pae.toString()
268             + "");
269     try
270     {
271       UrlDownloadClient.download(paeURL, pae);
272     } catch (IOException e)
273     {
274       throw e;
275     }
276     // cache and it if successful
277     paeDownloadCache.put(paeURL, pae);
278     return pae;
279   }
280
281   /**
282    * get an alphafold pAE for the given id, and add it to sequence 0 in
283    * pdbAlignment (assuming it came from structurefile parser).
284    * 
285    * @param id
286    * @param pdbAlignment
287    * @param retrievalUrl
288    *          - URL of .mmcif from EBI-AlphaFold - will be used to generate the
289    *          pAE URL automatically
290    * @throws IOException
291    * @throws Exception
292    */
293   public static void retrieve_AlphaFold_pAE(String id,
294           AlignmentI pdbAlignment, String retrievalUrl) throws IOException
295   {
296     File pae = fetchAlphaFoldPAE(id, retrievalUrl);
297     addAlphaFoldPAE(pdbAlignment, pae, 0, null, false, false, null);
298   }
299
300   public static void addAlphaFoldPAE(AlignmentI pdbAlignment, File pae,
301           int index, String id, boolean isStruct, boolean isStructId,
302           String label)
303   {
304     FileInputStream paeInput = null;
305     try
306     {
307       paeInput = new FileInputStream(pae);
308     } catch (FileNotFoundException e)
309     {
310       Console.error(
311               "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
312       return;
313     }
314
315     if (isStruct)
316     {
317       StructureSelectionManager ssm = StructureSelectionManager
318               .getStructureSelectionManager(Desktop.instance);
319       if (ssm != null)
320       {
321         String structFilename = isStructId ? ssm.findFileForPDBId(id) : id;
322         addPAEToStructure(ssm, structFilename, pae, label);
323       }
324
325     }
326     else
327     {
328       // attach to sequence?!
329       try
330       {
331         if (!importPaeJSONAsContactMatrixToSequence(pdbAlignment, paeInput,
332                 index, id, label))
333         {
334           Console.warn("Could not import contact matrix from '"
335                   + pae.getAbsolutePath() + "' to sequence.");
336         }
337       } catch (IOException e1)
338       {
339         Console.error("Error when importing pAE file '"
340                 + pae.getAbsolutePath() + "'", e1);
341       } catch (ParseException e2)
342       {
343         Console.error("Error when parsing pAE file '"
344                 + pae.getAbsolutePath() + "'", e2);
345       }
346     }
347
348   }
349
350   public static void addPAEToStructure(StructureSelectionManager ssm,
351           String structFilename, File pae, String label)
352   {
353     FileInputStream paeInput = null;
354     try
355     {
356       paeInput = new FileInputStream(pae);
357     } catch (FileNotFoundException e)
358     {
359       Console.error(
360               "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
361       return;
362     }
363     if (ssm == null)
364     {
365       ssm = StructureSelectionManager
366               .getStructureSelectionManager(Desktop.instance);
367     }
368     if (ssm != null)
369     {
370       StructureMapping[] smArray = ssm.getMapping(structFilename);
371
372       try
373       {
374         if (!importPaeJSONAsContactMatrixToStructure(smArray, paeInput,
375                 label))
376         {
377           Console.warn("Could not import contact matrix from '"
378                   + pae.getAbsolutePath() + "' to structure.");
379         }
380       } catch (IOException e1)
381       {
382         Console.error("Error when importing pAE file '"
383                 + pae.getAbsolutePath() + "'", e1);
384       } catch (ParseException e2)
385       {
386         Console.error("Error when parsing pAE file '"
387                 + pae.getAbsolutePath() + "'", e2);
388       }
389     }
390   }
391
392   /**
393    * parses the given pAE matrix and adds it to sequence 0 in the given
394    * alignment
395    * 
396    * @param pdbAlignment
397    * @param pae_input
398    * @return true if there was a pAE matrix added
399    * @throws ParseException
400    * @throws IOException
401    * @throws Exception
402    */
403   public static boolean importPaeJSONAsContactMatrixToSequence(
404           AlignmentI pdbAlignment, InputStream pae_input, int index,
405           String seqId, String label) throws IOException, ParseException
406   {
407     SequenceI sequence = null;
408     if (seqId == null)
409     {
410       int seqToGet = index > 0 ? index : 0;
411       sequence = pdbAlignment.getSequenceAt(seqToGet);
412     }
413     if (sequence == null)
414     {
415       SequenceI[] sequences = pdbAlignment.findSequenceMatch(seqId);
416       if (sequences == null || sequences.length < 1)
417       {
418         Console.warn("Could not find sequence with id '" + seqId
419                 + "' to attach pAE matrix to. Ignoring matrix.");
420         return false;
421       }
422       else
423       {
424         sequence = sequences[0]; // just use the first sequence with this seqId
425       }
426     }
427     if (sequence == null)
428     {
429       return false;
430     }
431     return importPaeJSONAsContactMatrixToSequence(pdbAlignment, pae_input,
432             sequence, label);
433   }
434
435   public static boolean importPaeJSONAsContactMatrixToSequence(
436           AlignmentI pdbAlignment, InputStream pae_input,
437           SequenceI sequence, String label)
438           throws IOException, ParseException
439   {
440     JSONObject paeDict = parseJSONtoPAEContactMatrix(pae_input);
441     if (paeDict == null)
442     {
443       Console.debug("JSON file did not parse properly.");
444       return false;
445     }
446     ContactMatrixI matrix = new PAEContactMatrix(sequence,
447             (Map<String, Object>) paeDict);
448     ((PAEContactMatrix) matrix).makeGroups(5f, true);
449
450     AlignmentAnnotation cmannot = sequence.addContactList(matrix);
451     if (label != null)
452       cmannot.label = label;
453     pdbAlignment.addAnnotation(cmannot);
454
455     return true;
456   }
457
458   public static JSONObject parseJSONtoPAEContactMatrix(
459           InputStream pae_input) throws IOException, ParseException
460   {
461     Object paeJson = Platform.parseJSON(pae_input);
462     JSONObject paeDict = null;
463     if (paeJson instanceof JSONObject)
464     {
465       paeDict = (JSONObject) paeJson;
466     }
467     else if (paeJson instanceof JSONArray)
468     {
469       JSONArray jsonArray = (JSONArray) paeJson;
470       if (jsonArray.size() > 0)
471         paeDict = (JSONObject) jsonArray.get(0);
472     }
473
474     return paeDict;
475   }
476
477   public static boolean importPaeJSONAsContactMatrixToStructure(
478           StructureMapping[] smArray, InputStream paeInput, String label)
479           throws IOException, ParseException
480   {
481     boolean someDone = false;
482     for (StructureMapping sm : smArray)
483     {
484       boolean thisDone = importPaeJSONAsContactMatrixToStructure(sm,
485               paeInput, label);
486       someDone |= thisDone;
487     }
488     return someDone;
489   }
490
491   public static boolean importPaeJSONAsContactMatrixToStructure(
492           StructureMapping sm, InputStream paeInput, String label)
493           throws IOException, ParseException
494   {
495     JSONObject pae_obj = parseJSONtoPAEContactMatrix(paeInput);
496     if (pae_obj == null)
497     {
498       Console.debug("JSON file did not parse properly.");
499       return false;
500     }
501
502     SequenceI seq = sm.getSequence();
503     Console.debug("##### SEQUENCE FOUND=" + seq.getName());
504     ContactMatrixI matrix = new PAEContactMatrix(seq,
505             (Map<String, Object>) pae_obj);
506     ((PAEContactMatrix) matrix).makeGroups(5f, true);
507     AlignmentAnnotation cmannot = seq.addContactList(matrix);
508     seq.addAlignmentAnnotation(cmannot);
509     // seq.addAlignmentAnnotation(cmannot);
510
511     return true;
512   }
513
514   /**
515    * general purpose structure importer - designed to yield alignment useful for
516    * transfer of annotation to associated sequences
517    * 
518    * @param alphaFoldCif
519    * @param tmpFile
520    * @param id
521    * @param chain
522    * @param dbSource
523    * @param dbVersion
524    * @return
525    * @throws Exception
526    */
527   public static AlignmentI importDownloadedStructureFromUrl(
528           String alphaFoldCif, File tmpFile, String id, String chain,
529           String dbSource, String dbVersion) throws Exception
530   {
531     String file = tmpFile.getAbsolutePath();
532     // todo get rid of Type and use FileFormatI instead?
533     FileFormatI fileFormat = FileFormat.MMCif;
534     TFType tempfacType = TFType.PLDDT;
535     AlignmentI pdbAlignment = new FormatAdapter().readFile(tmpFile, file,
536             DataSourceType.FILE, fileFormat, tempfacType);
537
538     if (pdbAlignment != null)
539     {
540       List<SequenceI> toremove = new ArrayList<SequenceI>();
541       for (SequenceI pdbcs : pdbAlignment.getSequences())
542       {
543         String chid = null;
544         // Mapping map=null;
545         for (PDBEntry pid : pdbcs.getAllPDBEntries())
546         {
547           if (pid.getFile() == file)
548           {
549             chid = pid.getChainCode();
550           }
551         }
552         if (chain == null || (chid != null && (chid.equals(chain)
553                 || chid.trim().equals(chain.trim())
554                 || (chain.trim().length() == 0 && chid.equals("_")))))
555         {
556           // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
557           // TODO: suggest simplify naming to 1qip|A as default name defined
558           pdbcs.setName(id + SEPARATOR + pdbcs.getName());
559           // Might need to add more metadata to the PDBEntry object
560           // like below
561           /*
562            * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
563            * entry.setId(id); if (entry.getProperty() == null)
564            * entry.setProperty(new Hashtable());
565            * entry.getProperty().put("chains", pdbchain.id + "=" +
566            * sq.getStart() + "-" + sq.getEnd());
567            * sq.getDatasetSequence().addPDBId(entry);
568            */
569           // Add PDB DB Refs
570           // We make a DBRefEtntry because we have obtained the PDB file from
571           // a
572           // verifiable source
573           // JBPNote - PDB DBRefEntry should also carry the chain and mapping
574           // information
575           if (dbSource != null)
576           {
577             DBRefEntry dbentry = new DBRefEntry(dbSource,
578
579                     dbVersion, (chid == null ? id : id + chid));
580             // dbentry.setMap()
581             pdbcs.addDBRef(dbentry);
582             // update any feature groups
583             List<SequenceFeature> allsf = pdbcs.getFeatures()
584                     .getAllFeatures();
585             List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
586             if (allsf != null && allsf.size() > 0)
587             {
588               for (SequenceFeature f : allsf)
589               {
590                 if (file.equals(f.getFeatureGroup()))
591                 {
592                   f = new SequenceFeature(f, f.type, f.begin, f.end, id,
593                           f.score);
594                 }
595                 newsf.add(f);
596               }
597               pdbcs.setSequenceFeatures(newsf);
598             }
599           }
600         }
601         else
602         {
603           // mark this sequence to be removed from the alignment
604           // - since it's not from the right chain
605           toremove.add(pdbcs);
606         }
607       }
608       // now remove marked sequences
609       for (SequenceI pdbcs : toremove)
610       {
611         pdbAlignment.deleteSequence(pdbcs);
612         if (pdbcs.getAnnotation() != null)
613         {
614           for (AlignmentAnnotation aa : pdbcs.getAnnotation())
615           {
616             pdbAlignment.deleteAnnotation(aa);
617           }
618         }
619       }
620     }
621     return pdbAlignment;
622   }
623
624   /*
625    * (non-Javadoc)
626    * 
627    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
628    */
629   @Override
630   public boolean isValidReference(String accession)
631   {
632     Regex r = getAccessionValidator();
633     return r.search(accession.trim());
634   }
635
636   /**
637    * human glyoxalase
638    */
639   @Override
640   public String getTestQuery()
641   {
642     return "AF-O15552-F1";
643   }
644
645   @Override
646   public String getDbName()
647   {
648     return "ALPHAFOLD"; // getDbSource();
649   }
650
651   @Override
652   public int getTier()
653   {
654     return 0;
655   }
656
657   /**
658    * Returns a descriptor for suitable feature display settings with
659    * <ul>
660    * <li>ResNums or insertions features visible</li>
661    * <li>insertions features coloured red</li>
662    * <li>ResNum features coloured by label</li>
663    * <li>Insertions displayed above (on top of) ResNums</li>
664    * </ul>
665    */
666   @Override
667   public FeatureSettingsModelI getFeatureColourScheme()
668   {
669     return new PDBFeatureSettings();
670   }
671
672   // days * 86400000
673   private static final long PAE_CACHE_STALE_TIME = 1 * 86400000;
674
675   private static Map<String, File> paeDownloadCache = new HashMap<>();
676
677 }