c1018a325efa6ac49abfdcc061f16aff6814482a
[jalview.git] / src / MCview / PDBfile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.lang.reflect.Constructor;
35 import java.util.ArrayList;
36 import java.util.Hashtable;
37 import java.util.List;
38 import java.util.Vector;
39
40 public class PDBfile extends jalview.io.AlignFile
41 {
42   private static String CALC_ID_PREFIX = "JalviewPDB";
43
44   public Vector<PDBChain> chains;
45
46   public String id;
47
48   /**
49    * set to true to add derived sequence annotations (temp factor read from
50    * file, or computed secondary structure) to the alignment
51    */
52   private boolean visibleChainAnnotation = false;
53
54   /*
55    * Set true to predict secondary structure (using JMol for protein, Annotate3D
56    * for RNA)
57    */
58   private boolean predictSecondaryStructure = true;
59
60   /*
61    * Set true (with predictSecondaryStructure=true) to predict secondary
62    * structure using an external service (currently Annotate3D for RNA only)
63    */
64   private boolean externalSecondaryStructure = false;
65
66   public PDBfile(boolean addAlignmentAnnotations,
67           boolean predictSecondaryStructure, boolean externalSecStr)
68   {
69     super();
70     this.visibleChainAnnotation = addAlignmentAnnotations;
71     this.predictSecondaryStructure = predictSecondaryStructure;
72     this.externalSecondaryStructure = externalSecStr;
73   }
74
75   public PDBfile(boolean addAlignmentAnnotations,
76           boolean predictSecondaryStructure, boolean externalSecStr,
77           String file, String protocol) throws IOException
78   {
79     super(false, file, protocol);
80     this.visibleChainAnnotation = addAlignmentAnnotations;
81     this.predictSecondaryStructure = predictSecondaryStructure;
82     this.externalSecondaryStructure = externalSecStr;
83     doParse();
84   }
85
86   public PDBfile(boolean addAlignmentAnnotations,
87           boolean predictSecondaryStructure, boolean externalSecStr,
88           FileParse source) throws IOException
89   {
90     super(false, source);
91     this.visibleChainAnnotation = addAlignmentAnnotations;
92     this.predictSecondaryStructure = predictSecondaryStructure;
93     this.externalSecondaryStructure = externalSecStr;
94     doParse();
95   }
96
97   public String print()
98   {
99     return null;
100   }
101
102   public void parse() throws IOException
103   {
104     // TODO set the filename sensibly - try using data source name.
105     id = safeName(getDataName());
106
107     chains = new Vector<PDBChain>();
108     List<SequenceI> rna = new ArrayList<SequenceI>();
109     List<SequenceI> prot = new ArrayList<SequenceI>();
110     PDBChain tmpchain;
111     String line = null;
112     boolean modelFlag = false;
113     boolean terFlag = false;
114     String lastID = "";
115
116     int indexx = 0;
117     String atomnam = null;
118     try
119     {
120       while ((line = nextLine()) != null)
121       {
122         if (line.indexOf("HEADER") == 0)
123         {
124           if (line.length() > 62)
125           {
126             String tid;
127             if (line.length() > 67)
128             {
129               tid = line.substring(62, 67).trim();
130             }
131             else
132             {
133               tid = line.substring(62).trim();
134             }
135             if (tid.length() > 0)
136             {
137               id = tid;
138             }
139             continue;
140           }
141         }
142         // Were we to do anything with SEQRES - we start it here
143         if (line.indexOf("SEQRES") == 0)
144         {
145         }
146
147         if (line.indexOf("MODEL") == 0)
148         {
149           modelFlag = true;
150         }
151
152         if (line.indexOf("TER") == 0)
153         {
154           terFlag = true;
155         }
156
157         if (modelFlag && line.indexOf("ENDMDL") == 0)
158         {
159           break;
160         }
161         if (line.indexOf("ATOM") == 0
162                 || (line.indexOf("HETATM") == 0 && !terFlag))
163         {
164           terFlag = false;
165
166           // Jalview is only interested in CA bonds????
167           atomnam = line.substring(12, 15).trim();
168           if (!atomnam.equals("CA") && !atomnam.equals("P"))
169           {
170             continue;
171           }
172
173           Atom tmpatom = new Atom(line);
174           tmpchain = findChain(tmpatom.chain);
175           if (tmpchain != null)
176           {
177             if (tmpatom.resNumIns.trim().equals(lastID))
178             {
179               // phosphorylated protein - seen both CA and P..
180               continue;
181             }
182             tmpchain.atoms.addElement(tmpatom);
183           }
184           else
185           {
186             tmpchain = new PDBChain(id, tmpatom.chain);
187             chains.addElement(tmpchain);
188             tmpchain.atoms.addElement(tmpatom);
189           }
190           lastID = tmpatom.resNumIns.trim();
191         }
192         index++;
193       }
194
195       makeResidueList();
196       makeCaBondList();
197
198       if (id == null)
199       {
200         id = inFile.getName();
201       }
202       for (PDBChain chain : chains)
203       {
204         SequenceI chainseq = postProcessChain(chain);
205         if (isRNA(chainseq))
206         {
207           rna.add(chainseq);
208         }
209         else
210         {
211           prot.add(chainseq);
212         }
213       }
214       if (predictSecondaryStructure)
215       {
216         predictSecondaryStructure(rna, prot);
217       }
218     } catch (OutOfMemoryError er)
219     {
220       System.out.println("OUT OF MEMORY LOADING PDB FILE");
221       throw new IOException(
222               MessageManager
223                       .getString("exception.outofmemory_loading_pdb_file"));
224     } catch (NumberFormatException ex)
225     {
226       if (line != null)
227       {
228         System.err.println("Couldn't read number from line:");
229         System.err.println(line);
230       }
231     }
232     markCalcIds();
233   }
234
235   /**
236    * Predict secondary structure for RNA and/or protein sequences and add as
237    * annotations
238    * 
239    * @param rnaSequences
240    * @param proteinSequences
241    */
242   protected void predictSecondaryStructure(List<SequenceI> rnaSequences,
243           List<SequenceI> proteinSequences)
244   {
245     /*
246      * Currently using Annotate3D for RNA, but only if the 'use external
247      * prediction' flag is set
248      */
249     if (externalSecondaryStructure && rnaSequences.size() > 0)
250     {
251       try
252       {
253         processPdbFileWithAnnotate3d(rnaSequences);
254       } catch (Exception x)
255       {
256         System.err.println("Exceptions when dealing with RNA in pdb file");
257         x.printStackTrace();
258
259       }
260     }
261
262     /*
263      * Currently using JMol PDB parser for peptide
264      */
265     if (proteinSequences.size() > 0)
266     {
267       try
268       {
269         processPdbFileWithJmol(proteinSequences);
270       } catch (Exception x)
271       {
272         System.err
273                 .println("Exceptions from Jmol when processing data in pdb file");
274         x.printStackTrace();
275       }
276     }
277   }
278
279   /**
280    * Process a parsed chain to construct and return a Sequence, and add it to
281    * the list of sequences parsed.
282    * 
283    * @param chain
284    * @return
285    */
286   protected SequenceI postProcessChain(PDBChain chain)
287   {
288     SequenceI dataset = chain.sequence;
289     dataset.setName(id + "|" + dataset.getName());
290     PDBEntry entry = new PDBEntry();
291     entry.setId(id);
292     entry.setType(PDBEntry.Type.PDB);
293     entry.setProperty(new Hashtable());
294     if (chain.id != null)
295     {
296       // entry.getProperty().put("CHAIN", chains.elementAt(i).id);
297       entry.setChainCode(String.valueOf(chain.id));
298     }
299     if (inFile != null)
300     {
301       entry.setFile(inFile.getAbsolutePath());
302     }
303     else
304     {
305       // TODO: decide if we should dump the datasource to disk
306       entry.setFile(getDataName());
307     }
308     dataset.addPDBId(entry);
309     // PDBChain objects maintain reference to dataset
310     SequenceI chainseq = dataset.deriveSequence();
311     seqs.addElement(chainseq);
312
313     AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
314
315     if (chainannot != null && visibleChainAnnotation)
316     {
317       for (int ai = 0; ai < chainannot.length; ai++)
318       {
319         chainannot[ai].visible = visibleChainAnnotation;
320         annotations.addElement(chainannot[ai]);
321       }
322     }
323     return chainseq;
324   }
325
326   public static boolean isCalcIdHandled(String calcId)
327   {
328     return calcId != null && (CALC_ID_PREFIX.equals(calcId));
329   }
330
331   public static boolean isCalcIdForFile(AlignmentAnnotation alan,
332           String pdbFile)
333   {
334     return alan.getCalcId() != null
335             && CALC_ID_PREFIX.equals(alan.getCalcId())
336             && pdbFile.equals(alan.getProperty("PDBID"));
337   }
338
339   public static String relocateCalcId(String calcId,
340           Hashtable<String, String> alreadyLoadedPDB) throws Exception
341   {
342     int s = CALC_ID_PREFIX.length(), end = calcId
343             .indexOf(CALC_ID_PREFIX, s);
344     String between = calcId.substring(s, end - 1);
345     return CALC_ID_PREFIX + alreadyLoadedPDB.get(between) + ":"
346             + calcId.substring(end);
347   }
348
349   private void markCalcIds()
350   {
351     for (SequenceI sq : seqs)
352     {
353       if (sq.getAnnotation() != null)
354       {
355         for (AlignmentAnnotation aa : sq.getAnnotation())
356         {
357           String oldId = aa.getCalcId();
358           if (oldId == null)
359           {
360             oldId = "";
361           }
362           aa.setCalcId(CALC_ID_PREFIX);
363           aa.setProperty("PDBID", id);
364           aa.setProperty("oldCalcId", oldId);
365         }
366       }
367     }
368   }
369
370   private void processPdbFileWithJmol(List<SequenceI> prot)
371           throws Exception
372   {
373     try
374     {
375       Class cl = Class.forName("jalview.ext.jmol.PDBFileWithJmol");
376       if (cl != null)
377       {
378         final Constructor constructor = cl
379                 .getConstructor(new Class[] { FileParse.class });
380         final Object[] args = new Object[] { new FileParse(getDataName(),
381                 type) };
382         Object jmf = constructor.newInstance(args);
383         AlignmentI al = new Alignment((SequenceI[]) cl.getMethod(
384                 "getSeqsAsArray", new Class[] {}).invoke(jmf));
385         cl.getMethod("addAnnotations", new Class[] { AlignmentI.class })
386                 .invoke(jmf, al);
387         for (SequenceI sq : al.getSequences())
388         {
389           if (sq.getDatasetSequence() != null)
390           {
391             sq.getDatasetSequence().getAllPDBEntries().clear();
392           }
393           else
394           {
395             sq.getAllPDBEntries().clear();
396           }
397         }
398         replaceAndUpdateChains(prot, al, AlignSeq.PEP, false);
399       }
400     } catch (ClassNotFoundException q)
401     {
402     }
403   }
404
405   private void replaceAndUpdateChains(List<SequenceI> prot, AlignmentI al,
406           String pep, boolean b)
407   {
408     List<List<? extends Object>> replaced = AlignSeq
409             .replaceMatchingSeqsWith(seqs, annotations, prot, al, pep,
410                     false);
411     for (PDBChain ch : chains)
412     {
413       int p = 0;
414       for (SequenceI sq : (List<SequenceI>) replaced.get(0))
415       {
416         p++;
417         if (sq == ch.sequence || sq.getDatasetSequence() == ch.sequence)
418         {
419           p = -p;
420           break;
421         }
422       }
423       if (p < 0)
424       {
425         p = -p - 1;
426         // set shadow entry for chains
427         ch.shadow = (SequenceI) replaced.get(1).get(p);
428         ch.shadowMap = ((AlignSeq) replaced.get(2).get(p))
429                 .getMappingFromS1(false);
430       }
431     }
432   }
433
434   private void processPdbFileWithAnnotate3d(List<SequenceI> rna)
435           throws Exception
436   {
437     // System.out.println("this is a PDB format and RNA sequence");
438     // note: we use reflection here so that the applet can compile and run
439     // without the HTTPClient bits and pieces needed for accessing Annotate3D
440     // web service
441     try
442     {
443       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
444       if (cl != null)
445       {
446         // TODO: use the PDB ID of the structure if one is available, to save
447         // bandwidth and avoid uploading the whole structure to the service
448         Object annotate3d = cl.getConstructor(new Class[] {}).newInstance(
449                 new Object[] {});
450         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
451                 new Class[] { FileParse.class }).invoke(annotate3d,
452                 new Object[] { new FileParse(getDataName(), type) }));
453         for (SequenceI sq : al.getSequences())
454         {
455           if (sq.getDatasetSequence() != null)
456           {
457             if (sq.getDatasetSequence().getAllPDBEntries() != null)
458             {
459               sq.getDatasetSequence().getAllPDBEntries().clear();
460             }
461           }
462           else
463           {
464             if (sq.getAllPDBEntries() != null)
465             {
466               sq.getAllPDBEntries().clear();
467             }
468           }
469         }
470         replaceAndUpdateChains(rna, al, AlignSeq.DNA, false);
471       }
472     } catch (ClassNotFoundException x)
473     {
474       // ignore classnotfounds - occurs in applet
475     }
476     ;
477   }
478
479   /**
480    * make a friendly ID string.
481    * 
482    * @param dataName
483    * @return truncated dataName to after last '/'
484    */
485   private String safeName(String dataName)
486   {
487     int p = 0;
488     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
489     {
490       dataName = dataName.substring(p + 1);
491     }
492     return dataName;
493   }
494
495   public void makeResidueList()
496   {
497     for (int i = 0; i < chains.size(); i++)
498     {
499       chains.elementAt(i).makeResidueList(visibleChainAnnotation);
500     }
501   }
502
503   public void makeCaBondList()
504   {
505     for (int i = 0; i < chains.size(); i++)
506     {
507       chains.elementAt(i).makeCaBondList();
508     }
509   }
510
511   public PDBChain findChain(String id)
512   {
513     for (int i = 0; i < chains.size(); i++)
514     {
515       if (chains.elementAt(i).id.equals(id))
516       {
517         return chains.elementAt(i);
518       }
519     }
520
521     return null;
522   }
523
524   public void setChargeColours()
525   {
526     for (int i = 0; i < chains.size(); i++)
527     {
528       chains.elementAt(i).setChargeColours();
529     }
530   }
531
532   public void setColours(jalview.schemes.ColourSchemeI cs)
533   {
534     for (int i = 0; i < chains.size(); i++)
535     {
536       chains.elementAt(i).setChainColours(cs);
537     }
538   }
539
540   public void setChainColours()
541   {
542     for (int i = 0; i < chains.size(); i++)
543     {
544       // divide by zero --> infinity --> 255 ;-)
545       chains.elementAt(i).setChainColours(
546               Color.getHSBColor(1.0f / i, .4f, 1.0f));
547     }
548   }
549
550   public static boolean isRNA(SequenceI seq)
551   {
552     for (char c : seq.getSequence())
553     {
554       if ((c != 'A') && (c != 'C') && (c != 'G') && (c != 'U'))
555       {
556         return false;
557       }
558     }
559
560     return true;
561
562   }
563 }