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