JAL-1140 JAL-674 process with annotate3d and Jmol to get RNA and protein secondary...
[jalview.git] / src / MCview / PDBfile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package MCview;
19
20 import java.io.*;
21 import java.util.*;
22
23 import java.awt.*;
24
25 import jalview.analysis.AlignSeq;
26 import jalview.datamodel.*;
27 import jalview.ext.jmol.PDBFileWithJmol;
28 import jalview.io.FileParse;
29 import jalview.ws.jws1.Annotate3D;
30
31 public class PDBfile extends jalview.io.AlignFile
32 {
33   public Vector chains;
34
35   public String id;
36
37   /**
38    * set to true to add chain alignment annotation as visible annotation.
39    */
40   boolean VisibleChainAnnotation = false;
41
42   public PDBfile(String inFile, String inType) throws IOException
43   {
44     super(inFile, inType);
45   }
46
47   public PDBfile(FileParse source) throws IOException
48   {
49     super(source);
50   }
51
52   public String print()
53   {
54     return null;
55   }
56
57   public void parse() throws IOException
58   {
59     // TODO set the filename sensibly - try using data source name.
60     id = safeName(getDataName());
61
62     chains = new Vector();
63     ArrayList<SequenceI> rna=new ArrayList<SequenceI>(), prot=new ArrayList<SequenceI>();
64     PDBChain tmpchain;
65     String line = null;
66     boolean modelFlag = false;
67     boolean terFlag = false;
68     String lastID = "";
69
70     int index = 0;
71     String atomnam = null;
72     try
73     {
74       while ((line = nextLine()) != null)
75       {
76         if (line.indexOf("HEADER") == 0)
77         {
78           if (line.length() > 62)
79           {
80             String tid;
81             if (line.length() > 67)
82             {
83               tid = line.substring(62, 67).trim();
84             }
85             else
86             {
87               tid = line.substring(62).trim();
88             }
89             if (tid.length() > 0)
90             {
91               id = tid;
92             }
93             continue;
94           }
95         }
96         // Were we to do anything with SEQRES - we start it here
97         if (line.indexOf("SEQRES") == 0)
98         {
99         }
100
101         if (line.indexOf("MODEL") == 0)
102         {
103           modelFlag = true;
104         }
105
106         if (line.indexOf("TER") == 0)
107         {
108           terFlag = true;
109         }
110
111         if (modelFlag && line.indexOf("ENDMDL") == 0)
112         {
113           break;
114         }
115         if (line.indexOf("ATOM") == 0
116                 || (line.indexOf("HETATM") == 0 && !terFlag))
117         {
118           terFlag = false;
119
120           // Jalview is only interested in CA bonds????
121           atomnam = line.substring(12, 15).trim();
122           if (!atomnam.equals("CA") && !atomnam.equals("P"))
123           {
124             continue;
125           }
126
127           Atom tmpatom = new Atom(line);
128           tmpchain = findChain(tmpatom.chain);
129           if (tmpchain != null)
130           {
131             if (tmpatom.resNumIns.trim().equals(lastID))
132             {
133               // phosphorylated protein - seen both CA and P..
134               continue;
135             }
136             tmpchain.atoms.addElement(tmpatom);
137           }
138           else
139           {
140             tmpchain = new PDBChain(id, tmpatom.chain);
141             chains.addElement(tmpchain);
142             tmpchain.atoms.addElement(tmpatom);
143           }
144           lastID = tmpatom.resNumIns.trim();
145         }
146         index++;
147       }
148
149       makeResidueList();
150       makeCaBondList();
151
152       if (id == null)
153       {
154         id = inFile.getName();
155       }
156       for (int i = 0; i < chains.size(); i++)
157       {
158         SequenceI dataset = ((PDBChain) chains.elementAt(i)).sequence;
159         dataset.setName(id + "|" + dataset.getName());
160         PDBEntry entry = new PDBEntry();
161         entry.setId(id);
162         entry.setProperty(new Hashtable());
163         if (((PDBChain)chains.elementAt(i)).id!=null) {
164           entry.getProperty().put("CHAIN", ((PDBChain)chains.elementAt(i)).id);
165         }
166         if (inFile != null)
167         {
168           entry.setFile(inFile.getAbsolutePath());
169         }
170         else
171         {
172           // TODO: decide if we should dump the datasource to disk
173           entry.setFile(getDataName());
174         }
175         dataset.addPDBId(entry);
176         SequenceI chainseq = dataset.deriveSequence(); // PDBChain objects
177         // maintain reference to
178         // dataset
179         seqs.addElement(chainseq);
180        if(isRNA(chainseq)==true)
181        {
182          rna.add(chainseq);
183        } else {
184          prot.add(chainseq);
185        }
186          
187         AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
188         
189         if (chainannot != null)
190         {
191           for (int ai = 0; ai < chainannot.length; ai++)
192           {
193         
194             chainannot[ai].visible = VisibleChainAnnotation;
195             annotations.addElement(chainannot[ai]);
196           }
197         }
198       }
199       if (rna.size()>0)
200       try {
201         processPdbFileWithAnnotate3d(rna);
202       } catch (Exception x)
203       {
204         System.err.println("Exceptions when dealing with RNA in pdb file");
205         x.printStackTrace();
206         
207       };
208       if (prot.size()>0)
209       try {
210         processPdbFileWithJmol(prot);
211       } catch (Exception x)
212       {
213         System.err.println("Exceptions when dealing with RNA in pdb file");
214         x.printStackTrace();
215         
216       };
217       if (prot.size()>0)
218       try {
219         processPdbFileWithJmol(prot);
220       } catch (Exception x)
221       {
222         System.err.println("Exceptions when dealing with RNA in pdb file");
223         x.printStackTrace();
224         
225       };
226     } catch (OutOfMemoryError er)
227     {
228       System.out.println("OUT OF MEMORY LOADING PDB FILE");
229       throw new IOException("Out of memory loading PDB File");
230     } catch (NumberFormatException ex)
231     {
232       if (line != null)
233       {
234         System.err.println("Couldn't read number from line:");
235         System.err.println(line);
236       }
237     }
238   }
239   private void processPdbFileWithJmol(ArrayList<SequenceI> prot) throws Exception
240   {
241     PDBFileWithJmol jmf = new PDBFileWithJmol(new FileParse(getDataName(),type));
242     Alignment al = new Alignment(jmf.getSeqsAsArray());
243     jmf.addAnnotations(al);
244     replaceMatchingSeqsWith(prot, al, AlignSeq.PEP);
245   }
246   private void processPdbFileWithAnnotate3d(ArrayList<SequenceI> rna) throws Exception {
247 //    System.out.println("this is a PDB format and RNA sequence");
248     Annotate3D an3d = new Annotate3D();
249     // TODO: use the PDB ID of the structure if one is available, to save bandwidth and avoid uploading the whole structure to the service
250     AlignmentI al = an3d.getRNAMLFor(new FileParse(getDataName(),type));
251     replaceMatchingSeqsWith(rna, al, AlignSeq.DNA);
252   }
253   private void replaceMatchingSeqsWith(ArrayList<SequenceI> ochains, AlignmentI al, String dnaOrProtein)
254   {
255     if (al!=null && al.getHeight()>0)
256     {
257       ArrayList<SequenceI> matches=new ArrayList<SequenceI>();
258       ArrayList<AlignSeq> aligns=new ArrayList<AlignSeq>();
259       
260       for (SequenceI sq:ochains)
261       {
262         SequenceI bestm=null;
263         AlignSeq bestaseq=null;
264         int bestscore=0;
265         for (SequenceI msq:al.getSequences())
266         {
267           AlignSeq aseq = AlignSeq.doGlobalNWAlignment(msq, sq, dnaOrProtein);
268           if (bestm==null || aseq.getMaxScore()>bestscore)
269           {
270             bestscore=aseq.getMaxScore();
271             bestaseq= aseq;
272             bestm=msq;
273           }
274         }
275         System.out.println("Best Score for "+(matches.size()+1)+" :"+bestscore);
276         matches.add(bestm);
277         aligns.add(bestaseq);
278         al.deleteSequence(bestm);
279       }
280       for (int p=0,pSize=seqs.size();p<pSize;p++)
281       {
282         SequenceI sq,sp=seqs.get(p);
283         int q;
284         if ((q=ochains.indexOf(sp))>-1)
285         {
286           seqs.set(p, sq=matches.get(q));
287           sq.setName(sp.getName());
288           sq.setDescription(sp.getDescription());
289           sq.transferAnnotation(sp, aligns.get(q).getMappingFromS1(false));
290           int inspos=-1;
291           for (int ap=0;ap<annotations.size();)
292           {
293             if (((AlignmentAnnotation)annotations.get(ap)).sequenceRef==sp) {
294               if (inspos==-1)
295               {
296                 inspos=ap;
297               }
298               annotations.remove(ap);
299             } else {
300               ap++;
301             }
302           }
303           if (sq.getAnnotation()!=null) {
304             annotations.addAll(inspos, Arrays.asList(sq.getAnnotation()));
305           }
306         }
307       }
308     }
309   }
310   /**
311    * make a friendly ID string.
312    * 
313    * @param dataName
314    * @return truncated dataName to after last '/'
315    */
316   private String safeName(String dataName)
317   {
318     int p = 0;
319     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
320     {
321       dataName = dataName.substring(p + 1);
322     }
323     return dataName;
324   }
325
326   public void makeResidueList()
327   {
328     for (int i = 0; i < chains.size(); i++)
329     {
330       ((PDBChain) chains.elementAt(i)).makeResidueList();
331     }
332   }
333
334   public void makeCaBondList()
335   {
336     for (int i = 0; i < chains.size(); i++)
337     {
338       ((PDBChain) chains.elementAt(i)).makeCaBondList();
339     }
340   }
341
342   public PDBChain findChain(String id)
343   {
344     for (int i = 0; i < chains.size(); i++)
345     {
346       if (((PDBChain) chains.elementAt(i)).id.equals(id))
347       {
348         return (PDBChain) chains.elementAt(i);
349       }
350     }
351
352     return null;
353   }
354
355   public void setChargeColours()
356   {
357     for (int i = 0; i < chains.size(); i++)
358     {
359       ((PDBChain) chains.elementAt(i)).setChargeColours();
360     }
361   }
362
363   public void setColours(jalview.schemes.ColourSchemeI cs)
364   {
365     for (int i = 0; i < chains.size(); i++)
366     {
367       ((PDBChain) chains.elementAt(i)).setChainColours(cs);
368     }
369   }
370
371   public void setChainColours()
372   {
373     for (int i = 0; i < chains.size(); i++)
374     {
375       ((PDBChain) chains.elementAt(i)).setChainColours(Color.getHSBColor(
376               1.0f / (float) i, .4f, 1.0f));
377     }
378   }
379   public boolean isRNA(SequenceI seqs)
380   {
381           for (int i=0;i<seqs.getLength();i++){
382                   if((seqs.getCharAt(i)!='A') &&(seqs.getCharAt(i)!='C')&&(seqs.getCharAt(i)!='G')&&(seqs.getCharAt(i)!='U'))
383                   {
384                           return false;
385                   }
386           }
387          
388                   return true;
389           
390           
391   }
392 }