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