JAL-1942 JAL-1479 refactored SequenceI.getDBRef/SequenceI.setDBRef to SequenceI.getDB...
[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     pdbSequence.addPDBId(entry);
313
314     DBRefEntry sourceDBRef = new DBRefEntry();
315     sourceDBRef.setAccessionId(id);
316     sourceDBRef.setSource(DBRefSource.PDB);
317     sourceDBRef.setStartRes(pdbSequence.getStart());
318     sourceDBRef.setEndRes(pdbSequence.getEnd());
319     pdbSequence.setSourceDBRef(sourceDBRef);
320     // PDBChain objects maintain reference to dataset
321     SequenceI chainseq = pdbSequence.deriveSequence();
322     seqs.addElement(chainseq);
323
324     AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
325
326     if (chainannot != null && visibleChainAnnotation)
327     {
328       for (int ai = 0; ai < chainannot.length; ai++)
329       {
330         chainannot[ai].visible = visibleChainAnnotation;
331         annotations.addElement(chainannot[ai]);
332       }
333     }
334     return chainseq;
335   }
336
337   public static boolean isCalcIdHandled(String calcId)
338   {
339     return calcId != null && (CALC_ID_PREFIX.equals(calcId));
340   }
341
342   public static boolean isCalcIdForFile(AlignmentAnnotation alan,
343           String pdbFile)
344   {
345     return alan.getCalcId() != null
346             && CALC_ID_PREFIX.equals(alan.getCalcId())
347             && pdbFile.equals(alan.getProperty("PDBID"));
348   }
349
350   public static String relocateCalcId(String calcId,
351           Hashtable<String, String> alreadyLoadedPDB) throws Exception
352   {
353     int s = CALC_ID_PREFIX.length(), end = calcId
354             .indexOf(CALC_ID_PREFIX, s);
355     String between = calcId.substring(s, end - 1);
356     return CALC_ID_PREFIX + alreadyLoadedPDB.get(between) + ":"
357             + calcId.substring(end);
358   }
359
360   private void markCalcIds()
361   {
362     for (SequenceI sq : seqs)
363     {
364       if (sq.getAnnotation() != null)
365       {
366         for (AlignmentAnnotation aa : sq.getAnnotation())
367         {
368           String oldId = aa.getCalcId();
369           if (oldId == null)
370           {
371             oldId = "";
372           }
373           aa.setCalcId(CALC_ID_PREFIX);
374           aa.setProperty("PDBID", id);
375           aa.setProperty("oldCalcId", oldId);
376         }
377       }
378     }
379   }
380
381   private void processPdbFileWithJmol(List<SequenceI> prot)
382           throws Exception
383   {
384     try
385     {
386       Class cl = Class.forName("jalview.ext.jmol.PDBFileWithJmol");
387       if (cl != null)
388       {
389         final Constructor constructor = cl
390                 .getConstructor(new Class[] { FileParse.class });
391         final Object[] args = new Object[] { new FileParse(getDataName(),
392                 type) };
393         Object jmf = constructor.newInstance(args);
394         AlignmentI al = new Alignment((SequenceI[]) cl.getMethod(
395                 "getSeqsAsArray", new Class[] {}).invoke(jmf));
396         cl.getMethod("addAnnotations", new Class[] { AlignmentI.class })
397                 .invoke(jmf, al);
398         for (SequenceI sq : al.getSequences())
399         {
400           if (sq.getDatasetSequence() != null)
401           {
402             sq.getDatasetSequence().getAllPDBEntries().clear();
403           }
404           else
405           {
406             sq.getAllPDBEntries().clear();
407           }
408         }
409         replaceAndUpdateChains(prot, al, AlignSeq.PEP, false);
410       }
411     } catch (ClassNotFoundException q)
412     {
413     }
414   }
415
416   private void replaceAndUpdateChains(List<SequenceI> prot, AlignmentI al,
417           String pep, boolean b)
418   {
419     List<List<? extends Object>> replaced = AlignSeq
420             .replaceMatchingSeqsWith(seqs, annotations, prot, al, pep,
421                     false);
422     for (PDBChain ch : chains)
423     {
424       int p = 0;
425       for (SequenceI sq : (List<SequenceI>) replaced.get(0))
426       {
427         p++;
428         if (sq == ch.sequence || sq.getDatasetSequence() == ch.sequence)
429         {
430           p = -p;
431           break;
432         }
433       }
434       if (p < 0)
435       {
436         p = -p - 1;
437         // set shadow entry for chains
438         ch.shadow = (SequenceI) replaced.get(1).get(p);
439         ch.shadowMap = ((AlignSeq) replaced.get(2).get(p))
440                 .getMappingFromS1(false);
441       }
442     }
443   }
444
445   private void processPdbFileWithAnnotate3d(List<SequenceI> rna)
446           throws Exception
447   {
448     // System.out.println("this is a PDB format and RNA sequence");
449     // note: we use reflection here so that the applet can compile and run
450     // without the HTTPClient bits and pieces needed for accessing Annotate3D
451     // web service
452     try
453     {
454       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
455       if (cl != null)
456       {
457         // TODO: use the PDB ID of the structure if one is available, to save
458         // bandwidth and avoid uploading the whole structure to the service
459         Object annotate3d = cl.getConstructor(new Class[] {}).newInstance(
460                 new Object[] {});
461         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
462                 new Class[] { FileParse.class }).invoke(annotate3d,
463                 new Object[] { new FileParse(getDataName(), type) }));
464         for (SequenceI sq : al.getSequences())
465         {
466           if (sq.getDatasetSequence() != null)
467           {
468             if (sq.getDatasetSequence().getAllPDBEntries() != null)
469             {
470               sq.getDatasetSequence().getAllPDBEntries().clear();
471             }
472           }
473           else
474           {
475             if (sq.getAllPDBEntries() != null)
476             {
477               sq.getAllPDBEntries().clear();
478             }
479           }
480         }
481         replaceAndUpdateChains(rna, al, AlignSeq.DNA, false);
482       }
483     } catch (ClassNotFoundException x)
484     {
485       // ignore classnotfounds - occurs in applet
486     }
487     ;
488   }
489
490   /**
491    * make a friendly ID string.
492    * 
493    * @param dataName
494    * @return truncated dataName to after last '/'
495    */
496   private String safeName(String dataName)
497   {
498     int p = 0;
499     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
500     {
501       dataName = dataName.substring(p + 1);
502     }
503     return dataName;
504   }
505
506   public void makeResidueList()
507   {
508     for (int i = 0; i < chains.size(); i++)
509     {
510       chains.elementAt(i).makeResidueList(visibleChainAnnotation);
511     }
512   }
513
514   public void makeCaBondList()
515   {
516     for (int i = 0; i < chains.size(); i++)
517     {
518       chains.elementAt(i).makeCaBondList();
519     }
520   }
521
522   public PDBChain findChain(String id)
523   {
524     for (int i = 0; i < chains.size(); i++)
525     {
526       if (chains.elementAt(i).id.equals(id))
527       {
528         return chains.elementAt(i);
529       }
530     }
531
532     return null;
533   }
534
535   public void setChargeColours()
536   {
537     for (int i = 0; i < chains.size(); i++)
538     {
539       chains.elementAt(i).setChargeColours();
540     }
541   }
542
543   public void setColours(jalview.schemes.ColourSchemeI cs)
544   {
545     for (int i = 0; i < chains.size(); i++)
546     {
547       chains.elementAt(i).setChainColours(cs);
548     }
549   }
550
551   public void setChainColours()
552   {
553     for (int i = 0; i < chains.size(); i++)
554     {
555       // divide by zero --> infinity --> 255 ;-)
556       chains.elementAt(i).setChainColours(
557               Color.getHSBColor(1.0f / i, .4f, 1.0f));
558     }
559   }
560
561   public static boolean isRNA(SequenceI seq)
562   {
563     for (char c : seq.getSequence())
564     {
565       if ((c != 'A') && (c != 'C') && (c != 'G') && (c != 'U'))
566       {
567         return false;
568       }
569     }
570
571     return true;
572
573   }
574 }