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