Merge branch 'develop' into develop_m2_8_1_2
[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
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     PDBFileWithJmol jmf = new PDBFileWithJmol(new FileParse(getDataName(),type));
241     Alignment al = new Alignment(jmf.getSeqsAsArray());
242     jmf.addAnnotations(al);
243     replaceMatchingSeqsWith(prot, al, AlignSeq.PEP);
244   }
245   private void processPdbFileWithAnnotate3d(ArrayList<SequenceI> rna) throws Exception {
246 //    System.out.println("this is a PDB format and RNA sequence");
247     // 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
248     try {
249     Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
250     if (cl!=null)
251     {
252       // TODO: use the PDB ID of the structure if one is available, to save bandwidth and avoid uploading the whole structure to the service
253       Object annotate3d = cl.getConstructor(new Class[] {}).newInstance(new Object[] {});
254       AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor", new Class[] { FileParse.class}).invoke(annotate3d, new Object[] { new FileParse(getDataName(),type)}));
255       replaceMatchingSeqsWith(rna, al, AlignSeq.DNA);
256     }
257     } catch (ClassNotFoundException x)
258     {
259       //ignore classnotfounds - occurs in applet
260     };
261   }
262   private void replaceMatchingSeqsWith(ArrayList<SequenceI> ochains, AlignmentI al, String dnaOrProtein)
263   {
264     if (al!=null && al.getHeight()>0)
265     {
266       ArrayList<SequenceI> matches=new ArrayList<SequenceI>();
267       ArrayList<AlignSeq> aligns=new ArrayList<AlignSeq>();
268       
269       for (SequenceI sq:ochains)
270       {
271         SequenceI bestm=null;
272         AlignSeq bestaseq=null;
273         int bestscore=0;
274         for (SequenceI msq:al.getSequences())
275         {
276           AlignSeq aseq = AlignSeq.doGlobalNWAlignment(msq, sq, dnaOrProtein);
277           if (bestm==null || aseq.getMaxScore()>bestscore)
278           {
279             bestscore=aseq.getMaxScore();
280             bestaseq= aseq;
281             bestm=msq;
282           }
283         }
284         System.out.println("Best Score for "+(matches.size()+1)+" :"+bestscore);
285         matches.add(bestm);
286         aligns.add(bestaseq);
287         al.deleteSequence(bestm);
288       }
289       for (int p=0,pSize=seqs.size();p<pSize;p++)
290       {
291         SequenceI sq,sp=seqs.get(p);
292         int q;
293         if ((q=ochains.indexOf(sp))>-1)
294         {
295           seqs.set(p, sq=matches.get(q));
296           sq.setName(sp.getName());
297           sq.setDescription(sp.getDescription());
298           sq.transferAnnotation(sp, aligns.get(q).getMappingFromS1(false));
299           int inspos=-1;
300           for (int ap=0;ap<annotations.size();)
301           {
302             if (((AlignmentAnnotation)annotations.get(ap)).sequenceRef==sp) {
303               if (inspos==-1)
304               {
305                 inspos=ap;
306               }
307               annotations.remove(ap);
308             } else {
309               ap++;
310             }
311           }
312           if (sq.getAnnotation()!=null) {
313             annotations.addAll(inspos, Arrays.asList(sq.getAnnotation()));
314           }
315         }
316       }
317     }
318   }
319   /**
320    * make a friendly ID string.
321    * 
322    * @param dataName
323    * @return truncated dataName to after last '/'
324    */
325   private String safeName(String dataName)
326   {
327     int p = 0;
328     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
329     {
330       dataName = dataName.substring(p + 1);
331     }
332     return dataName;
333   }
334
335   public void makeResidueList()
336   {
337     for (int i = 0; i < chains.size(); i++)
338     {
339       ((PDBChain) chains.elementAt(i)).makeResidueList();
340     }
341   }
342
343   public void makeCaBondList()
344   {
345     for (int i = 0; i < chains.size(); i++)
346     {
347       ((PDBChain) chains.elementAt(i)).makeCaBondList();
348     }
349   }
350
351   public PDBChain findChain(String id)
352   {
353     for (int i = 0; i < chains.size(); i++)
354     {
355       if (((PDBChain) chains.elementAt(i)).id.equals(id))
356       {
357         return (PDBChain) chains.elementAt(i);
358       }
359     }
360
361     return null;
362   }
363
364   public void setChargeColours()
365   {
366     for (int i = 0; i < chains.size(); i++)
367     {
368       ((PDBChain) chains.elementAt(i)).setChargeColours();
369     }
370   }
371
372   public void setColours(jalview.schemes.ColourSchemeI cs)
373   {
374     for (int i = 0; i < chains.size(); i++)
375     {
376       ((PDBChain) chains.elementAt(i)).setChainColours(cs);
377     }
378   }
379
380   public void setChainColours()
381   {
382     for (int i = 0; i < chains.size(); i++)
383     {
384       ((PDBChain) chains.elementAt(i)).setChainColours(Color.getHSBColor(
385               1.0f / (float) i, .4f, 1.0f));
386     }
387   }
388   public boolean isRNA(SequenceI seqs)
389   {
390           for (int i=0;i<seqs.getLength();i++){
391                   if((seqs.getCharAt(i)!='A') &&(seqs.getCharAt(i)!='C')&&(seqs.getCharAt(i)!='G')&&(seqs.getCharAt(i)!='U'))
392                   {
393                           return false;
394                   }
395           }
396          
397                   return true;
398           
399           
400   }
401 }