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