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.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;
68 public class EBIAlfaFold extends EbiFileRetrievedProxy
70 private static final String SEPARATOR = "|";
72 private static final String COLON = ":";
74 private static final int PDB_ID_LENGTH = 4;
76 private static String AF_VERSION = "3";
86 * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
89 public String getAccessionSeparator()
97 * @see jalview.ws.DbSourceProxy#getAccessionValidator()
100 public Regex getAccessionValidator()
102 Regex validator = new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
103 validator.setIgnoreCase(true);
110 * @see jalview.ws.DbSourceProxy#getDbSource()
113 public String getDbSource()
121 * @see jalview.ws.DbSourceProxy#getDbVersion()
124 public String getDbVersion()
129 public static String getAlphaFoldCifDownloadUrl(String id, String vnum)
131 if (vnum == null || vnum.length() == 0)
135 return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v" + vnum
139 public static String getAlphaFoldPaeDownloadUrl(String id, String vnum)
141 if (vnum == null || vnum.length() == 0)
145 return "https://alphafold.ebi.ac.uk/files/" + id
146 + "-predicted_aligned_error_v" + vnum + ".json";
152 * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
155 public AlignmentI getSequenceRecords(String queries) throws Exception
157 return getSequenceRecords(queries, null);
160 public AlignmentI getSequenceRecords(String queries, String retrievalUrl)
163 AlignmentI pdbAlignment = null;
166 if (queries.indexOf(COLON) > -1)
168 chain = queries.substring(queries.indexOf(COLON) + 1);
169 id = queries.substring(0, queries.indexOf(COLON));
176 if (!isValidReference(id))
179 "(AFClient) Ignoring invalid alphafold query: '" + id + "'");
183 String alphaFoldCif = getAlphaFoldCifDownloadUrl(id, AF_VERSION);
184 if (retrievalUrl != null)
186 alphaFoldCif = retrievalUrl;
191 File tmpFile = File.createTempFile(id, ".cif");
192 Console.debug("Retrieving structure file for " + id + " from "
194 UrlDownloadClient.download(alphaFoldCif, tmpFile);
196 // may not need this check ?
197 file = tmpFile.getAbsolutePath();
202 // TODO Get the PAE file somewhere around here and remove from JmolParser
204 pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile,
205 id, chain, getDbSource(), getDbVersion());
207 if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
209 throw new Exception(MessageManager.formatMessage(
210 "exception.no_pdb_records_for_chain", new String[]
211 { id, ((chain == null) ? "' '" : chain) }));
213 // done during structure retrieval
214 // retrieve_AlphaFold_pAE(id, pdbAlignment, retrievalUrl);
216 } catch (Exception ex) // Problem parsing PDB file
225 * get an alphafold pAE for the given id and return the File object of the
226 * downloaded (temp) file
229 * @param pdbAlignment
230 * @param retrievalUrl
231 * - URL of .mmcif from EBI-AlphaFold - will be used to generate the
232 * pAE URL automatically
233 * @throws IOException
236 public static File fetchAlphaFoldPAE(String id, String retrievalUrl)
239 // import PAE as contact matrix - assume this will work if there was a
241 String paeURL = getAlphaFoldPaeDownloadUrl(id, AF_VERSION);
243 if (retrievalUrl != null)
245 // manufacture the PAE url from a url like ...-model-vN.cif
246 paeURL = retrievalUrl.replace("model", "predicted_aligned_error")
247 .replace(".cif", ".json");
251 File pae = paeDownloadCache.get(paeURL);
252 if (pae != null && pae.exists() && (new Date().getTime()
253 - pae.lastModified()) < PAE_CACHE_STALE_TIME)
256 "Using existing file in PAE cache for '" + paeURL + "'");
262 pae = File.createTempFile(id == null ? "af_pae" : id, "pae_json");
263 } catch (IOException e)
267 Console.debug("Downloading pae from " + paeURL + " to " + pae.toString()
271 UrlDownloadClient.download(paeURL, pae);
272 } catch (IOException e)
276 // cache and it if successful
277 paeDownloadCache.put(paeURL, pae);
282 * get an alphafold pAE for the given id, and add it to sequence 0 in
283 * pdbAlignment (assuming it came from structurefile parser).
286 * @param pdbAlignment
287 * @param retrievalUrl
288 * - URL of .mmcif from EBI-AlphaFold - will be used to generate the
289 * pAE URL automatically
290 * @throws IOException
293 public static void retrieve_AlphaFold_pAE(String id,
294 AlignmentI pdbAlignment, String retrievalUrl) throws IOException
296 File pae = fetchAlphaFoldPAE(id, retrievalUrl);
297 addAlphaFoldPAE(pdbAlignment, pae, 0, null, false, false, null);
300 public static void addAlphaFoldPAE(AlignmentI pdbAlignment, File pae,
301 int index, String id, boolean isStruct, boolean isStructId,
304 FileInputStream paeInput = null;
307 paeInput = new FileInputStream(pae);
308 } catch (FileNotFoundException e)
311 "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
317 // ###### WRITE A TEST for this bit of the logic addAlphaFoldPAE with
319 StructureSelectionManager ssm = StructureSelectionManager
320 .getStructureSelectionManager(Desktop.instance);
323 String structFilename = isStructId ? ssm.findFileForPDBId(id) : id;
324 addPAEToStructure(ssm, structFilename, pae, label);
330 // attach to sequence?!
333 if (!importPaeJSONAsContactMatrixToSequence(pdbAlignment, paeInput,
336 Console.warn("Could not import contact matrix from '"
337 + pae.getAbsolutePath() + "' to sequence.");
339 } catch (IOException e1)
341 Console.error("Error when importing pAE file '"
342 + pae.getAbsolutePath() + "'", e1);
343 } catch (ParseException e2)
345 Console.error("Error when parsing pAE file '"
346 + pae.getAbsolutePath() + "'", e2);
352 public static void addPAEToStructure(StructureSelectionManager ssm,
353 String structFilename, File pae, String label)
355 FileInputStream paeInput = null;
358 paeInput = new FileInputStream(pae);
359 } catch (FileNotFoundException e)
362 "Could not find pAE file '" + pae.getAbsolutePath() + "'", e);
367 ssm = StructureSelectionManager
368 .getStructureSelectionManager(Desktop.instance);
372 StructureMapping[] smArray = ssm.getMapping(structFilename);
376 if (!importPaeJSONAsContactMatrixToStructure(smArray, paeInput,
379 Console.warn("Could not import contact matrix from '"
380 + pae.getAbsolutePath() + "' to structure.");
382 } catch (IOException e1)
384 Console.error("Error when importing pAE file '"
385 + pae.getAbsolutePath() + "'", e1);
386 } catch (ParseException e2)
388 Console.error("Error when parsing pAE file '"
389 + pae.getAbsolutePath() + "'", e2);
395 * parses the given pAE matrix and adds it to sequence 0 in the given
398 * @param pdbAlignment
400 * @return true if there was a pAE matrix added
401 * @throws ParseException
402 * @throws IOException
405 public static boolean importPaeJSONAsContactMatrixToSequence(
406 AlignmentI pdbAlignment, InputStream pae_input, int index,
407 String seqId, String label) throws IOException, ParseException
409 SequenceI sequence = null;
412 int seqToGet = index > 0 ? index : 0;
413 sequence = pdbAlignment.getSequenceAt(seqToGet);
415 if (sequence == null)
417 SequenceI[] sequences = pdbAlignment.findSequenceMatch(seqId);
418 if (sequences == null || sequences.length < 1)
420 Console.warn("Could not find sequence with id '" + seqId
421 + "' to attach pAE matrix to. Ignoring matrix.");
426 sequence = sequences[0]; // just use the first sequence with this seqId
429 if (sequence == null)
433 return importPaeJSONAsContactMatrixToSequence(pdbAlignment, pae_input,
437 public static boolean importPaeJSONAsContactMatrixToSequence(
438 AlignmentI pdbAlignment, InputStream pae_input,
439 SequenceI sequence, String label)
440 throws IOException, ParseException
442 JSONObject paeDict = parseJSONtoPAEContactMatrix(pae_input);
445 Console.debug("JSON file did not parse properly.");
448 ContactMatrixI matrix = new PAEContactMatrix(sequence,
449 (Map<String, Object>) paeDict);
450 ((PAEContactMatrix) matrix).makeGroups(5f, true);
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 ((PAEContactMatrix) matrix).makeGroups(5f, true);
509 AlignmentAnnotation cmannot = seq.addContactList(matrix);
510 /* this already happens in Sequence.addContactList()
511 seq.addAlignmentAnnotation(cmannot);
517 * general purpose structure importer - designed to yield alignment useful for
518 * transfer of annotation to associated sequences
520 * @param alphaFoldCif
529 public static AlignmentI importDownloadedStructureFromUrl(
530 String alphaFoldCif, File tmpFile, String id, String chain,
531 String dbSource, String dbVersion) throws Exception
533 String file = tmpFile.getAbsolutePath();
534 // todo get rid of Type and use FileFormatI instead?
535 FileFormatI fileFormat = FileFormat.MMCif;
536 TFType tempfacType = TFType.PLDDT;
537 AlignmentI pdbAlignment = new FormatAdapter().readFile(tmpFile, file,
538 DataSourceType.FILE, fileFormat, tempfacType);
540 if (pdbAlignment != null)
542 List<SequenceI> toremove = new ArrayList<SequenceI>();
543 for (SequenceI pdbcs : pdbAlignment.getSequences())
547 for (PDBEntry pid : pdbcs.getAllPDBEntries())
549 if (pid.getFile() == file)
551 chid = pid.getChainCode();
554 if (chain == null || (chid != null && (chid.equals(chain)
555 || chid.trim().equals(chain.trim())
556 || (chain.trim().length() == 0 && chid.equals("_")))))
558 // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
559 // TODO: suggest simplify naming to 1qip|A as default name defined
560 pdbcs.setName(id + SEPARATOR + pdbcs.getName());
561 // Might need to add more metadata to the PDBEntry object
564 * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
565 * entry.setId(id); if (entry.getProperty() == null)
566 * entry.setProperty(new Hashtable());
567 * entry.getProperty().put("chains", pdbchain.id + "=" +
568 * sq.getStart() + "-" + sq.getEnd());
569 * sq.getDatasetSequence().addPDBId(entry);
572 // We make a DBRefEtntry because we have obtained the PDB file from
575 // JBPNote - PDB DBRefEntry should also carry the chain and mapping
577 if (dbSource != null)
579 DBRefEntry dbentry = new DBRefEntry(dbSource,
581 dbVersion, (chid == null ? id : id + chid));
583 pdbcs.addDBRef(dbentry);
584 // update any feature groups
585 List<SequenceFeature> allsf = pdbcs.getFeatures()
587 List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
588 if (allsf != null && allsf.size() > 0)
590 for (SequenceFeature f : allsf)
592 if (file.equals(f.getFeatureGroup()))
594 f = new SequenceFeature(f, f.type, f.begin, f.end, id,
599 pdbcs.setSequenceFeatures(newsf);
605 // mark this sequence to be removed from the alignment
606 // - since it's not from the right chain
610 // now remove marked sequences
611 for (SequenceI pdbcs : toremove)
613 pdbAlignment.deleteSequence(pdbcs);
614 if (pdbcs.getAnnotation() != null)
616 for (AlignmentAnnotation aa : pdbcs.getAnnotation())
618 pdbAlignment.deleteAnnotation(aa);
629 * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
632 public boolean isValidReference(String accession)
634 Regex r = getAccessionValidator();
635 return r.search(accession.trim());
642 public String getTestQuery()
644 return "AF-O15552-F1";
648 public String getDbName()
650 return "ALPHAFOLD"; // getDbSource();
660 * Returns a descriptor for suitable feature display settings with
662 * <li>ResNums or insertions features visible</li>
663 * <li>insertions features coloured red</li>
664 * <li>ResNum features coloured by label</li>
665 * <li>Insertions displayed above (on top of) ResNums</li>
669 public FeatureSettingsModelI getFeatureColourScheme()
671 return new PDBFeatureSettings();
675 private static final long PAE_CACHE_STALE_TIME = 1 * 86400000;
677 private static Map<String, File> paeDownloadCache = new HashMap<>();