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