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