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