Merge branch 'develop' into trialMerge
[jalview.git] / src / jalview / io / StructureFile.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 jalview.io;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.api.FeatureSettingsModelI;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.DBRefSource;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.PDBEntry.Type;
32 import jalview.datamodel.SequenceI;
33 import jalview.structure.StructureImportSettings;
34
35 import java.awt.Color;
36 import java.io.IOException;
37 import java.lang.reflect.Constructor;
38 import java.util.List;
39 import java.util.Vector;
40
41 import MCview.PDBChain;
42
43 public abstract class StructureFile extends AlignFile
44 {
45
46   private String id;
47
48   public enum StructureFileType
49   {
50     PDB, MMCIF, MMTF
51   };
52
53   private PDBEntry.Type dbRefType;
54
55   /**
56    * set to true to add derived sequence annotations (temp factor read from
57    * file, or computed secondary structure) to the alignment
58    */
59   protected boolean visibleChainAnnotation = false;
60
61   /**
62    * Set true to predict secondary structure (using JMol for protein, Annotate3D
63    * for RNA)
64    */
65   protected boolean predictSecondaryStructure = false;
66
67   /**
68    * Set true (with predictSecondaryStructure=true) to predict secondary
69    * structure using an external service (currently Annotate3D for RNA only)
70    */
71   protected boolean externalSecondaryStructure = false;
72
73   private Vector<PDBChain> chains;
74
75   private boolean pdbIdAvailable;
76
77   public StructureFile(String inFile, DataSourceType sourceType)
78           throws IOException
79   {
80     super(inFile, sourceType);
81   }
82
83   public StructureFile(FileParse fp) throws IOException
84   {
85     super(fp);
86   }
87
88   public void addSettings(boolean addAlignmentAnnotations,
89           boolean predictSecondaryStructure, boolean externalSecStr)
90   {
91     this.visibleChainAnnotation = addAlignmentAnnotations;
92     this.predictSecondaryStructure = predictSecondaryStructure;
93     this.externalSecondaryStructure = externalSecStr;
94   }
95
96   public void xferSettings()
97   {
98     this.visibleChainAnnotation = StructureImportSettings
99             .isVisibleChainAnnotation();
100     this.predictSecondaryStructure = StructureImportSettings
101             .isProcessSecondaryStructure();
102     this.externalSecondaryStructure = StructureImportSettings
103             .isExternalSecondaryStructure();
104
105   }
106
107   public StructureFile(boolean parseImmediately, String dataObject,
108           DataSourceType sourceType) throws IOException
109   {
110     super(parseImmediately, dataObject, sourceType);
111   }
112
113   public StructureFile(boolean a, FileParse fp) throws IOException
114   {
115     super(a, fp);
116   }
117
118   public StructureFile()
119   {
120   }
121
122   protected SequenceI postProcessChain(PDBChain chain)
123   {
124     SequenceI pdbSequence = chain.sequence;
125     pdbSequence.setName(getId() + "|" + pdbSequence.getName());
126     PDBEntry entry = new PDBEntry();
127     entry.setId(getId());
128     entry.setType(getStructureFileType());
129     if (chain.id != null)
130     {
131       entry.setChainCode(chain.id);
132     }
133     if (inFile != null)
134     {
135       entry.setFile(inFile.getAbsolutePath());
136     }
137     else
138     {
139       entry.setFile(getDataName());
140     }
141
142     DBRefEntry sourceDBRef = new DBRefEntry();
143     sourceDBRef.setAccessionId(getId());
144     sourceDBRef.setSource(DBRefSource.PDB);
145     // TODO: specify version for 'PDB' database ref if it is read from a file.
146     // TODO: decide if jalview.io should be creating primary refs!
147     sourceDBRef.setVersion("");
148     pdbSequence.addPDBId(entry);
149     pdbSequence.addDBRef(sourceDBRef);
150     SequenceI chainseq = pdbSequence;
151     seqs.addElement(chainseq);
152     AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
153
154     if (chainannot != null && visibleChainAnnotation)
155     {
156       for (int ai = 0; ai < chainannot.length; ai++)
157       {
158         chainannot[ai].visible = visibleChainAnnotation;
159         annotations.addElement(chainannot[ai]);
160       }
161     }
162     return chainseq;
163   }
164
165   /**
166    * filetype of structure file - default is PDB
167    */
168   String structureFileType = PDBEntry.Type.PDB.toString();
169
170   protected void setStructureFileType(String structureFileType)
171   {
172     this.structureFileType = structureFileType;
173   }
174
175   /**
176    * filetype of last file processed
177    * 
178    * @return
179    */
180   public String getStructureFileType()
181   {
182     return structureFileType;
183   }
184
185   @SuppressWarnings({ "unchecked", "rawtypes" })
186   protected void processPdbFileWithAnnotate3d(List<SequenceI> rna)
187           throws Exception
188   {
189     // System.out.println("this is a PDB format and RNA sequence");
190     // note: we use reflection here so that the applet can compile and run
191     // without the HTTPClient bits and pieces needed for accessing Annotate3D
192     // web service
193     try
194     {
195       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
196       if (cl != null)
197       {
198         // TODO: use the PDB ID of the structure if one is available, to save
199         // bandwidth and avoid uploading the whole structure to the service
200         Object annotate3d = cl.getConstructor(new Class[] {}).newInstance(
201                 new Object[] {});
202         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
203                 new Class[] { FileParse.class }).invoke(annotate3d,
204                 new Object[] { new FileParse(getDataName(), dataSourceType) }));
205         for (SequenceI sq : al.getSequences())
206         {
207           if (sq.getDatasetSequence() != null)
208           {
209             if (sq.getDatasetSequence().getAllPDBEntries() != null)
210             {
211               sq.getDatasetSequence().getAllPDBEntries().clear();
212             }
213           }
214           else
215           {
216             if (sq.getAllPDBEntries() != null)
217             {
218               sq.getAllPDBEntries().clear();
219             }
220           }
221         }
222         replaceAndUpdateChains(rna, al, AlignSeq.DNA, false);
223       }
224     } catch (ClassNotFoundException x)
225     {
226       // ignore classnotfounds - occurs in applet
227     }
228   }
229
230   @SuppressWarnings("unchecked")
231   protected void replaceAndUpdateChains(List<SequenceI> prot,
232           AlignmentI al, String pep, boolean b)
233   {
234     List<List<? extends Object>> replaced = AlignSeq
235             .replaceMatchingSeqsWith(seqs, annotations, prot, al, pep,
236                     false);
237     for (PDBChain ch : getChains())
238     {
239       int p = 0;
240       for (SequenceI sq : (List<SequenceI>) replaced.get(0))
241       {
242         p++;
243         if (sq == ch.sequence || sq.getDatasetSequence() == ch.sequence)
244         {
245           p = -p;
246           break;
247         }
248       }
249       if (p < 0)
250       {
251         p = -p - 1;
252         // set shadow entry for chains
253         ch.shadow = (SequenceI) replaced.get(1).get(p);
254         ch.shadowMap = ((AlignSeq) replaced.get(2).get(p))
255                 .getMappingFromS1(false);
256       }
257     }
258   }
259
260   /**
261    * Predict secondary structure for RNA and/or protein sequences and add as
262    * annotations
263    * 
264    * @param rnaSequences
265    * @param proteinSequences
266    */
267   protected void addSecondaryStructure(List<SequenceI> rnaSequences,
268           List<SequenceI> proteinSequences)
269   {
270     /*
271      * Currently using Annotate3D for RNA, but only if the 'use external
272      * prediction' flag is set
273      */
274     if (externalSecondaryStructure && rnaSequences.size() > 0)
275     {
276       try
277       {
278         processPdbFileWithAnnotate3d(rnaSequences);
279       } catch (Exception x)
280       {
281         System.err.println("Exceptions when dealing with RNA in pdb file");
282         x.printStackTrace();
283
284       }
285     }
286
287     /*
288      * Currently using JMol PDB parser for peptide
289      */
290     if (proteinSequences.size() > 0)
291     {
292       try
293       {
294         processWithJmolParser(proteinSequences);
295       } catch (Exception x)
296       {
297         System.err
298                 .println("Exceptions from Jmol when processing data in pdb file");
299         x.printStackTrace();
300       }
301     }
302   }
303
304   @SuppressWarnings({ "unchecked", "rawtypes" })
305   private void processWithJmolParser(List<SequenceI> prot) throws Exception
306   {
307     try
308     {
309
310       Class cl = Class.forName("jalview.ext.jmol.JmolParser");
311       if (cl != null)
312       {
313         final Constructor constructor = cl.getConstructor(new Class[] {FileParse.class });
314         final Object[] args = new Object[] { new FileParse(getDataName(), dataSourceType) };
315
316         StructureImportSettings.setShowSeqFeatures(false);
317         StructureImportSettings.setVisibleChainAnnotation(false);
318         StructureImportSettings
319                 .setProcessSecondaryStructure(predictSecondaryStructure);
320         StructureImportSettings
321                 .setExternalSecondaryStructure(externalSecondaryStructure);
322         Object jmf = constructor.newInstance(args);
323         AlignmentI al = new Alignment((SequenceI[]) cl.getMethod(
324                 "getSeqsAsArray", new Class[] {}).invoke(jmf));
325         cl.getMethod("addAnnotations", new Class[] { AlignmentI.class })
326                 .invoke(jmf, al);
327         for (SequenceI sq : al.getSequences())
328         {
329           if (sq.getDatasetSequence() != null)
330           {
331             sq.getDatasetSequence().getAllPDBEntries().clear();
332           }
333           else
334           {
335             sq.getAllPDBEntries().clear();
336           }
337         }
338         replaceAndUpdateChains(prot, al, AlignSeq.PEP, false);
339       }
340     } catch (ClassNotFoundException q)
341     {
342     }
343     StructureImportSettings.setShowSeqFeatures(true);
344   }
345
346   public PDBChain findChain(String id) throws Exception
347   {
348     for (PDBChain chain : getChains())
349     {
350       if (chain.id.equals(id))
351       {
352         return chain;
353       }
354     }
355     throw new Exception("PDB chain not Found!");
356   }
357
358   public void makeResidueList()
359   {
360     for (PDBChain chain : getChains())
361     {
362       chain.makeResidueList(visibleChainAnnotation);
363     }
364   }
365
366   public void makeCaBondList()
367   {
368     for (PDBChain chain : getChains())
369     {
370       chain.makeCaBondList();
371     }
372   }
373
374   public void setChargeColours()
375   {
376     for (PDBChain chain : getChains())
377     {
378       chain.setChargeColours();
379     }
380   }
381
382   public void setColours(jalview.schemes.ColourSchemeI cs)
383   {
384     for (PDBChain chain : getChains())
385     {
386       chain.setChainColours(cs);
387     }
388   }
389
390   public void setChainColours()
391   {
392     int i = 0;
393     for (PDBChain chain : getChains())
394     {
395       chain.setChainColours(Color.getHSBColor(1.0f / i++, .4f, 1.0f));
396     }
397   }
398
399   public static boolean isRNA(SequenceI seq)
400   {
401     for (char c : seq.getSequence())
402     {
403       if ((c != 'A') && (c != 'C') && (c != 'G') && (c != 'U'))
404       {
405         return false;
406       }
407     }
408     return true;
409   }
410
411   /**
412    * make a friendly ID string.
413    * 
414    * @param dataName
415    * @return truncated dataName to after last '/'
416    */
417   protected String safeName(String dataName)
418   {
419     int p = 0;
420     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
421     {
422       dataName = dataName.substring(p + 1);
423     }
424     return dataName;
425   }
426
427   public String getId()
428   {
429     return id;
430   }
431
432   public void setId(String id)
433   {
434     this.id = id;
435   }
436
437   public Vector<PDBChain> getChains()
438   {
439     return chains;
440   }
441
442   public void setChains(Vector<PDBChain> chains)
443   {
444     this.chains = chains;
445   }
446
447   public Type getDbRefType()
448   {
449     return dbRefType;
450   }
451
452   public void setDbRefType(String dbRefType)
453   {
454     this.dbRefType = Type.getType(dbRefType);
455   }
456
457   public void setDbRefType(Type dbRefType)
458   {
459     this.dbRefType = dbRefType;
460   }
461
462   /**
463    * Returns a descriptor for suitable feature display settings with
464    * <ul>
465    * <li>ResNums or insertions features visible</li>
466    * <li>insertions features coloured red</li>
467    * <li>ResNum features coloured by label</li>
468    * <li>Insertions displayed above (on top of) ResNums</li>
469    * </ul>
470    */
471   @Override
472   public FeatureSettingsModelI getFeatureColourScheme()
473   {
474     return new PDBFeatureSettings();
475   }
476
477   /**
478    * Answers true if the structure file has a PDBId
479    * 
480    * @return
481    */
482   public boolean isPPDBIdAvailable()
483   {
484     return pdbIdAvailable;
485   }
486
487   public void setPDBIdAvailable(boolean pdbIdAvailable)
488   {
489     this.pdbIdAvailable = pdbIdAvailable;
490   }
491
492   public static boolean isStructureFile(String fileType)
493   {
494     if (fileType == null)
495     {
496       return false;
497     }
498     for (StructureFileType sfType : StructureFileType.values())
499     {
500       if (sfType.name().equalsIgnoreCase(fileType))
501       {
502         return true;
503       }
504     }
505     return false;
506   }
507 }