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