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