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