1dbfdefeb8d2e92e58dd734fc16541522a9278fd
[jalview.git] / src / jalview / io / FormatAdapter.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 jalview.api.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.util.Comparison;
34
35 import java.io.IOException;
36
37 /**
38  * Additional formatting methods used by the application in a number of places.
39  * 
40  * @author $author$
41  * @version $Revision$
42  */
43 public class FormatAdapter extends AppletFormatAdapter
44 {
45   public FormatAdapter(AlignmentViewPanel viewpanel)
46   {
47     super(viewpanel);
48     init();
49   }
50
51   public FormatAdapter()
52   {
53     super();
54     init();
55   }
56
57   public FormatAdapter(AlignmentViewPanel alignPanel,
58           AlignExportSettingI settings)
59   {
60     super(alignPanel, settings);
61   }
62
63   private void init()
64   {
65     if (jalview.bin.Cache.getDefault("STRUCT_FROM_PDB", true))
66     {
67       annotFromStructure = jalview.bin.Cache.getDefault("ADD_TEMPFACT_ANN",
68               true);
69       localSecondaryStruct = jalview.bin.Cache.getDefault("ADD_SS_ANN",
70               true);
71       serviceSecondaryStruct = jalview.bin.Cache.getDefault("USE_RNAVIEW",
72               true);
73     }
74     else
75     {
76       // disable all PDB annotation options
77       annotFromStructure = false;
78       localSecondaryStruct = false;
79       serviceSecondaryStruct = false;
80     }
81   }
82
83   public String formatSequences(FileFormatI format, SequenceI[] seqs,
84           String[] omitHiddenColumns, int[] exportRange)
85   {
86
87     return formatSequences(format,
88             replaceStrings(seqs, omitHiddenColumns, exportRange));
89   }
90
91   /**
92    * create sequences with each sequence string replaced with the one given in
93    * omitHiddenCOlumns
94    * 
95    * @param seqs
96    * @param omitHiddenColumns
97    * @return new sequences
98    */
99   public SequenceI[] replaceStrings(SequenceI[] seqs,
100           String[] omitHiddenColumns, int[] startEnd)
101   {
102     if (omitHiddenColumns != null)
103     {
104       SequenceI[] tmp = new SequenceI[seqs.length];
105
106       int startRes;
107       int endRes;
108       int startIndex;
109       int endIndex;
110       for (int i = 0; i < seqs.length; i++)
111       {
112         startRes = seqs[i].getStart();
113         endRes = seqs[i].getEnd();
114         if (startEnd != null)
115         {
116           startIndex = startEnd[0];
117           endIndex = startEnd[1];
118           // get first non-gaped residue start position
119           while (Comparison.isGap(seqs[i]
120                   .getCharAt(startIndex)) && startIndex < endIndex)
121           {
122             startIndex++;
123           }
124
125           // get last non-gaped residue end position
126           while (Comparison.isGap(seqs[i].getCharAt(endIndex))
127                   && endIndex > startIndex)
128           {
129             endIndex--;
130           }
131
132           startRes = seqs[i].findPosition(startIndex);
133           endRes = seqs[i].findPosition(endIndex);
134         }
135
136         tmp[i] = new Sequence(seqs[i].getName(), omitHiddenColumns[i],
137                 startRes, endRes);
138         tmp[i].setDescription(seqs[i].getDescription());
139       }
140       seqs = tmp;
141     }
142     return seqs;
143   }
144
145   /**
146    * Format a vector of sequences as a flat alignment file. TODO: allow caller
147    * to detect errors and warnings encountered when generating output
148    * 
149    * 
150    * @param format
151    * @param seqs
152    *          vector of sequences to write
153    * 
154    * @return String containing sequences in desired format
155    */
156   public String formatSequences(FileFormatI format, SequenceI[] seqs)
157   {
158     //
159     // try
160     // {
161     boolean withSuffix = getCacheSuffixDefault(format);
162     return format.getAlignmentFile().print(seqs, withSuffix);
163       // null;
164       //
165       // if (format.equalsIgnoreCase("FASTA"))
166       // {
167       // afile = new FastaFile();
168       // afile.addJVSuffix(jalview.bin.Cache.getDefault("FASTA_JVSUFFIX",
169       // true));
170       // }
171       // else if (format.equalsIgnoreCase("MSF"))
172       // {
173       // afile = new MSFfile();
174       // afile.addJVSuffix(jalview.bin.Cache
175       // .getDefault("MSF_JVSUFFIX", true));
176       // }
177       // else if (format.equalsIgnoreCase("PileUp"))
178       // {
179       // afile = new PileUpfile();
180       // afile.addJVSuffix(jalview.bin.Cache.getDefault("PILEUP_JVSUFFIX",
181       // true));
182       // }
183       // else if (format.equalsIgnoreCase("CLUSTAL"))
184       // {
185       // afile = new ClustalFile();
186       // afile.addJVSuffix(jalview.bin.Cache.getDefault("CLUSTAL_JVSUFFIX",
187       // true));
188       // }
189       // else if (format.equalsIgnoreCase("BLC"))
190       // {
191       // afile = new BLCFile();
192       // afile.addJVSuffix(jalview.bin.Cache
193       // .getDefault("BLC_JVSUFFIX", true));
194       // }
195       // else if (format.equalsIgnoreCase("PIR"))
196       // {
197       // afile = new PIRFile();
198       // afile.addJVSuffix(jalview.bin.Cache
199       // .getDefault("PIR_JVSUFFIX", true));
200       // }
201       // else if (format.equalsIgnoreCase("PFAM"))
202       // {
203       // afile = new PfamFile();
204       // afile.addJVSuffix(jalview.bin.Cache.getDefault("PFAM_JVSUFFIX",
205       // true));
206       // }
207       // /*
208       // * amsa is not supported by this function - it requires an alignment
209       // * rather than a sequence vector else if
210       // (format.equalsIgnoreCase("AMSA"))
211       // * { afile = new AMSAFile(); afile.addJVSuffix(
212       // * jalview.bin.Cache.getDefault("AMSA_JVSUFFIX", true)); }
213       // */
214
215 //      afile.setSeqs(seqs);
216 //      String afileresp = afile.print();
217 //      if (afile.hasWarningMessage())
218 //      {
219 //        System.err.println("Warning raised when writing as " + format
220 //                + " : " + afile.getWarningMessage());
221 //      }
222 //      return afileresp;
223 //    } catch (Exception e)
224 //    {
225 //      System.err.println("Failed to write alignment as a '" + format
226 //              + "' file\n");
227 //      e.printStackTrace();
228 //    }
229 //
230 //    return null;
231   }
232
233   public boolean getCacheSuffixDefault(FileFormatI format)
234   {
235     return Cache.getDefault(format.toString() + "_JVSUFFIX", true);
236   }
237
238   public String formatSequences(FileFormatI format, AlignmentI alignment,
239           String[] omitHidden, int[] exportRange, ColumnSelection colSel)
240   {
241     return formatSequences(format, alignment, omitHidden, exportRange,
242             getCacheSuffixDefault(format), colSel, null);
243   }
244
245   /**
246    * hack function to replace seuqences with visible sequence strings before
247    * generating a string of the alignment in the given format.
248    * 
249    * @param format
250    * @param alignment
251    * @param omitHidden
252    *          sequence strings to write out in order of sequences in alignment
253    * @param colSel
254    *          defines hidden columns that are edited out of annotation
255    * @return string representation of the alignment formatted as format
256    */
257   public String formatSequences(FileFormatI format, AlignmentI alignment,
258           String[] omitHidden, int[] exportRange, boolean suffix,
259           ColumnSelection colSel)
260   {
261     return formatSequences(format, alignment, omitHidden, exportRange,
262             suffix, colSel, null);
263   }
264
265   public String formatSequences(FileFormatI format, AlignmentI alignment,
266           String[] omitHidden, int[] exportRange, boolean suffix,
267           ColumnSelection colSel, SequenceGroup selgp)
268   {
269     if (omitHidden != null)
270     {
271       // TODO consider using AlignmentView to prune to visible region
272       // TODO prune sequence annotation and groups to visible region
273       // TODO: JAL-1486 - set start and end for output correctly. basically,
274       // AlignmentView.getVisibleContigs does this.
275       Alignment alv = new Alignment(replaceStrings(
276               alignment.getSequencesArray(), omitHidden, exportRange));
277       AlignmentAnnotation[] ala = alignment.getAlignmentAnnotation();
278       if (ala != null)
279       {
280         for (int i = 0; i < ala.length; i++)
281         {
282           AlignmentAnnotation na = new AlignmentAnnotation(ala[i]);
283           if (selgp != null)
284           {
285             colSel.makeVisibleAnnotation(selgp.getStartRes(),
286                     selgp.getEndRes(), na);
287           }
288           else
289           {
290             colSel.makeVisibleAnnotation(na);
291           }
292           alv.addAnnotation(na);
293         }
294       }
295       return this.formatSequences(format, alv, suffix);
296     }
297     return this.formatSequences(format, alignment, suffix);
298   }
299
300   @Override
301   public AlignmentI readFile(String file, DataSourceType sourceType,
302           FileFormatI fileFormat) throws IOException
303   {
304     AlignmentI al = super.readFile(file, sourceType, fileFormat);
305     return al;
306   }
307
308   @Override
309   public AlignmentI readFromFile(FileParse source, FileFormatI format)
310           throws IOException
311   {
312     AlignmentI al = super.readFromFile(source, format);
313     return al;
314   }
315
316   /**
317    * Create a flat file representation of a given view or selected region of a
318    * view
319    * 
320    * @param format
321    * @param ap
322    *          alignment panel originating the view
323    * @return String containing flat file
324    */
325   public String formatSequences(FileFormatI format, AlignmentViewPanel ap,
326           boolean selectedOnly)
327   {
328     return formatSequences(format, getCacheSuffixDefault(format), ap,
329             selectedOnly);
330   }
331
332   public AlignmentI readFromFile(AlignmentFileI source, FileFormatI format)
333           throws IOException
334   {
335     FileParse fp = new FileParse(source.getInFile(),
336             source.getDataSourceType());
337     return readFromFile(fp, format);
338   }
339
340 }