JAL-1486 fixed flatfile output of visible region for consensus sequence
[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.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32
33 /**
34  * Additional formatting methods used by the application in a number of places.
35  * 
36  * @author $author$
37  * @version $Revision$
38  */
39 public class FormatAdapter extends AppletFormatAdapter
40 {
41   public FormatAdapter(AlignmentViewPanel viewpanel)
42   {
43     super(viewpanel);
44     init();
45   }
46
47   public FormatAdapter()
48   {
49     super();
50     init();
51   }
52
53   public FormatAdapter(AlignmentViewPanel alignPanel,
54           AlignExportSettingI settings)
55   {
56     super(alignPanel, settings);
57   }
58
59   private void init()
60   {
61     if (jalview.bin.Cache.getDefault("STRUCT_FROM_PDB", true))
62     {
63       annotFromStructure = jalview.bin.Cache.getDefault("ADD_TEMPFACT_ANN",
64               true);
65       localSecondaryStruct = jalview.bin.Cache.getDefault("ADD_SS_ANN",
66             true);
67     serviceSecondaryStruct = jalview.bin.Cache.getDefault("USE_RNAVIEW",
68             true);
69     }
70     else
71     {
72       // disable all PDB annotation options
73       annotFromStructure = false;
74       localSecondaryStruct = false;
75       serviceSecondaryStruct = false;
76     }
77   }
78
79   public String formatSequences(String format, SequenceI[] seqs,
80           String[] omitHiddenColumns, int[] exportRange)
81   {
82
83     return formatSequences(format,
84             replaceStrings(seqs, omitHiddenColumns, exportRange));
85   }
86
87   /**
88    * create sequences with each sequence string replaced with the one given in
89    * omitHiddenCOlumns
90    * 
91    * @param seqs
92    * @param omitHiddenColumns
93    * @return new sequences
94    */
95   public SequenceI[] replaceStrings(SequenceI[] seqs,
96           String[] omitHiddenColumns, int[] startEnd)
97   {
98     if (omitHiddenColumns != null)
99     {
100       SequenceI[] tmp = new SequenceI[seqs.length];
101
102       int startRes;
103       int endRes;
104       int startIndex;
105       int endIndex;
106       for (int i = 0; i < seqs.length; i++)
107       {
108         startRes = seqs[i].getStart();
109         endRes = seqs[i].getEnd();
110
111
112         if (startEnd != null)
113         {
114           startIndex = startEnd[0];
115           endIndex = startEnd[1];
116           // get first non-gaped residue start position
117           while (jalview.util.Comparison.isGap(seqs[i]
118                   .getCharAt(startIndex)) && startIndex < endIndex)
119           {
120             startIndex++;
121           }
122
123           // get last non-gaped residue end position
124           while (jalview.util.Comparison.isGap(seqs[i].getCharAt(endIndex))
125                   && endIndex > startIndex)
126           {
127             endIndex--;
128           }
129
130           startRes = seqs[i].findPosition(startIndex);
131           startRes = seqs[i].getStart() > 1 ? startRes - seqs[i].getStart()
132                   : startRes;
133           endRes = seqs[i].findPosition(endIndex) - seqs[i].getStart();
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    *          Format string as givien in the AppletFormatAdaptor list (exact
152    *          match to name of class implementing file io for that format)
153    * @param seqs
154    *          vector of sequences to write
155    * 
156    * @return String containing sequences in desired format
157    */
158   public String formatSequences(String format, SequenceI[] seqs)
159   {
160
161     try
162     {
163       AlignFile afile = 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 (format.equalsIgnoreCase("AMSA"))
210        * { afile = new AMSAFile(); afile.addJVSuffix(
211        * jalview.bin.Cache.getDefault("AMSA_JVSUFFIX", true)); }
212        */
213
214       afile.setSeqs(seqs);
215       String afileresp = afile.print();
216       if (afile.hasWarningMessage())
217       {
218         System.err.println("Warning raised when writing as " + format
219                 + " : " + afile.getWarningMessage());
220       }
221       return afileresp;
222     } catch (Exception e)
223     {
224       System.err.println("Failed to write alignment as a '" + format
225               + "' file\n");
226       e.printStackTrace();
227     }
228
229     return null;
230   }
231
232   public boolean getCacheSuffixDefault(String format)
233   {
234     if (isValidFormat(format))
235     {
236       return jalview.bin.Cache.getDefault(format.toUpperCase()
237               + "_JVSUFFIX", true);
238     }
239     return false;
240   }
241
242   public String formatSequences(String format, AlignmentI alignment,
243           String[] omitHidden, int[] exportRange, ColumnSelection colSel)
244   {
245     return formatSequences(format, alignment, omitHidden, exportRange,
246             getCacheSuffixDefault(format), colSel, null);
247   }
248
249   public String formatSequences(String format, AlignmentI alignment,
250           String[] omitHidden, int[] exportRange, ColumnSelection colSel,
251           SequenceGroup sgp)
252   {
253     return formatSequences(format, alignment, omitHidden, exportRange,
254             getCacheSuffixDefault(format), colSel, sgp);
255   }
256
257   /**
258    * hack function to replace seuqences with visible sequence strings before
259    * generating a string of the alignment in the given format.
260    * 
261    * @param format
262    * @param alignment
263    * @param omitHidden
264    *          sequence strings to write out in order of sequences in alignment
265    * @param colSel
266    *          defines hidden columns that are edited out of annotation
267    * @return string representation of the alignment formatted as format
268    */
269   public String formatSequences(String format, AlignmentI alignment,
270           String[] omitHidden, int[] exportRange, boolean suffix,
271           ColumnSelection colSel)
272   {
273     return formatSequences(format, alignment, omitHidden, exportRange,
274             suffix, colSel,
275             null);
276   }
277
278   public String formatSequences(String format, AlignmentI alignment,
279           String[] omitHidden, int[] exportRange, boolean suffix,
280           ColumnSelection colSel,
281           jalview.datamodel.SequenceGroup selgp)
282   {
283     if (omitHidden != null)
284     {
285       // TODO consider using AlignmentView to prune to visible region
286       // TODO prune sequence annotation and groups to visible region
287       // TODO: JAL-1486 - set start and end for output correctly. basically,
288       // AlignmentView.getVisibleContigs does this.
289       Alignment alv = new Alignment(replaceStrings(
290               alignment.getSequencesArray(), omitHidden, exportRange));
291       AlignmentAnnotation[] ala = alignment.getAlignmentAnnotation();
292       if (ala != null)
293       {
294         for (int i = 0; i < ala.length; i++)
295         {
296           AlignmentAnnotation na = new AlignmentAnnotation(ala[i]);
297           if (selgp != null)
298           {
299             colSel.makeVisibleAnnotation(selgp.getStartRes(),
300                     selgp.getEndRes(), na);
301           }
302           else
303           {
304             colSel.makeVisibleAnnotation(na);
305           }
306           alv.addAnnotation(na);
307         }
308       }
309       return this.formatSequences(format, alv, suffix);
310     }
311     return this.formatSequences(format, alignment, suffix);
312   }
313
314   public AlignmentI readFile(String inFile, String type, String format)
315           throws java.io.IOException
316   {
317     AlignmentI al = super.readFile(inFile, type, format);
318     return al;
319   }
320
321   public AlignmentI readFromFile(FileParse source, String format)
322           throws java.io.IOException
323   {
324     AlignmentI al = super.readFromFile(source, format);
325     return al;
326   }
327
328   /**
329    * validate format is valid for IO in Application. This is basically the
330    * AppletFormatAdapter.isValidFormat call with additional checks for
331    * Application only formats like 'Jalview'.
332    * 
333    * @param format
334    *          a format string to be compared with list of readable or writable
335    *          formats (READABLE_FORMATS or WRITABLE_FORMATS)
336    * @param forwriting
337    *          when true, format is checked against list of writable formats.
338    * @return true if format is valid
339    */
340   public static final boolean isValidIOFormat(String format,
341           boolean forwriting)
342   {
343     if (format.equalsIgnoreCase("jalview"))
344     {
345       return true;
346     }
347     return AppletFormatAdapter.isValidFormat(format, forwriting);
348   }
349
350   /**
351    * Create a flat file representation of a given view or selected region of a
352    * view
353    * 
354    * @param format
355    * @param ap
356    *          alignment panel originating the view
357    * @return String containing flat file
358    */
359   public String formatSequences(String format, AlignmentViewPanel ap,
360           boolean selectedOnly)
361   {
362     return formatSequences(format, getCacheSuffixDefault(format), ap,
363             selectedOnly);
364   }
365
366
367 }