JAL-3829 ignore the fake ID generated when a PDB format file without embedded ID...
[jalview.git] / src / jalview / io / StructureFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.datamodel.Alignment;
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.structure.StructureImportSettings;
34
35 import java.awt.Color;
36 import java.io.IOException;
37 import java.lang.reflect.Constructor;
38 import java.util.List;
39 import java.util.Vector;
40
41 import mc_view.PDBChain;
42
43 public abstract class StructureFile extends AlignFile
44 {
45   private String id;
46
47   private PDBEntry.Type dbRefType;
48
49   /**
50    * set to true to add derived sequence annotations (temp factor read from
51    * file, or computed secondary structure) to the alignment
52    */
53   protected boolean visibleChainAnnotation = false;
54
55   /**
56    * Set true to predict secondary structure (using JMol for protein, Annotate3D
57    * for RNA)
58    */
59   protected boolean predictSecondaryStructure = false;
60
61   /**
62    * Set true (with predictSecondaryStructure=true) to predict secondary
63    * structure using an external service (currently Annotate3D for RNA only)
64    */
65   protected boolean externalSecondaryStructure = false;
66
67   private Vector<PDBChain> chains;
68
69   private boolean pdbIdAvailable;
70
71   public StructureFile(Object inFile, DataSourceType sourceType)
72           throws IOException
73   {
74     super(inFile, sourceType);
75   }
76
77   public StructureFile(FileParse fp) throws IOException
78   {
79     super(fp);
80   }
81
82   public void addSettings(boolean addAlignmentAnnotations,
83           boolean predictSecondaryStructure, boolean externalSecStr)
84   {
85     this.visibleChainAnnotation = addAlignmentAnnotations;
86     this.predictSecondaryStructure = predictSecondaryStructure;
87     this.externalSecondaryStructure = externalSecStr;
88   }
89
90   public void xferSettings()
91   {
92     this.visibleChainAnnotation = StructureImportSettings
93             .isVisibleChainAnnotation();
94     this.predictSecondaryStructure = StructureImportSettings
95             .isProcessSecondaryStructure();
96     this.externalSecondaryStructure = StructureImportSettings
97             .isExternalSecondaryStructure();
98
99   }
100
101   public StructureFile(boolean parseImmediately, Object dataObject,
102           DataSourceType sourceType) throws IOException
103   {
104     super(parseImmediately, dataObject, sourceType);
105   }
106
107   public StructureFile(boolean a, FileParse fp) throws IOException
108   {
109     super(a, fp);
110   }
111
112   public StructureFile()
113   {
114   }
115
116   protected SequenceI postProcessChain(PDBChain chain)
117   {
118     SequenceI pdbSequence = chain.sequence;
119     pdbSequence.setName(getId() + "|" + pdbSequence.getName());
120     PDBEntry entry = new PDBEntry();
121     entry.setId(getId());
122     entry.setFakedPDBId(!isPPDBIdAvailable());
123     entry.setType(getStructureFileType());
124     if (chain.id != null)
125     {
126       entry.setChainCode(chain.id);
127     }
128     if (inFile != null)
129     {
130       entry.setFile(inFile.getAbsolutePath());
131     }
132     else
133     {
134       entry.setFile(getDataName());
135     }
136
137     DBRefEntry sourceDBRef = new DBRefEntry();
138     sourceDBRef.setAccessionId(getId());
139     sourceDBRef.setSource(DBRefSource.PDB);
140     // TODO: specify version for 'PDB' database ref if it is read from a file.
141     // TODO: decide if jalview.io should be creating primary refs!
142     sourceDBRef.setVersion("");
143     pdbSequence.addPDBId(entry);
144     pdbSequence.addDBRef(sourceDBRef);
145     SequenceI chainseq = pdbSequence;
146     seqs.addElement(chainseq);
147     AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
148
149     if (chainannot != null && visibleChainAnnotation)
150     {
151       for (int ai = 0; ai < chainannot.length; ai++)
152       {
153         chainannot[ai].visible = visibleChainAnnotation;
154         annotations.addElement(chainannot[ai]);
155       }
156     }
157     return chainseq;
158   }
159
160   /**
161    * filetype of structure file - default is PDB
162    */
163   String structureFileType = PDBEntry.Type.PDB.toString();
164
165   protected void setStructureFileType(String structureFileType)
166   {
167     this.structureFileType = structureFileType;
168   }
169
170   /**
171    * filetype of last file processed
172    * 
173    * @return
174    */
175   public String getStructureFileType()
176   {
177     return structureFileType;
178   }
179
180   @SuppressWarnings({ "unchecked", "rawtypes" })
181   protected void processPdbFileWithAnnotate3d(List<SequenceI> rna)
182           throws Exception
183   {
184     // System.out.println("this is a PDB format and RNA sequence");
185     // note: we use reflection here so that the applet can compile and run
186     // without the HTTPClient bits and pieces needed for accessing Annotate3D
187     // web service
188     try
189     {
190       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
191       if (cl != null)
192       {
193         // TODO: use the PDB ID of the structure if one is available, to save
194         // bandwidth and avoid uploading the whole structure to the service
195         Object annotate3d = cl.getConstructor(new Class[] {})
196                 .newInstance(new Object[] {});
197         AlignmentI al = ((AlignmentI) cl
198                 .getMethod("getRNAMLFor", new Class[]
199                 { FileParse.class })
200                 .invoke(annotate3d, new Object[]
201                 { new FileParse(getDataName(), dataSourceType) }));
202         for (SequenceI sq : al.getSequences())
203         {
204           if (sq.getDatasetSequence() != null)
205           {
206             if (sq.getDatasetSequence().getAllPDBEntries() != null)
207             {
208               sq.getDatasetSequence().getAllPDBEntries().clear();
209             }
210           }
211           else
212           {
213             if (sq.getAllPDBEntries() != null)
214             {
215               sq.getAllPDBEntries().clear();
216             }
217           }
218         }
219         replaceAndUpdateChains(rna, al, AlignSeq.DNA, false);
220       }
221     } catch (ClassNotFoundException x)
222     {
223       // ignore classnotfounds - occurs in applet
224     }
225   }
226
227   @SuppressWarnings("unchecked")
228   protected void replaceAndUpdateChains(List<SequenceI> prot, AlignmentI al,
229           String pep, boolean b)
230   {
231     List<List<? extends Object>> replaced = AlignSeq
232             .replaceMatchingSeqsWith(seqs, annotations, prot, al, pep,
233                     false);
234     for (PDBChain ch : getChains())
235     {
236       int p = 0;
237       for (SequenceI sq : (List<SequenceI>) replaced.get(0))
238       {
239         p++;
240         if (sq == ch.sequence || sq.getDatasetSequence() == ch.sequence)
241         {
242           p = -p;
243           break;
244         }
245       }
246       if (p < 0)
247       {
248         p = -p - 1;
249         // set shadow entry for chains
250         ch.shadow = (SequenceI) replaced.get(1).get(p);
251         ch.shadowMap = ((AlignSeq) replaced.get(2).get(p))
252                 .getMappingFromS1(false);
253       }
254     }
255   }
256
257   /**
258    * Predict secondary structure for RNA and/or protein sequences and add as
259    * annotations
260    * 
261    * @param rnaSequences
262    * @param proteinSequences
263    */
264   protected void addSecondaryStructure(List<SequenceI> rnaSequences,
265           List<SequenceI> proteinSequences)
266   {
267     /*
268      * Currently using Annotate3D for RNA, but only if the 'use external
269      * prediction' flag is set
270      */
271     if (externalSecondaryStructure && rnaSequences.size() > 0)
272     {
273       try
274       {
275         processPdbFileWithAnnotate3d(rnaSequences);
276       } catch (Exception x)
277       {
278         System.err.println("Exceptions when dealing with RNA in pdb file");
279         x.printStackTrace();
280
281       }
282     }
283
284     /*
285      * Currently using JMol PDB parser for peptide
286      */
287     if (proteinSequences.size() > 0)
288     {
289       try
290       {
291         processWithJmolParser(proteinSequences);
292       } catch (Exception x)
293       {
294         System.err.println(
295                 "Exceptions from Jmol when processing data in pdb file");
296         x.printStackTrace();
297       }
298     }
299   }
300
301   @SuppressWarnings({ "unchecked", "rawtypes" })
302   private void processWithJmolParser(List<SequenceI> prot) throws Exception
303   {
304     try
305     {
306
307       Class cl = Class.forName("jalview.ext.jmol.JmolParser");
308       if (cl != null)
309       {
310         final Constructor constructor = cl
311                 .getConstructor(new Class[]
312                 { FileParse.class });
313         final Object[] args = new Object[] {
314             new FileParse(getDataName(), dataSourceType) };
315
316         StructureImportSettings.setShowSeqFeatures(false);
317         StructureImportSettings.setVisibleChainAnnotation(false);
318         StructureImportSettings
319                 .setProcessSecondaryStructure(predictSecondaryStructure);
320         StructureImportSettings
321                 .setExternalSecondaryStructure(externalSecondaryStructure);
322         Object jmf = constructor.newInstance(args);
323         AlignmentI al = new Alignment((SequenceI[]) cl
324                 .getMethod("getSeqsAsArray", new Class[] {}).invoke(jmf));
325         cl.getMethod("addAnnotations", new Class[] { AlignmentI.class })
326                 .invoke(jmf, al);
327         for (SequenceI sq : al.getSequences())
328         {
329           if (sq.getDatasetSequence() != null)
330           {
331             sq.getDatasetSequence().getAllPDBEntries().clear();
332           }
333           else
334           {
335             sq.getAllPDBEntries().clear();
336           }
337         }
338         replaceAndUpdateChains(prot, al, AlignSeq.PEP, false);
339       }
340     } catch (ClassNotFoundException q)
341     {
342     }
343     StructureImportSettings.setShowSeqFeatures(true);
344   }
345   
346   /**
347    * Answers the first PDBChain found matching the given id, or null if none 
348    * is found
349    * 
350    * @param id
351    * @return
352    */
353   public PDBChain findChain(String id)
354   {
355     for (PDBChain chain : getChains())
356     {
357       if (chain.id.equals(id))
358       {
359         return chain;
360       }
361     }
362     return null;
363   }
364
365   public void makeResidueList()
366   {
367     for (PDBChain chain : getChains())
368     {
369       chain.makeResidueList(visibleChainAnnotation);
370     }
371   }
372
373   public void makeCaBondList()
374   {
375     for (PDBChain chain : getChains())
376     {
377       chain.makeCaBondList();
378     }
379   }
380
381   public void setChargeColours()
382   {
383     for (PDBChain chain : getChains())
384     {
385       chain.setChargeColours();
386     }
387   }
388
389   public void setColours(jalview.schemes.ColourSchemeI cs)
390   {
391     for (PDBChain chain : getChains())
392     {
393       chain.setChainColours(cs);
394     }
395   }
396
397   public void setChainColours()
398   {
399     int i = 0;
400     for (PDBChain chain : getChains())
401     {
402       chain.setChainColours(Color.getHSBColor(1.0f / i++, .4f, 1.0f));
403     }
404   }
405
406   public static boolean isRNA(SequenceI seq)
407   {
408     int length = seq.getLength();
409     for (int i = 0; i < length; i++)
410     {
411       char c = seq.getCharAt(i);
412       if ((c != 'A') && (c != 'C') && (c != 'G') && (c != 'U'))
413       {
414         return false;
415       }
416     }
417     return true;
418   }
419
420   /**
421    * make a friendly ID string.
422    * 
423    * @param dataName
424    * @return truncated dataName to after last '/' and pruned .extension if
425    *         present
426    */
427   protected String safeName(String dataName)
428   {
429     int p = 0;
430     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
431     {
432       dataName = dataName.substring(p + 1);
433     }
434     if (dataName.indexOf(".") > -1)
435     {
436       dataName = dataName.substring(0, dataName.lastIndexOf("."));
437     }
438     return dataName;
439   }
440
441   public String getId()
442   {
443     return id;
444   }
445
446   public void setId(String id)
447   {
448     this.id = id;
449   }
450
451   public Vector<PDBChain> getChains()
452   {
453     return chains;
454   }
455
456   public void setChains(Vector<PDBChain> chains)
457   {
458     this.chains = chains;
459   }
460
461   public Type getDbRefType()
462   {
463     return dbRefType;
464   }
465
466   public void setDbRefType(String dbRefType)
467   {
468     this.dbRefType = Type.getType(dbRefType);
469   }
470
471   public void setDbRefType(Type dbRefType)
472   {
473     this.dbRefType = dbRefType;
474   }
475
476   /**
477    * Returns a descriptor for suitable feature display settings with
478    * <ul>
479    * <li>ResNums or insertions features visible</li>
480    * <li>insertions features coloured red</li>
481    * <li>ResNum features coloured by label</li>
482    * <li>Insertions displayed above (on top of) ResNums</li>
483    * </ul>
484    */
485   @Override
486   public FeatureSettingsModelI getFeatureColourScheme()
487   {
488     return new PDBFeatureSettings();
489   }
490
491   /**
492    * Answers true if the structure file has a PDBId
493    * 
494    * @return
495    */
496   public boolean isPPDBIdAvailable()
497   {
498     return pdbIdAvailable;
499   }
500
501   public void setPDBIdAvailable(boolean pdbIdAvailable)
502   {
503     this.pdbIdAvailable = pdbIdAvailable;
504   }
505 }