JAL-2089 patch broken merge to master for Release 2.10.0b1
[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         if (startEnd != null)
111         {
112           startIndex = startEnd[0];
113           endIndex = startEnd[1];
114           // get first non-gaped residue start position
115           while (jalview.util.Comparison.isGap(seqs[i]
116                   .getCharAt(startIndex)) && startIndex < endIndex)
117           {
118             startIndex++;
119           }
120
121           // get last non-gaped residue end position
122           while (jalview.util.Comparison.isGap(seqs[i].getCharAt(endIndex))
123                   && endIndex > startIndex)
124           {
125             endIndex--;
126           }
127
128           startRes = seqs[i].findPosition(startIndex);
129           endRes = seqs[i].findPosition(endIndex);
130         }
131
132         tmp[i] = new Sequence(seqs[i].getName(), omitHiddenColumns[i],
133                 startRes, endRes);
134         tmp[i].setDescription(seqs[i].getDescription());
135       }
136       seqs = tmp;
137     }
138     return seqs;
139   }
140
141   /**
142    * Format a vector of sequences as a flat alignment file. TODO: allow caller
143    * to detect errors and warnings encountered when generating output
144    * 
145    * 
146    * @param format
147    *          Format string as givien in the AppletFormatAdaptor list (exact
148    *          match to name of class implementing file io for that format)
149    * @param seqs
150    *          vector of sequences to write
151    * 
152    * @return String containing sequences in desired format
153    */
154   public String formatSequences(String format, SequenceI[] seqs)
155   {
156
157     try
158     {
159       AlignFile afile = null;
160
161       if (format.equalsIgnoreCase("FASTA"))
162       {
163         afile = new FastaFile();
164         afile.addJVSuffix(jalview.bin.Cache.getDefault("FASTA_JVSUFFIX",
165                 true));
166       }
167       else if (format.equalsIgnoreCase("MSF"))
168       {
169         afile = new MSFfile();
170         afile.addJVSuffix(jalview.bin.Cache
171                 .getDefault("MSF_JVSUFFIX", true));
172       }
173       else if (format.equalsIgnoreCase("PileUp"))
174       {
175         afile = new PileUpfile();
176         afile.addJVSuffix(jalview.bin.Cache.getDefault("PILEUP_JVSUFFIX",
177                 true));
178       }
179       else if (format.equalsIgnoreCase("CLUSTAL"))
180       {
181         afile = new ClustalFile();
182         afile.addJVSuffix(jalview.bin.Cache.getDefault("CLUSTAL_JVSUFFIX",
183                 true));
184       }
185       else if (format.equalsIgnoreCase("BLC"))
186       {
187         afile = new BLCFile();
188         afile.addJVSuffix(jalview.bin.Cache
189                 .getDefault("BLC_JVSUFFIX", true));
190       }
191       else if (format.equalsIgnoreCase("PIR"))
192       {
193         afile = new PIRFile();
194         afile.addJVSuffix(jalview.bin.Cache
195                 .getDefault("PIR_JVSUFFIX", true));
196       }
197       else if (format.equalsIgnoreCase("PFAM"))
198       {
199         afile = new PfamFile();
200         afile.addJVSuffix(jalview.bin.Cache.getDefault("PFAM_JVSUFFIX",
201                 true));
202       }
203       /*
204        * amsa is not supported by this function - it requires an alignment
205        * rather than a sequence vector else if (format.equalsIgnoreCase("AMSA"))
206        * { afile = new AMSAFile(); afile.addJVSuffix(
207        * jalview.bin.Cache.getDefault("AMSA_JVSUFFIX", true)); }
208        */
209
210       afile.setSeqs(seqs);
211       String afileresp = afile.print();
212       if (afile.hasWarningMessage())
213       {
214         System.err.println("Warning raised when writing as " + format
215                 + " : " + afile.getWarningMessage());
216       }
217       return afileresp;
218     } catch (Exception e)
219     {
220       System.err.println("Failed to write alignment as a '" + format
221               + "' file\n");
222       e.printStackTrace();
223     }
224
225     return null;
226   }
227
228   public boolean getCacheSuffixDefault(String format)
229   {
230     if (isValidFormat(format))
231     {
232       return jalview.bin.Cache.getDefault(format.toUpperCase()
233               + "_JVSUFFIX", true);
234     }
235     return false;
236   }
237
238   public String formatSequences(String 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   public String formatSequences(String format, AlignmentI alignment,
246           String[] omitHidden, int[] exportRange, ColumnSelection colSel,
247           SequenceGroup sgp)
248   {
249     return formatSequences(format, alignment, omitHidden, exportRange,
250             getCacheSuffixDefault(format), colSel, sgp);
251   }
252
253   /**
254    * hack function to replace seuqences with visible sequence strings before
255    * generating a string of the alignment in the given format.
256    * 
257    * @param format
258    * @param alignment
259    * @param omitHidden
260    *          sequence strings to write out in order of sequences in alignment
261    * @param colSel
262    *          defines hidden columns that are edited out of annotation
263    * @return string representation of the alignment formatted as format
264    */
265   public String formatSequences(String format, AlignmentI alignment,
266           String[] omitHidden, int[] exportRange, boolean suffix,
267           ColumnSelection colSel)
268   {
269     return formatSequences(format, alignment, omitHidden, exportRange,
270             suffix, colSel, null);
271   }
272
273   public String formatSequences(String format, AlignmentI alignment,
274           String[] omitHidden, int[] exportRange, boolean suffix,
275           ColumnSelection colSel, jalview.datamodel.SequenceGroup selgp)
276   {
277     if (omitHidden != null)
278     {
279       // TODO consider using AlignmentView to prune to visible region
280       // TODO prune sequence annotation and groups to visible region
281       // TODO: JAL-1486 - set start and end for output correctly. basically,
282       // AlignmentView.getVisibleContigs does this.
283       Alignment alv = new Alignment(replaceStrings(
284               alignment.getSequencesArray(), omitHidden, exportRange));
285       AlignmentAnnotation[] ala = alignment.getAlignmentAnnotation();
286       if (ala != null)
287       {
288         for (int i = 0; i < ala.length; i++)
289         {
290           AlignmentAnnotation na = new AlignmentAnnotation(ala[i]);
291           if (selgp != null)
292           {
293             colSel.makeVisibleAnnotation(selgp.getStartRes(),
294                     selgp.getEndRes(), na);
295           }
296           else
297           {
298             colSel.makeVisibleAnnotation(na);
299           }
300           alv.addAnnotation(na);
301         }
302       }
303       return this.formatSequences(format, alv, suffix);
304     }
305     return this.formatSequences(format, alignment, suffix);
306   }
307
308   /**
309    * validate format is valid for IO in Application. This is basically the
310    * AppletFormatAdapter.isValidFormat call with additional checks for
311    * Application only formats like 'Jalview'.
312    * 
313    * @param format
314    *          a format string to be compared with list of readable or writable
315    *          formats (READABLE_FORMATS or WRITABLE_FORMATS)
316    * @param forwriting
317    *          when true, format is checked against list of writable formats.
318    * @return true if format is valid
319    */
320   public static final boolean isValidIOFormat(String format,
321           boolean forwriting)
322   {
323     if (format.equalsIgnoreCase("jalview"))
324     {
325       return true;
326     }
327     return AppletFormatAdapter.isValidFormat(format, forwriting);
328   }
329
330   /**
331    * Create a flat file representation of a given view or selected region of a
332    * view
333    * 
334    * @param format
335    * @param ap
336    *          alignment panel originating the view
337    * @return String containing flat file
338    */
339   public String formatSequences(String format, AlignmentViewPanel ap,
340           boolean selectedOnly)
341   {
342     return formatSequences(format, getCacheSuffixDefault(format), ap,
343             selectedOnly);
344   }
345
346 }