4449b0b04e5abbc0e7307e332fa97ff06dab01f2
[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 jalview.api.FeatureSettingsModelI;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.PDBEntry;
30 import jalview.datamodel.PDBEntry.Type;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceI;
33 import jalview.datamodel.features.SequenceFeaturesI;
34 import jalview.io.DataSourceType;
35 import jalview.io.FileFormat;
36 import jalview.io.FileFormatI;
37 import jalview.io.FormatAdapter;
38 import jalview.io.PDBFeatureSettings;
39 import jalview.structure.StructureImportSettings;
40 import jalview.util.HttpUtils;
41 import jalview.util.MessageManager;
42 import jalview.ws.ebi.EBIFetchClient;
43 import jalview.ws.utils.UrlDownloadClient;
44
45 import java.io.File;
46 import java.util.ArrayList;
47 import java.util.List;
48
49 import com.stevesoft.pat.Regex;
50
51 /**
52  * @author JimP
53  * 
54  */
55 public class EBIAlfaFold extends EbiFileRetrievedProxy
56 {
57   private static final String SEPARATOR = "|";
58
59   private static final String COLON = ":";
60
61   private static final int PDB_ID_LENGTH = 4;
62
63   public EBIAlfaFold()
64   {
65     super();
66   }
67
68   /*
69    * (non-Javadoc)
70    * 
71    * @see jalview.ws.DbSourceProxy#getAccessionSeparator()
72    */
73   @Override
74   public String getAccessionSeparator()
75   {
76     return null;
77   }
78
79   /*
80    * (non-Javadoc)
81    * 
82    * @see jalview.ws.DbSourceProxy#getAccessionValidator()
83    */
84   @Override
85   public Regex getAccessionValidator()
86   {
87     Regex validator =  new Regex("(AF-[A-Z]+[0-9]+[A-Z0-9]+-F1)");
88     validator.setIgnoreCase(true);
89     return validator;
90   }
91
92   /*
93    * (non-Javadoc)
94    * 
95    * @see jalview.ws.DbSourceProxy#getDbSource()
96    */
97   @Override
98   public String getDbSource()
99   {
100     return "ALPHAFOLD";
101   }
102
103   /*
104    * (non-Javadoc)
105    * 
106    * @see jalview.ws.DbSourceProxy#getDbVersion()
107    */
108   @Override
109   public String getDbVersion()
110   {
111     return "1";
112   }
113
114   public static String getAlphaFoldCifDownloadUrl(String id)
115   {
116     return "https://alphafold.ebi.ac.uk/files/" + id + "-model_v1.cif";
117   }
118
119   /*
120    * (non-Javadoc)
121    * 
122    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
123    */
124   @Override
125   public AlignmentI getSequenceRecords(String queries) throws Exception
126   {
127     return getSequenceRecords(queries, null);
128   }
129   public AlignmentI getSequenceRecords(String queries, String retrievalUrl) throws Exception
130   {
131     AlignmentI pdbAlignment = null;
132     String chain = null;
133     String id = null;
134     if (queries.indexOf(COLON) > -1)
135     {
136       chain = queries.substring(queries.indexOf(COLON) + 1);
137       id = queries.substring(0, queries.indexOf(COLON));
138     }
139     else
140     {
141       id = queries;
142     }
143
144     if (!isValidReference(id))
145     {
146       System.err.println(
147               "(AFClient) Ignoring invalid pdb query: '" + id + "'");
148       stopQuery();
149       return null;
150     }
151     String alphaFoldCif = getAlphaFoldCifDownloadUrl(id);
152     if (retrievalUrl != null)
153     {
154       alphaFoldCif = retrievalUrl;
155     }
156
157     try
158     {
159       File tmpFile = File.createTempFile(id, ".cif");
160       UrlDownloadClient.download(alphaFoldCif, tmpFile);
161       
162       // may not need this check ?
163       file = tmpFile.getAbsolutePath();
164       if (file == null)
165       {
166         return null;
167       }
168
169       pdbAlignment = importDownloadedStructureFromUrl(alphaFoldCif, tmpFile, id, chain, getDbSource(),getDbVersion());
170       
171
172       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
173       {
174         throw new Exception(MessageManager.formatMessage(
175                 "exception.no_pdb_records_for_chain", new String[]
176                 { id, ((chain == null) ? "' '" : chain) }));
177       }
178
179     } catch (Exception ex) // Problem parsing PDB file
180     {
181       stopQuery();
182       throw (ex);
183     }
184     return pdbAlignment;
185   }
186
187   /**
188    * general purpose structure importer - designed to yield alignment useful for transfer of annotation to associated sequences
189    * @param alphaFoldCif
190    * @param tmpFile
191    * @param id
192    * @param chain
193    * @param dbSource
194    * @param dbVersion
195    * @return
196    * @throws Exception
197    */
198   public static AlignmentI importDownloadedStructureFromUrl(String alphaFoldCif,
199           File tmpFile, String id, String chain, String dbSource, String dbVersion) throws Exception
200   {
201     String file = tmpFile.getAbsolutePath();
202     // todo get rid of Type and use FileFormatI instead?
203     FileFormatI fileFormat = FileFormat.MMCif;
204     AlignmentI pdbAlignment = new FormatAdapter().readFile(tmpFile,
205             DataSourceType.FILE, fileFormat);
206     if (pdbAlignment != null)
207     {
208       List<SequenceI> toremove = new ArrayList<SequenceI>();
209       for (SequenceI pdbcs : pdbAlignment.getSequences())
210       {
211         String chid = null;
212         // Mapping map=null;
213         for (PDBEntry pid : pdbcs.getAllPDBEntries())
214         {
215           if (pid.getFile() == file)
216           {
217             chid = pid.getChainCode();
218
219           }
220         }
221         if (chain == null || (chid != null && (chid.equals(chain)
222                 || chid.trim().equals(chain.trim())
223                 || (chain.trim().length() == 0 && chid.equals("_")))))
224         {
225           // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
226           // TODO: suggest simplify naming to 1qip|A as default name defined
227           pdbcs.setName(id + SEPARATOR + pdbcs.getName());
228           // Might need to add more metadata to the PDBEntry object
229           // like below
230           /*
231            * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
232            * entry.setId(id); if (entry.getProperty() == null)
233            * entry.setProperty(new Hashtable());
234            * entry.getProperty().put("chains", pdbchain.id + "=" +
235            * sq.getStart() + "-" + sq.getEnd());
236            * sq.getDatasetSequence().addPDBId(entry);
237            */
238           // Add PDB DB Refs
239           // We make a DBRefEtntry because we have obtained the PDB file from
240           // a
241           // verifiable source
242           // JBPNote - PDB DBRefEntry should also carry the chain and mapping
243           // information
244           if (dbSource != null)
245           {
246             DBRefEntry dbentry = new DBRefEntry(dbSource,
247
248                     dbVersion, (chid == null ? id : id + chid));
249             // dbentry.setMap()
250             pdbcs.addDBRef(dbentry);
251             // update any feature groups
252             List<SequenceFeature> allsf = pdbcs.getFeatures().getAllFeatures();
253             List<SequenceFeature> newsf = new ArrayList<SequenceFeature>();
254             if (allsf!=null && allsf.size()>0)
255             {
256               for (SequenceFeature f:allsf)
257               {
258                 if (file.equals(f.getFeatureGroup()))
259                 {
260                   f = new SequenceFeature(f, f.type, f.begin, f.end, id, f.score);
261                 }
262                 newsf.add(f);
263               }
264               pdbcs.setSequenceFeatures(newsf);
265             }
266           }
267         }
268         else
269         {
270           // mark this sequence to be removed from the alignment
271           // - since it's not from the right chain
272           toremove.add(pdbcs);
273         }
274       }
275       // now remove marked sequences
276       for (SequenceI pdbcs : toremove)
277       {
278         pdbAlignment.deleteSequence(pdbcs);
279         if (pdbcs.getAnnotation() != null)
280         {
281           for (AlignmentAnnotation aa : pdbcs.getAnnotation())
282           {
283             pdbAlignment.deleteAnnotation(aa);
284           }
285         }
286       }
287     }
288     return pdbAlignment;
289   }
290
291   /*
292    * (non-Javadoc)
293    * 
294    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
295    */
296   @Override
297   public boolean isValidReference(String accession)
298   {
299     Regex r = getAccessionValidator();
300     return r.search(accession.trim());
301   }
302
303   /**
304    * human glyoxalase
305    */
306   @Override
307   public String getTestQuery()
308   {
309     return "1QIP";
310   }
311
312   @Override
313   public String getDbName()
314   {
315     return "PDB"; // getDbSource();
316   }
317
318   @Override
319   public int getTier()
320   {
321     return 0;
322   }
323
324   /**
325    * Returns a descriptor for suitable feature display settings with
326    * <ul>
327    * <li>ResNums or insertions features visible</li>
328    * <li>insertions features coloured red</li>
329    * <li>ResNum features coloured by label</li>
330    * <li>Insertions displayed above (on top of) ResNums</li>
331    * </ul>
332    */
333   @Override
334   public FeatureSettingsModelI getFeatureColourScheme()
335   {
336     return new PDBFeatureSettings();
337   }
338
339 }