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