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