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