JAL-674 remove any spurious PDBEntrys generated by Jmol/RNAView parsing processes
[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         for (SequenceI sq : al.getSequences())
331         {
332           if (sq.getDatasetSequence() != null)
333           {
334             sq.getDatasetSequence().getPDBId().clear();
335           }
336           else
337           {
338             sq.getPDBId().clear();
339           }
340         }
341         AlignSeq.replaceMatchingSeqsWith(seqs, annotations, prot, al, AlignSeq.PEP, false);
342       }
343     } catch (ClassNotFoundException q)
344     {
345     }
346   }
347
348   private void processPdbFileWithAnnotate3d(ArrayList<SequenceI> rna)
349           throws Exception
350   {
351     // System.out.println("this is a PDB format and RNA sequence");
352     // note: we use reflection here so that the applet can compile and run
353     // without the HTTPClient bits and pieces needed for accessing Annotate3D
354     // web service
355     try
356     {
357       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
358       if (cl != null)
359       {
360         // TODO: use the PDB ID of the structure if one is available, to save
361         // bandwidth and avoid uploading the whole structure to the service
362         Object annotate3d = cl.getConstructor(new Class[]
363         {}).newInstance(new Object[]
364         {});
365         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
366                 new Class[]
367                 { FileParse.class }).invoke(annotate3d, new Object[]
368         { new FileParse(getDataName(), type) }));
369         for (SequenceI sq : al.getSequences())
370         {
371           if (sq.getDatasetSequence() != null)
372           {
373             sq.getDatasetSequence().getPDBId().clear();
374           }
375           else
376           {
377             sq.getPDBId().clear();
378           }
379         }
380         AlignSeq.replaceMatchingSeqsWith(seqs, annotations, rna, al, AlignSeq.DNA, false);
381       }
382     } catch (ClassNotFoundException x)
383     {
384       // ignore classnotfounds - occurs in applet
385     }
386     ;
387   }
388
389   /**
390    * make a friendly ID string.
391    * 
392    * @param dataName
393    * @return truncated dataName to after last '/'
394    */
395   private String safeName(String dataName)
396   {
397     int p = 0;
398     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
399     {
400       dataName = dataName.substring(p + 1);
401     }
402     return dataName;
403   }
404
405   public void makeResidueList()
406   {
407     for (int i = 0; i < chains.size(); i++)
408     {
409       ((PDBChain) chains.elementAt(i)).makeResidueList();
410     }
411   }
412
413   public void makeCaBondList()
414   {
415     for (int i = 0; i < chains.size(); i++)
416     {
417       ((PDBChain) chains.elementAt(i)).makeCaBondList();
418     }
419   }
420
421   public PDBChain findChain(String id)
422   {
423     for (int i = 0; i < chains.size(); i++)
424     {
425       if (((PDBChain) chains.elementAt(i)).id.equals(id))
426       {
427         return (PDBChain) chains.elementAt(i);
428       }
429     }
430
431     return null;
432   }
433
434   public void setChargeColours()
435   {
436     for (int i = 0; i < chains.size(); i++)
437     {
438       ((PDBChain) chains.elementAt(i)).setChargeColours();
439     }
440   }
441
442   public void setColours(jalview.schemes.ColourSchemeI cs)
443   {
444     for (int i = 0; i < chains.size(); i++)
445     {
446       ((PDBChain) chains.elementAt(i)).setChainColours(cs);
447     }
448   }
449
450   public void setChainColours()
451   {
452     for (int i = 0; i < chains.size(); i++)
453     {
454       ((PDBChain) chains.elementAt(i)).setChainColours(Color.getHSBColor(
455               1.0f / i, .4f, 1.0f));
456     }
457   }
458
459   public boolean isRNA(SequenceI seqs)
460   {
461     for (int i = 0; i < seqs.getLength(); i++)
462     {
463       if ((seqs.getCharAt(i) != 'A') && (seqs.getCharAt(i) != 'C')
464               && (seqs.getCharAt(i) != 'G') && (seqs.getCharAt(i) != 'U'))
465       {
466         return false;
467       }
468     }
469
470     return true;
471
472   }
473 }