JAL-1551 formatting
[jalview.git] / src / MCview / PDBfile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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 MCview;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.FileParse;
30 import jalview.util.MessageManager;
31
32 import java.awt.Color;
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.Hashtable;
36 import java.util.Vector;
37
38 public class PDBfile extends jalview.io.AlignFile
39 {
40   public Vector chains;
41
42   public String id;
43
44   /**
45    * set to true to add chain alignment annotation as visible annotation.
46    */
47   boolean VisibleChainAnnotation = false;
48
49   boolean processSecondaryStructure=true;
50   
51
52   public PDBfile(boolean visibleChainAnnotation,
53           boolean processSecondaryStructure)
54   {
55     super();
56     VisibleChainAnnotation = visibleChainAnnotation;
57     this.processSecondaryStructure = processSecondaryStructure;
58   }
59
60   public PDBfile(boolean visibleChainAnnotation,
61           boolean processSecondaryStructure, String file, String protocol) throws IOException
62   {
63     super(false, file, protocol);
64     VisibleChainAnnotation = visibleChainAnnotation;
65     this.processSecondaryStructure = processSecondaryStructure;
66     doParse();
67   }
68
69   public PDBfile(boolean visibleChainAnnotation,
70           boolean processSecondaryStructure, FileParse source) throws IOException
71   {
72     super(false, source);
73     VisibleChainAnnotation = visibleChainAnnotation;
74     this.processSecondaryStructure = processSecondaryStructure;
75     doParse();
76   }
77
78   public String print()
79   {
80     return null;
81   }
82
83   public void parse() throws IOException
84   {
85     // TODO set the filename sensibly - try using data source name.
86     id = safeName(getDataName());
87
88     chains = new Vector();
89     ArrayList<SequenceI> rna = new ArrayList<SequenceI>(), prot = new ArrayList<SequenceI>();
90     PDBChain tmpchain;
91     String line = null;
92     boolean modelFlag = false;
93     boolean terFlag = false;
94     String lastID = "";
95
96     int index = 0;
97     String atomnam = null;
98     try
99     {
100       while ((line = nextLine()) != null)
101       {
102         if (line.indexOf("HEADER") == 0)
103         {
104           if (line.length() > 62)
105           {
106             String tid;
107             if (line.length() > 67)
108             {
109               tid = line.substring(62, 67).trim();
110             }
111             else
112             {
113               tid = line.substring(62).trim();
114             }
115             if (tid.length() > 0)
116             {
117               id = tid;
118             }
119             continue;
120           }
121         }
122         // Were we to do anything with SEQRES - we start it here
123         if (line.indexOf("SEQRES") == 0)
124         {
125         }
126
127         if (line.indexOf("MODEL") == 0)
128         {
129           modelFlag = true;
130         }
131
132         if (line.indexOf("TER") == 0)
133         {
134           terFlag = true;
135         }
136
137         if (modelFlag && line.indexOf("ENDMDL") == 0)
138         {
139           break;
140         }
141         if (line.indexOf("ATOM") == 0
142                 || (line.indexOf("HETATM") == 0 && !terFlag))
143         {
144           terFlag = false;
145
146           // Jalview is only interested in CA bonds????
147           atomnam = line.substring(12, 15).trim();
148           if (!atomnam.equals("CA") && !atomnam.equals("P"))
149           {
150             continue;
151           }
152
153           Atom tmpatom = new Atom(line);
154           tmpchain = findChain(tmpatom.chain);
155           if (tmpchain != null)
156           {
157             if (tmpatom.resNumIns.trim().equals(lastID))
158             {
159               // phosphorylated protein - seen both CA and P..
160               continue;
161             }
162             tmpchain.atoms.addElement(tmpatom);
163           }
164           else
165           {
166             tmpchain = new PDBChain(id, tmpatom.chain);
167             chains.addElement(tmpchain);
168             tmpchain.atoms.addElement(tmpatom);
169           }
170           lastID = tmpatom.resNumIns.trim();
171         }
172         index++;
173       }
174
175       makeResidueList();
176       makeCaBondList();
177
178       if (id == null)
179       {
180         id = inFile.getName();
181       }
182       for (int i = 0; i < chains.size(); i++)
183       {
184         SequenceI dataset = ((PDBChain) chains.elementAt(i)).sequence;
185         dataset.setName(id + "|" + dataset.getName());
186         PDBEntry entry = new PDBEntry();
187         entry.setId(id);
188         entry.setProperty(new Hashtable());
189         if (((PDBChain) chains.elementAt(i)).id != null)
190         {
191           entry.getProperty().put("CHAIN",
192                   ((PDBChain) chains.elementAt(i)).id);
193         }
194         if (inFile != null)
195         {
196           entry.setFile(inFile.getAbsolutePath());
197         }
198         else
199         {
200           // TODO: decide if we should dump the datasource to disk
201           entry.setFile(getDataName());
202         }
203         dataset.addPDBId(entry);
204         SequenceI chainseq = dataset.deriveSequence(); // PDBChain objects
205         // maintain reference to
206         // dataset
207         seqs.addElement(chainseq);
208         if (isRNA(chainseq) == true)
209         {
210           rna.add(chainseq);
211         }
212         else
213         {
214           prot.add(chainseq);
215         }
216
217         AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
218
219         if (chainannot != null)
220         {
221           for (int ai = 0; ai < chainannot.length; ai++)
222           {
223             chainannot[ai].visible = VisibleChainAnnotation;
224             annotations.addElement(chainannot[ai]);
225           }
226         }
227       }
228       if (processSecondaryStructure)
229       {
230       if (rna.size() > 0)
231       {
232         try
233         {
234           processPdbFileWithAnnotate3d(rna);
235         } catch (Exception x)
236         {
237           System.err
238                   .println("Exceptions when dealing with RNA in pdb file");
239           x.printStackTrace();
240
241         }
242       }
243       ;
244       if (prot.size() > 0)
245       {
246         try
247         {
248           processPdbFileWithJmol(prot);
249         } catch (Exception x)
250         {
251           System.err
252                   .println("Exceptions from Jmol when processing data in pdb file");
253           x.printStackTrace();
254
255         }
256       }
257       }
258     } catch (OutOfMemoryError er)
259     {
260       System.out.println("OUT OF MEMORY LOADING PDB FILE");
261       throw new IOException(
262               MessageManager
263                       .getString("exception.outofmemory_loading_pdb_file"));
264     } catch (NumberFormatException ex)
265     {
266       if (line != null)
267       {
268         System.err.println("Couldn't read number from line:");
269         System.err.println(line);
270       }
271     }
272   }
273
274   private void processPdbFileWithJmol(ArrayList<SequenceI> prot)
275           throws Exception
276   {
277     try
278     {
279       Class cl = Class.forName("jalview.ext.jmol.PDBFileWithJmol");
280       if (cl != null)
281       {
282         Object jmf = cl.getConstructor(new Class[]
283         { FileParse.class }).newInstance(new Object[]
284         { new FileParse(getDataName(), type) });
285         Alignment al = new Alignment((SequenceI[]) cl.getMethod(
286                 "getSeqsAsArray", new Class[]
287                 {}).invoke(jmf));
288         cl.getMethod("addAnnotations", new Class[]
289         { Alignment.class }).invoke(jmf, al);
290         AlignSeq.replaceMatchingSeqsWith(seqs, annotations, prot, al, AlignSeq.PEP, false);
291       }
292     } catch (ClassNotFoundException q)
293     {
294     }
295   }
296
297   private void processPdbFileWithAnnotate3d(ArrayList<SequenceI> rna)
298           throws Exception
299   {
300     // System.out.println("this is a PDB format and RNA sequence");
301     // note: we use reflection here so that the applet can compile and run
302     // without the HTTPClient bits and pieces needed for accessing Annotate3D
303     // web service
304     try
305     {
306       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
307       if (cl != null)
308       {
309         // TODO: use the PDB ID of the structure if one is available, to save
310         // bandwidth and avoid uploading the whole structure to the service
311         Object annotate3d = cl.getConstructor(new Class[]
312         {}).newInstance(new Object[]
313         {});
314         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
315                 new Class[]
316                 { FileParse.class }).invoke(annotate3d, new Object[]
317         { new FileParse(getDataName(), type) }));
318         AlignSeq.replaceMatchingSeqsWith(seqs, annotations, rna, al, AlignSeq.DNA, false);
319       }
320     } catch (ClassNotFoundException x)
321     {
322       // ignore classnotfounds - occurs in applet
323     }
324     ;
325   }
326
327   /**
328    * make a friendly ID string.
329    * 
330    * @param dataName
331    * @return truncated dataName to after last '/'
332    */
333   private String safeName(String dataName)
334   {
335     int p = 0;
336     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
337     {
338       dataName = dataName.substring(p + 1);
339     }
340     return dataName;
341   }
342
343   public void makeResidueList()
344   {
345     for (int i = 0; i < chains.size(); i++)
346     {
347       ((PDBChain) chains.elementAt(i)).makeResidueList();
348     }
349   }
350
351   public void makeCaBondList()
352   {
353     for (int i = 0; i < chains.size(); i++)
354     {
355       ((PDBChain) chains.elementAt(i)).makeCaBondList();
356     }
357   }
358
359   public PDBChain findChain(String id)
360   {
361     for (int i = 0; i < chains.size(); i++)
362     {
363       if (((PDBChain) chains.elementAt(i)).id.equals(id))
364       {
365         return (PDBChain) chains.elementAt(i);
366       }
367     }
368
369     return null;
370   }
371
372   public void setChargeColours()
373   {
374     for (int i = 0; i < chains.size(); i++)
375     {
376       ((PDBChain) chains.elementAt(i)).setChargeColours();
377     }
378   }
379
380   public void setColours(jalview.schemes.ColourSchemeI cs)
381   {
382     for (int i = 0; i < chains.size(); i++)
383     {
384       ((PDBChain) chains.elementAt(i)).setChainColours(cs);
385     }
386   }
387
388   public void setChainColours()
389   {
390     for (int i = 0; i < chains.size(); i++)
391     {
392       ((PDBChain) chains.elementAt(i)).setChainColours(Color.getHSBColor(
393               1.0f / i, .4f, 1.0f));
394     }
395   }
396
397   public boolean isRNA(SequenceI seqs)
398   {
399     for (int i = 0; i < seqs.getLength(); i++)
400     {
401       if ((seqs.getCharAt(i) != 'A') && (seqs.getCharAt(i) != 'C')
402               && (seqs.getCharAt(i) != 'G') && (seqs.getCharAt(i) != 'U'))
403       {
404         return false;
405       }
406     }
407
408     return true;
409
410   }
411 }