JAL-674 methods and test for PDB derived annotation stored and recovered in project
[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   private static String calcIdPrefix = "JalviewPDB:";
276
277   public static boolean isCalcIdHandled(String calcId)
278   {
279     return calcId != null
280             && (calcId.startsWith(calcIdPrefix) && calcId.indexOf(
281                     calcIdPrefix,
282             calcIdPrefix.length() + 1) > -1);
283   }
284   public static boolean isCalcIdForFile(String calcId, String pdbFile)
285   {
286     return (calcId != null && calcId.startsWith(calcIdPrefix + pdbFile
287             + ":" + calcIdPrefix));
288   }
289
290   public static String relocateCalcId(String calcId,
291           Hashtable<String, String> alreadyLoadedPDB) throws Exception
292   {
293     int s = calcIdPrefix.length(), end = calcId.indexOf(calcIdPrefix, s);
294     String between = calcId.substring(s, end - 1);
295     return calcIdPrefix + alreadyLoadedPDB.get(between) + ":"
296             + calcId.substring(end);
297   }
298
299   private void markCalcIds()
300   {
301     for (SequenceI sq : seqs)
302     {
303       for (AlignmentAnnotation aa : sq.getAnnotation())
304       {
305         String oldId = aa.getCalcId();
306         if (oldId == null)
307         {
308           oldId = "";
309         }
310         aa.setCalcId("JalviewPDB:" + id + ":JalviewPDB:" + oldId);
311       }
312     }
313   }
314   private void processPdbFileWithJmol(ArrayList<SequenceI> prot)
315           throws Exception
316   {
317     try
318     {
319       Class cl = Class.forName("jalview.ext.jmol.PDBFileWithJmol");
320       if (cl != null)
321       {
322         Object jmf = cl.getConstructor(new Class[]
323         { FileParse.class }).newInstance(new Object[]
324         { new FileParse(getDataName(), type) });
325         Alignment al = new Alignment((SequenceI[]) cl.getMethod(
326                 "getSeqsAsArray", new Class[]
327                 {}).invoke(jmf));
328         cl.getMethod("addAnnotations", new Class[]
329         { Alignment.class }).invoke(jmf, al);
330         AlignSeq.replaceMatchingSeqsWith(seqs, annotations, prot, al, AlignSeq.PEP, false);
331       }
332     } catch (ClassNotFoundException q)
333     {
334     }
335   }
336
337   private void processPdbFileWithAnnotate3d(ArrayList<SequenceI> rna)
338           throws Exception
339   {
340     // System.out.println("this is a PDB format and RNA sequence");
341     // note: we use reflection here so that the applet can compile and run
342     // without the HTTPClient bits and pieces needed for accessing Annotate3D
343     // web service
344     try
345     {
346       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
347       if (cl != null)
348       {
349         // TODO: use the PDB ID of the structure if one is available, to save
350         // bandwidth and avoid uploading the whole structure to the service
351         Object annotate3d = cl.getConstructor(new Class[]
352         {}).newInstance(new Object[]
353         {});
354         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
355                 new Class[]
356                 { FileParse.class }).invoke(annotate3d, new Object[]
357         { new FileParse(getDataName(), type) }));
358         AlignSeq.replaceMatchingSeqsWith(seqs, annotations, rna, al, AlignSeq.DNA, false);
359       }
360     } catch (ClassNotFoundException x)
361     {
362       // ignore classnotfounds - occurs in applet
363     }
364     ;
365   }
366
367   /**
368    * make a friendly ID string.
369    * 
370    * @param dataName
371    * @return truncated dataName to after last '/'
372    */
373   private String safeName(String dataName)
374   {
375     int p = 0;
376     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
377     {
378       dataName = dataName.substring(p + 1);
379     }
380     return dataName;
381   }
382
383   public void makeResidueList()
384   {
385     for (int i = 0; i < chains.size(); i++)
386     {
387       ((PDBChain) chains.elementAt(i)).makeResidueList();
388     }
389   }
390
391   public void makeCaBondList()
392   {
393     for (int i = 0; i < chains.size(); i++)
394     {
395       ((PDBChain) chains.elementAt(i)).makeCaBondList();
396     }
397   }
398
399   public PDBChain findChain(String id)
400   {
401     for (int i = 0; i < chains.size(); i++)
402     {
403       if (((PDBChain) chains.elementAt(i)).id.equals(id))
404       {
405         return (PDBChain) chains.elementAt(i);
406       }
407     }
408
409     return null;
410   }
411
412   public void setChargeColours()
413   {
414     for (int i = 0; i < chains.size(); i++)
415     {
416       ((PDBChain) chains.elementAt(i)).setChargeColours();
417     }
418   }
419
420   public void setColours(jalview.schemes.ColourSchemeI cs)
421   {
422     for (int i = 0; i < chains.size(); i++)
423     {
424       ((PDBChain) chains.elementAt(i)).setChainColours(cs);
425     }
426   }
427
428   public void setChainColours()
429   {
430     for (int i = 0; i < chains.size(); i++)
431     {
432       ((PDBChain) chains.elementAt(i)).setChainColours(Color.getHSBColor(
433               1.0f / i, .4f, 1.0f));
434     }
435   }
436
437   public boolean isRNA(SequenceI seqs)
438   {
439     for (int i = 0; i < seqs.getLength(); i++)
440     {
441       if ((seqs.getCharAt(i) != 'A') && (seqs.getCharAt(i) != 'C')
442               && (seqs.getCharAt(i) != 'G') && (seqs.getCharAt(i) != 'U'))
443       {
444         return false;
445       }
446     }
447
448     return true;
449
450   }
451 }