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