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