JAL-1824 updated caching procedure for pdb entries. Also refactored getPDBEntry metho...
[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, boolean predictSecondaryStructure,
67           boolean externalSecStr)
68   {
69     super();
70     this.visibleChainAnnotation = addAlignmentAnnotations;
71     this.predictSecondaryStructure = predictSecondaryStructure;
72     this.externalSecondaryStructure = externalSecStr;
73   }
74
75   public PDBfile(boolean addAlignmentAnnotations, boolean predictSecondaryStructure,
76           boolean externalSecStr, String file, String protocol)
77           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, boolean predictSecondaryStructure,
87           boolean externalSecStr, FileParse source) throws IOException
88   {
89     super(false, source);
90     this.visibleChainAnnotation = addAlignmentAnnotations;
91     this.predictSecondaryStructure = predictSecondaryStructure;
92     this.externalSecondaryStructure = externalSecStr;
93     doParse();
94   }
95
96   public String print()
97   {
98     return null;
99   }
100
101   public void parse() throws IOException
102   {
103     // TODO set the filename sensibly - try using data source name.
104     id = safeName(getDataName());
105
106     chains = new Vector<PDBChain>();
107     List<SequenceI> rna = new ArrayList<SequenceI>();
108     List<SequenceI> prot = new ArrayList<SequenceI>();
109     PDBChain tmpchain;
110     String line = null;
111     boolean modelFlag = false;
112     boolean terFlag = false;
113     String lastID = "";
114
115     int indexx = 0;
116     String atomnam = null;
117     try
118     {
119       while ((line = nextLine()) != null)
120       {
121         if (line.indexOf("HEADER") == 0)
122         {
123           if (line.length() > 62)
124           {
125             String tid;
126             if (line.length() > 67)
127             {
128               tid = line.substring(62, 67).trim();
129             }
130             else
131             {
132               tid = line.substring(62).trim();
133             }
134             if (tid.length() > 0)
135             {
136               id = tid;
137             }
138             continue;
139           }
140         }
141         // Were we to do anything with SEQRES - we start it here
142         if (line.indexOf("SEQRES") == 0)
143         {
144         }
145
146         if (line.indexOf("MODEL") == 0)
147         {
148           modelFlag = true;
149         }
150
151         if (line.indexOf("TER") == 0)
152         {
153           terFlag = true;
154         }
155
156         if (modelFlag && line.indexOf("ENDMDL") == 0)
157         {
158           break;
159         }
160         if (line.indexOf("ATOM") == 0
161                 || (line.indexOf("HETATM") == 0 && !terFlag))
162         {
163           terFlag = false;
164
165           // Jalview is only interested in CA bonds????
166           atomnam = line.substring(12, 15).trim();
167           if (!atomnam.equals("CA") && !atomnam.equals("P"))
168           {
169             continue;
170           }
171
172           Atom tmpatom = new Atom(line);
173           tmpchain = findChain(tmpatom.chain);
174           if (tmpchain != null)
175           {
176             if (tmpatom.resNumIns.trim().equals(lastID))
177             {
178               // phosphorylated protein - seen both CA and P..
179               continue;
180             }
181             tmpchain.atoms.addElement(tmpatom);
182           }
183           else
184           {
185             tmpchain = new PDBChain(id, tmpatom.chain);
186             chains.addElement(tmpchain);
187             tmpchain.atoms.addElement(tmpatom);
188           }
189           lastID = tmpatom.resNumIns.trim();
190         }
191         index++;
192       }
193
194       makeResidueList();
195       makeCaBondList();
196
197       if (id == null)
198       {
199         id = inFile.getName();
200       }
201       for (PDBChain chain : chains)
202       {
203         SequenceI chainseq = postProcessChain(chain);
204         if (isRNA(chainseq))
205         {
206           rna.add(chainseq);
207         }
208         else
209         {
210           prot.add(chainseq);
211         }
212       }
213       if (predictSecondaryStructure)
214       {
215         predictSecondaryStructure(rna, prot);
216       }
217     } catch (OutOfMemoryError er)
218     {
219       System.out.println("OUT OF MEMORY LOADING PDB FILE");
220       throw new IOException(
221               MessageManager
222                       .getString("exception.outofmemory_loading_pdb_file"));
223     } catch (NumberFormatException ex)
224     {
225       if (line != null)
226       {
227         System.err.println("Couldn't read number from line:");
228         System.err.println(line);
229       }
230     }
231     markCalcIds();
232   }
233
234   /**
235    * Predict secondary structure for RNA and/or protein sequences and add as
236    * annotations
237    * 
238    * @param rnaSequences
239    * @param proteinSequences
240    */
241   protected void predictSecondaryStructure(List<SequenceI> rnaSequences,
242           List<SequenceI> proteinSequences)
243   {
244     /*
245      * Currently using Annotate3D for RNA, but only if the 'use external
246      * prediction' flag is set
247      */
248     if (externalSecondaryStructure && rnaSequences.size() > 0)
249     {
250       try
251       {
252         processPdbFileWithAnnotate3d(rnaSequences);
253       } catch (Exception x)
254       {
255         System.err
256                 .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.indexOf(CALC_ID_PREFIX, s);
343     String between = calcId.substring(s, end - 1);
344     return CALC_ID_PREFIX + alreadyLoadedPDB.get(between) + ":"
345             + calcId.substring(end);
346   }
347
348   private void markCalcIds()
349   {
350     for (SequenceI sq : seqs)
351     {
352       if (sq.getAnnotation() != null)
353       {
354         for (AlignmentAnnotation aa : sq.getAnnotation())
355         {
356           String oldId = aa.getCalcId();
357           if (oldId == null)
358           {
359             oldId = "";
360           }
361           aa.setCalcId(CALC_ID_PREFIX);
362           aa.setProperty("PDBID", id);
363           aa.setProperty("oldCalcId", oldId);
364         }
365       }
366     }
367   }
368
369   private void processPdbFileWithJmol(List<SequenceI> prot)
370           throws Exception
371   {
372     try
373     {
374       Class cl = Class.forName("jalview.ext.jmol.PDBFileWithJmol");
375       if (cl != null)
376       {
377         final Constructor constructor = cl.getConstructor(new Class[]
378         { FileParse.class });
379         final Object[] args = new Object[]
380         { new FileParse(getDataName(), type) };
381         Object jmf = constructor.newInstance(args);
382         AlignmentI al = new Alignment((SequenceI[]) cl.getMethod(
383                 "getSeqsAsArray", new Class[]
384                 {}).invoke(jmf));
385         cl.getMethod("addAnnotations", new Class[]
386         { AlignmentI.class }).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,
406           AlignmentI al, 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[]
449         {}).newInstance(new Object[]
450         {});
451         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
452                 new Class[]
453                 { FileParse.class }).invoke(annotate3d, new Object[]
454         { new FileParse(getDataName(), type) }));
455         for (SequenceI sq : al.getSequences())
456         {
457           if (sq.getDatasetSequence() != null)
458           {
459             if (sq.getDatasetSequence().getAllPDBEntries() != null)
460             {
461               sq.getDatasetSequence().getAllPDBEntries().clear();
462             }
463           }
464           else
465           {
466             if (sq.getAllPDBEntries() != null)
467             {
468               sq.getAllPDBEntries().clear();
469             }
470           }
471         }
472         replaceAndUpdateChains(rna, al, AlignSeq.DNA, false);
473       }
474     } catch (ClassNotFoundException x)
475     {
476       // ignore classnotfounds - occurs in applet
477     }
478     ;
479   }
480
481   /**
482    * make a friendly ID string.
483    * 
484    * @param dataName
485    * @return truncated dataName to after last '/'
486    */
487   private String safeName(String dataName)
488   {
489     int p = 0;
490     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
491     {
492       dataName = dataName.substring(p + 1);
493     }
494     return dataName;
495   }
496
497   public void makeResidueList()
498   {
499     for (int i = 0; i < chains.size(); i++)
500     {
501       chains.elementAt(i).makeResidueList(visibleChainAnnotation);
502     }
503   }
504
505   public void makeCaBondList()
506   {
507     for (int i = 0; i < chains.size(); i++)
508     {
509       chains.elementAt(i).makeCaBondList();
510     }
511   }
512
513   public PDBChain findChain(String id)
514   {
515     for (int i = 0; i < chains.size(); i++)
516     {
517       if (chains.elementAt(i).id.equals(id))
518       {
519         return chains.elementAt(i);
520       }
521     }
522
523     return null;
524   }
525
526   public void setChargeColours()
527   {
528     for (int i = 0; i < chains.size(); i++)
529     {
530       chains.elementAt(i).setChargeColours();
531     }
532   }
533
534   public void setColours(jalview.schemes.ColourSchemeI cs)
535   {
536     for (int i = 0; i < chains.size(); i++)
537     {
538       chains.elementAt(i).setChainColours(cs);
539     }
540   }
541
542   public void setChainColours()
543   {
544     for (int i = 0; i < chains.size(); i++)
545     {
546       // divide by zero --> infinity --> 255 ;-)
547       chains.elementAt(i).setChainColours(
548               Color.getHSBColor(1.0f / i, .4f, 1.0f));
549     }
550   }
551
552   public static boolean isRNA(SequenceI seq)
553   {
554     for (char c : seq.getSequence())
555     {
556       if ((c != 'A') && (c != 'C') && (c != 'G') && (c != 'U'))
557       {
558         return false;
559       }
560     }
561
562     return true;
563
564   }
565 }