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