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