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