JAL-4369 invokeAndWait to avoid hang whilst calling getFiles if a Jmol redraw is...
[jalview.git] / src / jalview / ws / dbsources / Pdb.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.bin.Cache;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.PDBEntry.Type;
32 import jalview.datamodel.SequenceI;
33 import jalview.io.DataSourceType;
34 import jalview.io.FileFormat;
35 import jalview.io.FileFormatI;
36 import jalview.io.FormatAdapter;
37 import jalview.io.PDBFeatureSettings;
38 import jalview.structure.StructureImportSettings;
39 import jalview.util.MessageManager;
40 import jalview.ws.ebi.EBIFetchClient;
41
42 import java.io.File;
43 import java.util.ArrayList;
44 import java.util.List;
45 import java.util.Locale;
46
47 import com.stevesoft.pat.Regex;
48
49 /**
50  * @author JimP
51  * 
52  */
53 public class Pdb 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 Pdb()
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("([1-9][0-9A-Za-z]{3}):?([ _A-Za-z0-9]?)");
86   }
87
88   /*
89    * (non-Javadoc)
90    * 
91    * @see jalview.ws.DbSourceProxy#getDbSource()
92    */
93   @Override
94   public String getDbSource()
95   {
96     return DBRefSource.PDB;
97   }
98
99   /*
100    * (non-Javadoc)
101    * 
102    * @see jalview.ws.DbSourceProxy#getDbVersion()
103    */
104   @Override
105   public String getDbVersion()
106   {
107     return "0";
108   }
109
110   /*
111    * (non-Javadoc)
112    * 
113    * @see jalview.ws.DbSourceProxy#getSequenceRecords(java.lang.String[])
114    */
115   @Override
116   public AlignmentI getSequenceRecords(String queries) throws Exception
117   {
118     updateConfiguration();
119     AlignmentI pdbAlignment = null;
120     String chain = null;
121     String id = null;
122     if (queries.indexOf(COLON) > -1)
123     {
124       chain = queries.substring(queries.indexOf(COLON) + 1);
125       id = queries.substring(0, queries.indexOf(COLON));
126     }
127     else
128     {
129       id = queries;
130     }
131
132     /*
133      * extract chain code if it is appended to the id and we
134      * don't already have one
135      */
136     if (queries.length() > PDB_ID_LENGTH && chain == null)
137     {
138       chain = queries.substring(PDB_ID_LENGTH, PDB_ID_LENGTH + 1);
139       id = queries.substring(0, PDB_ID_LENGTH);
140     }
141
142     if (!isValidReference(id))
143     {
144       jalview.bin.Console
145               .errPrintln("Ignoring invalid pdb query: '" + id + "'");
146       stopQuery();
147       return null;
148     }
149
150     /*
151      * ensure that an mmCIF format structure file is saved with extension.cif,
152      * because the Chimera "open" command recognises this extension
153      */
154     Type pdbFileFormat = StructureImportSettings
155             .getDefaultStructureFileFormat();
156     String ext = pdbFileFormat.getExtension();
157     String fetchFormat = pdbFileFormat.getFormat();
158
159     EBIFetchClient ebi = new EBIFetchClient();
160     File tmpFile = ebi.fetchDataAsFile("pdb:" + id, fetchFormat, ext);
161     file = tmpFile.getAbsolutePath();
162     stopQuery();
163     if (file == null)
164     {
165       return null;
166     }
167     try
168     {
169       // todo get rid of Type and use FileFormatI instead?
170       FileFormatI fileFormat = (pdbFileFormat == Type.PDB) ? FileFormat.PDB
171               : FileFormat.MMCif;
172       pdbAlignment = new FormatAdapter().readFile(tmpFile,
173               DataSourceType.FILE, fileFormat);
174       if (pdbAlignment != null)
175       {
176         List<SequenceI> toremove = new ArrayList<SequenceI>();
177         for (SequenceI pdbcs : pdbAlignment.getSequences())
178         {
179           String chid = null;
180           // Mapping map=null;
181           for (PDBEntry pid : pdbcs.getAllPDBEntries())
182           {
183             if (pid.getFile() == file)
184             {
185               chid = pid.getChainCode();
186
187             }
188           }
189           if (chain == null || (chid != null && (chid.equals(chain)
190                   || chid.trim().equals(chain.trim())
191                   || (chain.trim().length() == 0 && chid.equals("_")))))
192           {
193             // FIXME seems to result in 'PDB|1QIP|1qip|A' - 1QIP is redundant.
194             // TODO: suggest simplify naming to 1qip|A as default name defined
195             if (legacyJalviewPDBeName)
196             {
197               pdbcs.setName(jalview.datamodel.DBRefSource.PDB + SEPARATOR + id
198                     + SEPARATOR + pdbcs.getName());
199             } else {
200               if (simpleChainName)
201               {
202                 int sep_pos = pdbcs.getName().indexOf(SEPARATOR);
203                 String cid = pdbcs.getName().substring(0,sep_pos);
204                 cid = cid.toLowerCase(Locale.ROOT);
205                 pdbcs.setName(cid+"_"+pdbcs.getName().substring(sep_pos+1));
206               };
207             }
208             // Might need to add more metadata to the PDBEntry object
209             // like below
210             /*
211              * PDBEntry entry = new PDBEntry(); // Construct the PDBEntry
212              * entry.setId(id); if (entry.getProperty() == null)
213              * entry.setProperty(new Hashtable());
214              * entry.getProperty().put("chains", pdbchain.id + "=" +
215              * sq.getStart() + "-" + sq.getEnd());
216              * sq.getDatasetSequence().addPDBId(entry);
217              */
218             // Add PDB DB Refs
219             // We make a DBRefEtntry because we have obtained the PDB file from
220             // a
221             // verifiable source
222             // JBPNote - PDB DBRefEntry should also carry the chain and mapping
223             // information
224             DBRefEntry dbentry = new DBRefEntry(getDbSource(),
225                     getDbVersion(), (chid == null ? id : id + chid));
226             // dbentry.setMap()
227             pdbcs.addDBRef(dbentry);
228           }
229           else
230           {
231             // mark this sequence to be removed from the alignment
232             // - since it's not from the right chain
233             toremove.add(pdbcs);
234           }
235         }
236         // now remove marked sequences
237         for (SequenceI pdbcs : toremove)
238         {
239           pdbAlignment.deleteSequence(pdbcs);
240           if (pdbcs.getAnnotation() != null)
241           {
242             for (AlignmentAnnotation aa : pdbcs.getAnnotation())
243             {
244               pdbAlignment.deleteAnnotation(aa);
245             }
246           }
247         }
248       }
249
250       if (pdbAlignment == null || pdbAlignment.getHeight() < 1)
251       {
252         throw new Exception(MessageManager.formatMessage(
253                 "exception.no_pdb_records_for_chain", new String[]
254                 { id, ((chain == null) ? "' '" : chain) }));
255       }
256
257     } catch (Exception ex) // Problem parsing PDB file
258     {
259       stopQuery();
260       throw (ex);
261     }
262     return pdbAlignment;
263   }
264   
265   boolean simpleChainName=false;
266   boolean legacyJalviewPDBeName=true;
267
268   private static String SIMPLE="SIMPLE";
269   private static String LEGACY="LEGACY";
270   
271   /**
272    * update the chain naming conventions based on the configuration
273    */
274   private void updateConfiguration()
275   {
276     final String nameConf = Cache.getDefault(Cache.PDB_CHAIN_NAME, "SIMPLE");
277     simpleChainName = SIMPLE.equals(nameConf);
278     legacyJalviewPDBeName = LEGACY.equals(nameConf);
279   }
280
281   /*
282    * (non-Javadoc)
283    * 
284    * @see jalview.ws.DbSourceProxy#isValidReference(java.lang.String)
285    */
286   @Override
287   public boolean isValidReference(String accession)
288   {
289     Regex r = getAccessionValidator();
290     return r.search(accession.trim());
291   }
292
293   /**
294    * human glyoxalase
295    */
296   @Override
297   public String getTestQuery()
298   {
299     return "1QIP";
300   }
301
302   @Override
303   public String getDbName()
304   {
305     return "PDB"; // getDbSource();
306   }
307
308   @Override
309   public int getTier()
310   {
311     return 0;
312   }
313
314   /**
315    * Returns a descriptor for suitable feature display settings with
316    * <ul>
317    * <li>ResNums or insertions features visible</li>
318    * <li>insertions features coloured red</li>
319    * <li>ResNum features coloured by label</li>
320    * <li>Insertions displayed above (on top of) ResNums</li>
321    * </ul>
322    */
323   @Override
324   public FeatureSettingsModelI getFeatureColourScheme()
325   {
326     return new PDBFeatureSettings();
327   }
328 }