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