JAL-629 Some refactoring to allow more flexible use of PAE files. Not working as...
[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.AlignedCodonFrame;
44 import jalview.datamodel.AlignmentAnnotation;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.ContactMatrixI;
47 import jalview.datamodel.DBRefEntry;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceFeature;
50 import jalview.datamodel.SequenceI;
51 import jalview.gui.Desktop;
52 import jalview.io.DataSourceType;
53 import jalview.io.FileFormat;
54 import jalview.io.FileFormatI;
55 import jalview.io.FormatAdapter;
56 import jalview.io.PDBFeatureSettings;
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
203       pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile,
204               id, chain, getDbSource(), getDbVersion());
205
206       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
207       {
208         throw new Exception(MessageManager.formatMessage(
209                 "exception.no_pdb_records_for_chain", new String[]
210                 { id, ((chain == null) ? "' '" : chain) }));
211       }
212       // done during structure retrieval
213       // retrieve_AlphaFold_pAE(id, pdbAlignment, retrievalUrl);
214
215     } catch (Exception ex) // Problem parsing PDB file
216     {
217       stopQuery();
218       throw (ex);
219     }
220     return pdbAlignment;
221   }
222
223   /**
224    * get an alphafold pAE for the given id and return the File object of the
225    * downloaded (temp) file
226    * 
227    * @param id
228    * @param pdbAlignment
229    * @param retrievalUrl
230    *          - URL of .mmcif from EBI-AlphaFold - will be used to generate the
231    *          pAE URL automatically
232    * @throws IOException
233    * @throws Exception
234    */
235   public static File fetchAlphaFoldPAE(String id, String retrievalUrl)
236           throws IOException
237   {
238     // import PAE as contact matrix - assume this will work if there was a
239     // model
240     String paeURL = getAlphaFoldPaeDownloadUrl(id, AF_VERSION);
241
242     if (retrievalUrl != null)
243     {
244       // manufacture the PAE url from a url like ...-model-vN.cif
245       paeURL = retrievalUrl.replace("model", "predicted_aligned_error")
246               .replace(".cif", ".json");
247     }
248
249     // check the cache
250     File pae = paeDownloadCache.get(paeURL);
251     if (pae != null && pae.exists() && (new Date().getTime()
252             - pae.lastModified()) < PAE_CACHE_STALE_TIME)
253     {
254       Console.debug(
255               "Using existing file in PAE cache for '" + paeURL + "'");
256       return pae;
257     }
258
259     try
260     {
261       pae = File.createTempFile(id == null ? "af_pae" : id, "pae_json");
262     } catch (IOException e)
263     {
264       e.printStackTrace();
265     }
266     Console.debug("Downloading pae from " + paeURL + " to " + pae.toString()
267             + "");
268     try
269     {
270       UrlDownloadClient.download(paeURL, pae);
271     } catch (IOException e)
272     {
273       throw e;
274     }
275     // cache and it if successful
276     paeDownloadCache.put(paeURL, pae);
277     return pae;
278   }
279
280   /**
281    * get an alphafold pAE for the given id, and add it to sequence 0 in
282    * pdbAlignment (assuming it came from structurefile parser).
283    * 
284    * @param id
285    * @param pdbAlignment
286    * @param retrievalUrl
287    *          - URL of .mmcif from EBI-AlphaFold - will be used to generate the
288    *          pAE URL automatically
289    * @throws IOException
290    * @throws Exception
291    */
292   public static void retrieve_AlphaFold_pAE(String id,
293           AlignmentI pdbAlignment, String retrievalUrl) throws IOException
294   {
295     File pae = fetchAlphaFoldPAE(id, retrievalUrl);
296     addAlphaFoldPAE(pdbAlignment, pae, 0, null, false, false);
297   }
298
299   public static void addAlphaFoldPAE(AlignmentI pdbAlignment, File pae,
300           int index, String id, boolean isStruct, boolean isStructId)
301   {
302     FileInputStream paeInput = null;
303     try
304     {
305       paeInput = new FileInputStream(pae);
306     } catch (FileNotFoundException e)
307     {
308       Console.error(
309               "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
310       return;
311     }
312
313     if (isStruct)
314     {
315       StructureSelectionManager ssm = StructureSelectionManager
316               .getStructureSelectionManager(Desktop.instance);
317       if (ssm != null)
318       {
319         String structFilename = isStructId ? ssm.findFileForPDBId(id) : id;
320         addPAEToStructure(ssm, structFilename, pae);
321       }
322
323     }
324     else
325     {
326       // attach to sequence?!
327       try
328       {
329         if (!importPaeJSONAsContactMatrixToSequence(pdbAlignment, paeInput,
330                 index, id))
331         {
332           Console.warn("Could not import contact matrix from '"
333                   + pae.getAbsolutePath() + "' to sequence.");
334         }
335       } catch (IOException e1)
336       {
337         Console.error("Error when importing pAE file '"
338                 + pae.getAbsolutePath() + "'", e1);
339       } catch (ParseException e2)
340       {
341         Console.error("Error when parsing pAE file '"
342                 + pae.getAbsolutePath() + "'", e2);
343       }
344     }
345
346   }
347
348   public static void addPAEToStructure(StructureSelectionManager ssm,
349           String structFilename, File pae)
350   {
351     FileInputStream paeInput = null;
352     try
353     {
354       paeInput = new FileInputStream(pae);
355     } catch (FileNotFoundException e)
356     {
357       Console.error(
358               "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
359       return;
360     }
361     if (ssm == null)
362     {
363       ssm = StructureSelectionManager
364               .getStructureSelectionManager(Desktop.instance);
365     }
366     if (ssm != null)
367     {
368       StructureMapping[] smArray = ssm.getMapping(structFilename);
369
370       try
371       {
372         if (!importPaeJSONAsContactMatrixToStructure(smArray, paeInput))
373         {
374           Console.warn("Could not import contact matrix from '"
375                   + pae.getAbsolutePath() + "' to structure.");
376         }
377       } catch (IOException e1)
378       {
379         Console.error("Error when importing pAE file '"
380                 + pae.getAbsolutePath() + "'", e1);
381       } catch (ParseException e2)
382       {
383         Console.error("Error when parsing pAE file '"
384                 + pae.getAbsolutePath() + "'", e2);
385       }
386     }
387   }
388
389   /**
390    * parses the given pAE matrix and adds it to sequence 0 in the given
391    * alignment
392    * 
393    * @param pdbAlignment
394    * @param pae_input
395    * @return true if there was a pAE matrix added
396    * @throws ParseException
397    * @throws IOException
398    * @throws Exception
399    */
400   public static boolean importPaeJSONAsContactMatrixToSequence(
401           AlignmentI pdbAlignment, InputStream pae_input)
402           throws IOException, ParseException
403   {
404     return importPaeJSONAsContactMatrixToSequence(pdbAlignment, pae_input,
405             0, null);
406   }
407
408   public static boolean importPaeJSONAsContactMatrixToSequence(
409           AlignmentI pdbAlignment, File paeFile, int index, String seqId)
410           throws FileNotFoundException, IOException, ParseException
411   {
412     return importPaeJSONAsContactMatrixToSequence(pdbAlignment,
413             new FileInputStream(paeFile), index, seqId);
414   }
415
416   public static boolean importPaeJSONAsContactMatrixToSequence(
417           AlignmentI pdbAlignment, InputStream pae_input, int index,
418           String seqId) throws IOException, ParseException
419   {
420     SequenceI sequence = null;
421     if (seqId == null)
422     {
423       int seqToGet = index > 0 ? index : 0;
424       sequence = pdbAlignment.getSequenceAt(seqToGet);
425     }
426     if (sequence == null)
427     {
428       SequenceI[] sequences = pdbAlignment.findSequenceMatch(seqId);
429       if (sequences == null || sequences.length < 1)
430       {
431         Console.warn("Could not find sequence with id '" + seqId
432                 + "' to attach pAE matrix to. Ignoring matrix.");
433         return false;
434       }
435       else
436       {
437         sequence = sequences[0]; // just use the first sequence with this seqId
438       }
439     }
440     if (sequence == null)
441     {
442       return false;
443     }
444     return importPaeJSONAsContactMatrixToSequence(pdbAlignment, pae_input,
445             sequence);
446   }
447
448   public static boolean importPaeJSONAsContactMatrixToSequence(
449           AlignmentI pdbAlignment, File pae_input, SequenceI sequence)
450           throws IOException, ParseException
451   {
452     return importPaeJSONAsContactMatrixToSequence(pdbAlignment,
453             new FileInputStream(pae_input), sequence);
454   }
455
456   public static boolean importPaeJSONAsContactMatrixToSequence(
457           AlignmentI pdbAlignment, InputStream pae_input,
458           SequenceI sequence) throws IOException, ParseException
459   {
460     JSONObject paeDict = parseJSONtoPAEContactMatrix(pae_input);
461     if (paeDict == null)
462     {
463       Console.debug("JSON file did not parse properly.");
464       return false;
465     }
466     ContactMatrixI matrix = new PAEContactMatrix(sequence,
467             (Map<String, Object>) paeDict);
468
469     AlignmentAnnotation cmannot = sequence.addContactList(matrix);
470     pdbAlignment.addAnnotation(cmannot);
471
472     return true;
473   }
474
475   public static JSONObject parseJSONtoPAEContactMatrix(
476           InputStream pae_input) throws IOException, ParseException
477   {
478     Object paeJson = Platform.parseJSON(pae_input);
479     JSONObject paeDict = null;
480     if (paeJson instanceof JSONObject)
481     {
482       paeDict = (JSONObject) paeJson;
483     }
484     else if (paeJson instanceof JSONArray)
485     {
486       JSONArray jsonArray = (JSONArray) paeJson;
487       if (jsonArray.size() > 0)
488         paeDict = (JSONObject) jsonArray.get(0);
489     }
490
491     return paeDict;
492   }
493
494   public static boolean importPaeJSONAsContactMatrixToStructure(
495           StructureMapping[] smArray, InputStream paeInput)
496           throws IOException, ParseException
497   {
498     boolean someDone = false;
499     for (StructureMapping sm : smArray)
500     {
501       boolean thisDone = importPaeJSONAsContactMatrixToStructure(sm,
502               paeInput);
503       someDone |= thisDone;
504     }
505     return someDone;
506   }
507
508   public static boolean importPaeJSONAsContactMatrixToStructure(
509           StructureMapping sm, InputStream paeInput)
510           throws IOException, ParseException
511   {
512     JSONObject pae_obj = parseJSONtoPAEContactMatrix(paeInput);
513     if (pae_obj == null)
514     {
515       Console.debug("JSON file did not parse properly.");
516       return false;
517     }
518
519     ContactMatrixI matrix = new PAEContactMatrix(sm.getSequence(),
520             (Map<String, Object>) pae_obj);
521
522     AlignmentAnnotation cmannot = sm.getSequence().addContactList(matrix);
523     // sm.getSequence().addAlignmentAnnotation(cmannot);
524     sm.transfer(cmannot);
525     // return true;
526
527     StructureSelectionManager ssm = StructureSelectionManager
528             .getStructureSelectionManager(Desktop.instance);
529     List<AlignedCodonFrame> acfList = ssm.getSequenceMappings();
530
531     return true;
532   }
533
534   /**
535    * general purpose structure importer - designed to yield alignment useful for
536    * transfer of annotation to associated sequences
537    * 
538    * @param alphaFoldCif
539    * @param tmpFile
540    * @param id
541    * @param chain
542    * @param dbSource
543    * @param dbVersion
544    * @return
545    * @throws Exception
546    */
547   public static AlignmentI importDownloadedStructureFromUrl(
548           String alphaFoldCif, File tmpFile, String id, String chain,
549           String dbSource, String dbVersion) throws Exception
550   {
551     String file = tmpFile.getAbsolutePath();
552     // todo get rid of Type and use FileFormatI instead?
553     FileFormatI fileFormat = FileFormat.MMCif;
554     AlignmentI pdbAlignment = new FormatAdapter().readFile(tmpFile,
555             DataSourceType.FILE, fileFormat);
556     if (pdbAlignment != null)
557     {
558       List<SequenceI> toremove = new ArrayList<SequenceI>();
559       for (SequenceI pdbcs : pdbAlignment.getSequences())
560       {
561         String chid = null;
562         // Mapping map=null;
563         for (PDBEntry pid : pdbcs.getAllPDBEntries())
564         {
565           if (pid.getFile() == file)
566           {
567             chid = pid.getChainCode();
568
569           }
570         }
571         if (chain == null || (chid != null && (chid.equals(chain)
572                 || chid.trim().equals(chain.trim())
573                 || (chain.trim().length() == 0 && chid.equals("_")))))
574         {
575           // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
576           // TODO: suggest simplify naming to 1qip|A as default name defined
577           pdbcs.setName(id + SEPARATOR + pdbcs.getName());
578           // Might need to add more metadata to the PDBEntry object
579           // like below
580           /*
581            * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
582            * entry.setId(id); if (entry.getProperty() == null)
583            * entry.setProperty(new Hashtable());
584            * entry.getProperty().put("chains", pdbchain.id + "=" +
585            * sq.getStart() + "-" + sq.getEnd());
586            * sq.getDatasetSequence().addPDBId(entry);
587            */
588           // Add PDB DB Refs
589           // We make a DBRefEtntry because we have obtained the PDB file from
590           // a
591           // verifiable source
592           // JBPNote - PDB DBRefEntry should also carry the chain and mapping
593           // information
594           if (dbSource != null)
595           {
596             DBRefEntry dbentry = new DBRefEntry(dbSource,
597
598                     dbVersion, (chid == null ? id : id + chid));
599             // dbentry.setMap()
600             pdbcs.addDBRef(dbentry);
601             // update any feature groups
602             List<SequenceFeature> allsf = pdbcs.getFeatures()
603                     .getAllFeatures();
604             List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
605             if (allsf != null && allsf.size() > 0)
606             {
607               for (SequenceFeature f : allsf)
608               {
609                 if (file.equals(f.getFeatureGroup()))
610                 {
611                   f = new SequenceFeature(f, f.type, f.begin, f.end, id,
612                           f.score);
613                 }
614                 newsf.add(f);
615               }
616               pdbcs.setSequenceFeatures(newsf);
617             }
618           }
619         }
620         else
621         {
622           // mark this sequence to be removed from the alignment
623           // - since it's not from the right chain
624           toremove.add(pdbcs);
625         }
626       }
627       // now remove marked sequences
628       for (SequenceI pdbcs : toremove)
629       {
630         pdbAlignment.deleteSequence(pdbcs);
631         if (pdbcs.getAnnotation() != null)
632         {
633           for (AlignmentAnnotation aa : pdbcs.getAnnotation())
634           {
635             pdbAlignment.deleteAnnotation(aa);
636           }
637         }
638       }
639     }
640     return pdbAlignment;
641   }
642
643   /*
644    * (non-Javadoc)
645    * 
646    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
647    */
648   @Override
649   public boolean isValidReference(String accession)
650   {
651     Regex r = getAccessionValidator();
652     return r.search(accession.trim());
653   }
654
655   /**
656    * human glyoxalase
657    */
658   @Override
659   public String getTestQuery()
660   {
661     return "AF-O15552-F1";
662   }
663
664   @Override
665   public String getDbName()
666   {
667     return "ALPHAFOLD"; // getDbSource();
668   }
669
670   @Override
671   public int getTier()
672   {
673     return 0;
674   }
675
676   /**
677    * Returns a descriptor for suitable feature display settings with
678    * <ul>
679    * <li>ResNums or insertions features visible</li>
680    * <li>insertions features coloured red</li>
681    * <li>ResNum features coloured by label</li>
682    * <li>Insertions displayed above (on top of) ResNums</li>
683    * </ul>
684    */
685   @Override
686   public FeatureSettingsModelI getFeatureColourScheme()
687   {
688     return new PDBFeatureSettings();
689   }
690
691   // days * 86400000
692   private static final long PAE_CACHE_STALE_TIME = 1 * 86400000;
693
694   private static Map<String, File> paeDownloadCache = new HashMap<>();
695
696 }