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