JAL-2178 remove duplicate Uniprot db source
[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     pdbSequence.setSourceDBRef(sourceDBRef);
121     pdbSequence.addPDBId(entry);
122     pdbSequence.addDBRef(sourceDBRef);
123     SequenceI chainseq = pdbSequence;
124     seqs.addElement(chainseq);
125     AlignmentAnnotation[] chainannot = chainseq.getAnnotation();
126
127     if (chainannot != null && visibleChainAnnotation)
128     {
129       for (int ai = 0; ai < chainannot.length; ai++)
130       {
131         chainannot[ai].visible = visibleChainAnnotation;
132         annotations.addElement(chainannot[ai]);
133       }
134     }
135     return chainseq;
136   }
137
138   @SuppressWarnings({ "unchecked", "rawtypes" })
139   protected void processPdbFileWithAnnotate3d(List<SequenceI> rna)
140           throws Exception
141   {
142     // System.out.println("this is a PDB format and RNA sequence");
143     // note: we use reflection here so that the applet can compile and run
144     // without the HTTPClient bits and pieces needed for accessing Annotate3D
145     // web service
146     try
147     {
148       Class cl = Class.forName("jalview.ws.jws1.Annotate3D");
149       if (cl != null)
150       {
151         // TODO: use the PDB ID of the structure if one is available, to save
152         // bandwidth and avoid uploading the whole structure to the service
153         Object annotate3d = cl.getConstructor(new Class[] {}).newInstance(
154                 new Object[] {});
155         AlignmentI al = ((AlignmentI) cl.getMethod("getRNAMLFor",
156                 new Class[] { FileParse.class }).invoke(annotate3d,
157                 new Object[] { new FileParse(getDataName(), type) }));
158         for (SequenceI sq : al.getSequences())
159         {
160           if (sq.getDatasetSequence() != null)
161           {
162             if (sq.getDatasetSequence().getAllPDBEntries() != null)
163             {
164               sq.getDatasetSequence().getAllPDBEntries().clear();
165             }
166           }
167           else
168           {
169             if (sq.getAllPDBEntries() != null)
170             {
171               sq.getAllPDBEntries().clear();
172             }
173           }
174         }
175         replaceAndUpdateChains(rna, al, AlignSeq.DNA, false);
176       }
177     } catch (ClassNotFoundException x)
178     {
179       // ignore classnotfounds - occurs in applet
180     }
181   }
182
183   @SuppressWarnings("unchecked")
184   protected void replaceAndUpdateChains(List<SequenceI> prot,
185           AlignmentI al, String pep, boolean b)
186   {
187     List<List<? extends Object>> replaced = AlignSeq
188             .replaceMatchingSeqsWith(seqs, annotations, prot, al, pep,
189                     false);
190     for (PDBChain ch : getChains())
191     {
192       int p = 0;
193       for (SequenceI sq : (List<SequenceI>) replaced.get(0))
194       {
195         p++;
196         if (sq == ch.sequence || sq.getDatasetSequence() == ch.sequence)
197         {
198           p = -p;
199           break;
200         }
201       }
202       if (p < 0)
203       {
204         p = -p - 1;
205         // set shadow entry for chains
206         ch.shadow = (SequenceI) replaced.get(1).get(p);
207         ch.shadowMap = ((AlignSeq) replaced.get(2).get(p))
208                 .getMappingFromS1(false);
209       }
210     }
211   }
212
213   /**
214    * Predict secondary structure for RNA and/or protein sequences and add as
215    * annotations
216    * 
217    * @param rnaSequences
218    * @param proteinSequences
219    */
220   protected void addSecondaryStructure(List<SequenceI> rnaSequences,
221           List<SequenceI> proteinSequences)
222   {
223     /*
224      * Currently using Annotate3D for RNA, but only if the 'use external
225      * prediction' flag is set
226      */
227     if (externalSecondaryStructure && rnaSequences.size() > 0)
228     {
229       try
230       {
231         processPdbFileWithAnnotate3d(rnaSequences);
232       } catch (Exception x)
233       {
234         System.err.println("Exceptions when dealing with RNA in pdb file");
235         x.printStackTrace();
236
237       }
238     }
239
240     /*
241      * Currently using JMol PDB parser for peptide
242      */
243     if (proteinSequences.size() > 0)
244     {
245       try
246       {
247         processWithJmolParser(proteinSequences);
248       } catch (Exception x)
249       {
250         System.err
251                 .println("Exceptions from Jmol when processing data in pdb file");
252         x.printStackTrace();
253       }
254     }
255   }
256
257   @SuppressWarnings({ "unchecked", "rawtypes" })
258   private void processWithJmolParser(List<SequenceI> prot) throws Exception
259   {
260     try
261     {
262
263       Class cl = Class.forName("jalview.ext.jmol.JmolParser");
264       if (cl != null)
265       {
266         final Constructor constructor = cl.getConstructor(new Class[] {
267             boolean.class, boolean.class, boolean.class, FileParse.class });
268         final Object[] args = new Object[] { visibleChainAnnotation,
269             predictSecondaryStructure, externalSecondaryStructure,
270             new FileParse(getDataName(), type) };
271
272         StructureImportSettings.setShowSeqFeatures(false);
273         StructureImportSettings.setVisibleChainAnnotation(false);
274         StructureImportSettings
275                 .setProcessSecondaryStructure(predictSecondaryStructure);
276         StructureImportSettings
277                 .setExternalSecondaryStructure(externalSecondaryStructure);
278         Object jmf = constructor.newInstance(args);
279         AlignmentI al = new Alignment((SequenceI[]) cl.getMethod(
280                 "getSeqsAsArray", new Class[] {}).invoke(jmf));
281         cl.getMethod("addAnnotations", new Class[] { AlignmentI.class })
282                 .invoke(jmf, al);
283         for (SequenceI sq : al.getSequences())
284         {
285           if (sq.getDatasetSequence() != null)
286           {
287             sq.getDatasetSequence().getAllPDBEntries().clear();
288           }
289           else
290           {
291             sq.getAllPDBEntries().clear();
292           }
293         }
294         replaceAndUpdateChains(prot, al, AlignSeq.PEP, false);
295       }
296     } catch (ClassNotFoundException q)
297     {
298     }
299     StructureImportSettings.setShowSeqFeatures(true);
300   }
301
302   public PDBChain findChain(String id) throws Exception
303   {
304     for (PDBChain chain : getChains())
305     {
306       if (chain.id.equals(id))
307       {
308         return chain;
309       }
310     }
311     throw new Exception("PDB chain not Found!");
312   }
313
314   public void makeResidueList()
315   {
316     for (PDBChain chain : getChains())
317     {
318       chain.makeResidueList(visibleChainAnnotation);
319     }
320   }
321
322   public void makeCaBondList()
323   {
324     for (PDBChain chain : getChains())
325     {
326       chain.makeCaBondList();
327     }
328   }
329
330   public void setChargeColours()
331   {
332     for (PDBChain chain : getChains())
333     {
334       chain.setChargeColours();
335     }
336   }
337
338   public void setColours(jalview.schemes.ColourSchemeI cs)
339   {
340     for (PDBChain chain : getChains())
341     {
342       chain.setChainColours(cs);
343     }
344   }
345
346   public void setChainColours()
347   {
348     int i = 0;
349     for (PDBChain chain : getChains())
350     {
351       chain.setChainColours(Color.getHSBColor(1.0f / i++, .4f, 1.0f));
352     }
353   }
354
355   public static boolean isRNA(SequenceI seq)
356   {
357     for (char c : seq.getSequence())
358     {
359       if ((c != 'A') && (c != 'C') && (c != 'G') && (c != 'U'))
360       {
361         return false;
362       }
363     }
364     return true;
365   }
366
367   /**
368    * make a friendly ID string.
369    * 
370    * @param dataName
371    * @return truncated dataName to after last '/'
372    */
373   protected String safeName(String dataName)
374   {
375     int p = 0;
376     while ((p = dataName.indexOf("/")) > -1 && p < dataName.length())
377     {
378       dataName = dataName.substring(p + 1);
379     }
380     return dataName;
381   }
382
383   public String getId()
384   {
385     return id;
386   }
387
388   public void setId(String id)
389   {
390     this.id = id;
391   }
392
393   public Vector<PDBChain> getChains()
394   {
395     return chains;
396   }
397
398   public void setChains(Vector<PDBChain> chains)
399   {
400     this.chains = chains;
401   }
402
403   public Type getDbRefType()
404   {
405     return dbRefType;
406   }
407
408   public void setDbRefType(String dbRefType)
409   {
410     this.dbRefType = Type.valueOf(dbRefType);
411   }
412
413   public void setDbRefType(Type dbRefType)
414   {
415     this.dbRefType = dbRefType;
416   }
417
418   /**
419    * Returns a descriptor for suitable feature display settings with
420    * <ul>
421    * <li>ResNums or insertions features visible</li>
422    * <li>insertions features coloured red</li>
423    * <li>ResNum features coloured by label</li>
424    * <li>Insertions displayed above (on top of) ResNums</li>
425    * </ul>
426    */
427   @Override
428   public FeatureSettingsModelI getFeatureColourScheme()
429   {
430     return new PDBFeatureSettings();
431   }
432 }