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