3 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
4 * Copyright (C) $$Year-Rel$$ The Jalview Authors
6 * This file is part of Jalview.
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.
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.
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.
22 package jalview.ws.dbsources;
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;
35 import org.json.simple.JSONArray;
36 import org.json.simple.JSONObject;
37 import org.json.simple.parser.ParseException;
39 import com.stevesoft.pat.Regex;
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;
69 public class EBIAlfaFold extends EbiFileRetrievedProxy
71 private static final String SEPARATOR = "|";
73 private static final String COLON = ":";
75 private static final int PDB_ID_LENGTH = 4;
77 private static String AF_VERSION = "3";
87 * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
90 public String getAccessionSeparator()
98 * @see jalview.ws.DbSourceProxy#getAccessionValidator()
101 public Regex getAccessionValidator()
103 Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
104 validator.setIgnoreCase(true);
111 * @see jalview.ws.DbSourceProxy#getDbSource()
114 public String getDbSource()
122 * @see jalview.ws.DbSourceProxy#getDbVersion()
125 public String getDbVersion()
130 public static String getAlphaFoldCifDownloadUrl(String id, String vnum)
132 if (vnum == null || vnum.length() == 0)
136 return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v" + vnum
140 public static String getAlphaFoldPaeDownloadUrl(String id, String vnum)
142 if (vnum == null || vnum.length() == 0)
146 return "https://alphafold.ebi.ac.uk/files/" + id
147 + "-predicted_aligned_error_v" + vnum + ".json";
153 * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
156 public AlignmentI getSequenceRecords(String queries) throws Exception
158 return getSequenceRecords(queries, null);
161 public AlignmentI getSequenceRecords(String queries, String retrievalUrl)
164 AlignmentI pdbAlignment = null;
167 if (queries.indexOf(COLON) > -1)
169 chain = queries.substring(queries.indexOf(COLON) + 1);
170 id = queries.substring(0, queries.indexOf(COLON));
177 if (!isValidReference(id))
179 jalview.bin.Console.errPrintln(
180 "(AFClient) Ignoring invalid alphafold query: '" + id + "'");
184 String alphaFoldCif = getAlphaFoldCifDownloadUrl(id, AF_VERSION);
185 if (retrievalUrl != null)
187 alphaFoldCif = retrievalUrl;
192 File tmpFile = File.createTempFile(id, ".cif");
193 Console.debug("Retrieving structure file for " + id + " from "
195 UrlDownloadClient.download(alphaFoldCif, tmpFile);
197 // may not need this check ?
198 file = tmpFile.getAbsolutePath();
203 // TODO Get the PAE file somewhere around here and remove from JmolParser
205 pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile,
206 id, chain, getDbSource(), getDbVersion());
208 if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
210 throw new Exception(MessageManager.formatMessage(
211 "exception.no_pdb_records_for_chain", new String[]
212 { id, ((chain == null) ? "' '" : chain) }));
214 // done during structure retrieval
215 // retrieve_AlphaFold_pAE(id, pdbAlignment, retrievalUrl);
217 } catch (Exception ex) // Problem parsing PDB file
226 * get an alphafold pAE for the given id and return the File object of the
227 * downloaded (temp) file
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
237 public static File fetchAlphaFoldPAE(String id, String retrievalUrl)
240 // import PAE as contact matrix - assume this will work if there was a
242 String paeURL = getAlphaFoldPaeDownloadUrl(id, AF_VERSION);
244 if (retrievalUrl != null)
246 // manufacture the PAE url from a url like ...-model-vN.cif
247 paeURL = retrievalUrl.replace("model", "predicted_aligned_error")
248 .replace(".cif", ".json");
252 File pae = paeDownloadCache.get(paeURL);
253 if (pae != null && pae.exists() && (new Date().getTime()
254 - pae.lastModified()) < PAE_CACHE_STALE_TIME)
257 "Using existing file in PAE cache for '" + paeURL + "'");
263 pae = File.createTempFile(id == null ? "af_pae" : id, "pae_json");
264 } catch (IOException e)
268 Console.debug("Downloading pae from " + paeURL + " to " + pae.toString()
272 UrlDownloadClient.download(paeURL, pae);
273 } catch (IOException e)
277 // cache and it if successful
278 paeDownloadCache.put(paeURL, pae);
283 * get an alphafold pAE for the given id, and add it to sequence 0 in
284 * pdbAlignment (assuming it came from structurefile parser).
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
294 public static void retrieve_AlphaFold_pAE(String id,
295 AlignmentI pdbAlignment, String retrievalUrl) throws IOException
297 File pae = fetchAlphaFoldPAE(id, retrievalUrl);
298 addAlphaFoldPAE(pdbAlignment, pae, 0, null, false, false, null);
301 public static void addAlphaFoldPAE(AlignmentI pdbAlignment, File pae,
302 int index, String id, boolean isStruct, boolean isStructId,
305 FileInputStream paeInput = null;
308 paeInput = new FileInputStream(pae);
309 } catch (FileNotFoundException e)
312 "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
318 // ###### WRITE A TEST for this bit of the logic addAlphaFoldPAE with
320 StructureSelectionManager ssm = StructureSelectionManager
321 .getStructureSelectionManager(Desktop.instance);
324 String structFilename = isStructId ? ssm.findFileForPDBId(id) : id;
325 addPAEToStructure(ssm, structFilename, pae, label);
331 // attach to sequence?!
334 if (!importPaeJSONAsContactMatrixToSequence(pdbAlignment, paeInput,
337 Console.warn("Could not import contact matrix from '"
338 + pae.getAbsolutePath() + "' to sequence.");
340 } catch (IOException e1)
342 Console.error("Error when importing pAE file '"
343 + pae.getAbsolutePath() + "'", e1);
344 } catch (ParseException e2)
346 Console.error("Error when parsing pAE file '"
347 + pae.getAbsolutePath() + "'", e2);
353 public static void addPAEToStructure(StructureSelectionManager ssm,
354 String structFilename, File pae, String label)
356 FileInputStream paeInput = null;
359 paeInput = new FileInputStream(pae);
360 } catch (FileNotFoundException e)
363 "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
368 ssm = StructureSelectionManager
369 .getStructureSelectionManager(Desktop.instance);
373 StructureMapping[] smArray = ssm.getMapping(structFilename);
377 if (!importPaeJSONAsContactMatrixToStructure(smArray, paeInput,
380 Console.warn("Could not import contact matrix from '"
381 + pae.getAbsolutePath() + "' to structure.");
383 } catch (IOException e1)
385 Console.error("Error when importing pAE file '"
386 + pae.getAbsolutePath() + "'", e1);
387 } catch (ParseException e2)
389 Console.error("Error when parsing pAE file '"
390 + pae.getAbsolutePath() + "'", e2);
396 * parses the given pAE matrix and adds it to sequence 0 in the given
399 * @param pdbAlignment
401 * @return true if there was a pAE matrix added
402 * @throws ParseException
403 * @throws IOException
406 public static boolean importPaeJSONAsContactMatrixToSequence(
407 AlignmentI pdbAlignment, InputStream pae_input, int index,
408 String seqId, String label) throws IOException, ParseException
410 SequenceI sequence = null;
413 int seqToGet = index > 0 ? index : 0;
414 sequence = pdbAlignment.getSequenceAt(seqToGet);
416 if (sequence == null)
418 SequenceI[] sequences = pdbAlignment.findSequenceMatch(seqId);
419 if (sequences == null || sequences.length < 1)
421 Console.warn("Could not find sequence with id '" + seqId
422 + "' to attach pAE matrix to. Ignoring matrix.");
427 sequence = sequences[0]; // just use the first sequence with this seqId
430 if (sequence == null)
434 return importPaeJSONAsContactMatrixToSequence(pdbAlignment, pae_input,
438 public static boolean importPaeJSONAsContactMatrixToSequence(
439 AlignmentI pdbAlignment, InputStream pae_input,
440 SequenceI sequence, String label)
441 throws IOException, ParseException
443 JSONObject paeDict = parseJSONtoPAEContactMatrix(pae_input);
446 Console.debug("JSON file did not parse properly.");
449 ContactMatrixI matrix = new PAEContactMatrix(sequence,
450 (Map<String, Object>) paeDict);
452 AlignmentAnnotation cmannot = sequence.addContactList(matrix);
454 cmannot.label = label;
455 pdbAlignment.addAnnotation(cmannot);
460 public static JSONObject parseJSONtoPAEContactMatrix(
461 InputStream pae_input) throws IOException, ParseException
463 Object paeJson = Platform.parseJSON(pae_input);
464 JSONObject paeDict = null;
465 if (paeJson instanceof JSONObject)
467 paeDict = (JSONObject) paeJson;
469 else if (paeJson instanceof JSONArray)
471 JSONArray jsonArray = (JSONArray) paeJson;
472 if (jsonArray.size() > 0)
473 paeDict = (JSONObject) jsonArray.get(0);
480 public static boolean importPaeJSONAsContactMatrixToStructure(
481 StructureMapping[] smArray, InputStream paeInput, String label)
482 throws IOException, ParseException
484 boolean someDone = false;
485 for (StructureMapping sm : smArray)
487 boolean thisDone = importPaeJSONAsContactMatrixToStructure(sm,
489 someDone |= thisDone;
494 public static boolean importPaeJSONAsContactMatrixToStructure(
495 StructureMapping sm, InputStream paeInput, String label)
496 throws IOException, ParseException
498 JSONObject pae_obj = parseJSONtoPAEContactMatrix(paeInput);
501 Console.debug("JSON file did not parse properly.");
505 SequenceI seq = sm.getSequence();
506 ContactMatrixI matrix = new PAEContactMatrix(seq,
507 (Map<String, Object>) pae_obj);
508 AlignmentAnnotation cmannot = sm.getSequence().addContactList(matrix);
509 /* this already happens in Sequence.addContactList()
510 seq.addAlignmentAnnotation(cmannot);
516 * general purpose structure importer - designed to yield alignment useful for
517 * transfer of annotation to associated sequences
519 * @param alphaFoldCif
528 public static AlignmentI importDownloadedStructureFromUrl(
529 String alphaFoldCif, File tmpFile, String id, String chain,
530 String dbSource, String dbVersion) throws Exception
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);
539 if (pdbAlignment != null)
541 List<SequenceI> toremove = new ArrayList<SequenceI>();
542 for (SequenceI pdbcs : pdbAlignment.getSequences())
546 for (PDBEntry pid : pdbcs.getAllPDBEntries())
548 if (pid.getFile() == file)
550 chid = pid.getChainCode();
553 if (chain == null || (chid != null && (chid.equals(chain)
554 || chid.trim().equals(chain.trim())
555 || (chain.trim().length() == 0 && chid.equals("_")))))
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
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);
571 // We make a DBRefEtntry because we have obtained the PDB file from
574 // JBPNote - PDB DBRefEntry should also carry the chain and mapping
576 if (dbSource != null)
578 DBRefEntry dbentry = new DBRefEntry(dbSource,
580 dbVersion, (chid == null ? id : id + chid));
582 pdbcs.addDBRef(dbentry);
583 // update any feature groups
584 List<SequenceFeature> allsf = pdbcs.getFeatures()
586 List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
587 if (allsf != null && allsf.size() > 0)
589 for (SequenceFeature f : allsf)
591 if (file.equals(f.getFeatureGroup()))
593 f = new SequenceFeature(f, f.type, f.begin, f.end, id,
598 pdbcs.setSequenceFeatures(newsf);
604 // mark this sequence to be removed from the alignment
605 // - since it's not from the right chain
609 // now remove marked sequences
610 for (SequenceI pdbcs : toremove)
612 pdbAlignment.deleteSequence(pdbcs);
613 if (pdbcs.getAnnotation() != null)
615 for (AlignmentAnnotation aa : pdbcs.getAnnotation())
617 pdbAlignment.deleteAnnotation(aa);
628 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
631 public boolean isValidReference(String accession)
633 Regex r = getAccessionValidator();
634 return r.search(accession.trim());
641 public String getTestQuery()
643 return "AF-O15552-F1";
647 public String getDbName()
649 return "ALPHAFOLD"; // getDbSource();
659 * Returns a descriptor for suitable feature display settings with
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>
668 public FeatureSettingsModelI getFeatureColourScheme()
670 return new PDBFeatureSettings();
674 private static final long PAE_CACHE_STALE_TIME = 1 * 86400000;
676 private static Map<String, File> paeDownloadCache = new HashMap<>();