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