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