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