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