JAL-1780 JAL-653 Format/AppletFormat import and export pipeline regularised, uses...
[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 import jalview.gui.AlignmentPanel;
33
34 /**
35  * Additional formatting methods used by the application in a number of places.
36  * 
37  * @author $author$
38  * @version $Revision$
39  */
40 public class FormatAdapter extends AppletFormatAdapter
41 {
42   public FormatAdapter(AlignmentViewPanel viewpanel)
43   {
44     super(viewpanel);
45     init();
46   }
47
48   public FormatAdapter()
49   {
50     super();
51     init();
52   }
53
54   public FormatAdapter(AlignmentPanel alignPanel,
55           AlignExportSettingI settings)
56   {
57     super(alignPanel, settings);
58   }
59
60   private void init()
61   {
62     if (jalview.bin.Cache.getDefault("STRUCT_FROM_PDB", true))
63     {
64       annotFromStructure = jalview.bin.Cache.getDefault("ADD_TEMPFACT_ANN",
65               true);
66       localSecondaryStruct = jalview.bin.Cache.getDefault("ADD_SS_ANN",
67             true);
68     serviceSecondaryStruct = jalview.bin.Cache.getDefault("USE_RNAVIEW",
69             true);
70     }
71     else
72     {
73       // disable all PDB annotation options
74       annotFromStructure = false;
75       localSecondaryStruct = false;
76       serviceSecondaryStruct = false;
77     }
78   }
79
80   public String formatSequences(String format, SequenceI[] seqs,
81           String[] omitHiddenColumns, int[] exportRange)
82   {
83
84     return formatSequences(format,
85             replaceStrings(seqs, omitHiddenColumns, exportRange));
86   }
87
88   /**
89    * create sequences with each sequence string replaced with the one given in
90    * omitHiddenCOlumns
91    * 
92    * @param seqs
93    * @param omitHiddenColumns
94    * @return new sequences
95    */
96   public SequenceI[] replaceStrings(SequenceI[] seqs,
97           String[] omitHiddenColumns, int[] startEnd)
98   {
99     if (omitHiddenColumns != null)
100     {
101       SequenceI[] tmp = new SequenceI[seqs.length];
102
103       int startRes;
104       int endRes;
105       int startIndex;
106       int endIndex;
107       for (int i = 0; i < seqs.length; i++)
108       {
109         startRes = seqs[i].getStart();
110         endRes = seqs[i].getEnd();
111
112         startIndex = startEnd[0];
113         endIndex = startEnd[1];
114
115         if (startEnd != null)
116         {
117           // get first non-gaped residue start position
118           while (jalview.util.Comparison.isGap(seqs[i]
119                   .getCharAt(startIndex)) && startIndex < endIndex)
120           {
121             startIndex++;
122           }
123
124           // get last non-gaped residue end position
125           while (jalview.util.Comparison.isGap(seqs[i].getCharAt(endIndex))
126                   && endIndex > startIndex)
127           {
128             endIndex--;
129           }
130
131           startRes = seqs[i].findPosition(startIndex);
132           startRes = seqs[i].getStart() > 1 ? startRes - seqs[i].getStart()
133                   : startRes;
134           endRes = seqs[i].findPosition(endIndex) - seqs[i].getStart();
135         }
136
137         tmp[i] = new Sequence(seqs[i].getName(), omitHiddenColumns[i],
138                 startRes, endRes);
139         tmp[i].setDescription(seqs[i].getDescription());
140       }
141       seqs = tmp;
142     }
143     return seqs;
144   }
145
146   /**
147    * Format a vector of sequences as a flat alignment file. TODO: allow caller
148    * to detect errors and warnings encountered when generating output
149    * 
150    * 
151    * @param format
152    *          Format string as givien in the AppletFormatAdaptor list (exact
153    *          match to name of class implementing file io for that format)
154    * @param seqs
155    *          vector of sequences to write
156    * 
157    * @return String containing sequences in desired format
158    */
159   public String formatSequences(String format, SequenceI[] seqs)
160   {
161
162     try
163     {
164       AlignFile afile = null;
165
166       if (format.equalsIgnoreCase("FASTA"))
167       {
168         afile = new FastaFile();
169         afile.addJVSuffix(jalview.bin.Cache.getDefault("FASTA_JVSUFFIX",
170                 true));
171       }
172       else if (format.equalsIgnoreCase("MSF"))
173       {
174         afile = new MSFfile();
175         afile.addJVSuffix(jalview.bin.Cache
176                 .getDefault("MSF_JVSUFFIX", true));
177       }
178       else if (format.equalsIgnoreCase("PileUp"))
179       {
180         afile = new PileUpfile();
181         afile.addJVSuffix(jalview.bin.Cache.getDefault("PILEUP_JVSUFFIX",
182                 true));
183       }
184       else if (format.equalsIgnoreCase("CLUSTAL"))
185       {
186         afile = new ClustalFile();
187         afile.addJVSuffix(jalview.bin.Cache.getDefault("CLUSTAL_JVSUFFIX",
188                 true));
189       }
190       else if (format.equalsIgnoreCase("BLC"))
191       {
192         afile = new BLCFile();
193         afile.addJVSuffix(jalview.bin.Cache
194                 .getDefault("BLC_JVSUFFIX", true));
195       }
196       else if (format.equalsIgnoreCase("PIR"))
197       {
198         afile = new PIRFile();
199         afile.addJVSuffix(jalview.bin.Cache
200                 .getDefault("PIR_JVSUFFIX", true));
201       }
202       else if (format.equalsIgnoreCase("PFAM"))
203       {
204         afile = new PfamFile();
205         afile.addJVSuffix(jalview.bin.Cache.getDefault("PFAM_JVSUFFIX",
206                 true));
207       }
208       /*
209        * amsa is not supported by this function - it requires an alignment
210        * rather than a sequence vector else if (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(String format)
234   {
235     if (isValidFormat(format))
236     {
237       return jalview.bin.Cache.getDefault(format.toUpperCase()
238               + "_JVSUFFIX", true);
239     }
240     return false;
241   }
242
243   public String formatSequences(String format, AlignmentI alignment,
244           String[] omitHidden, int[] exportRange, ColumnSelection colSel)
245   {
246     return formatSequences(format, alignment, omitHidden, exportRange,
247             getCacheSuffixDefault(format), colSel, null);
248   }
249
250   public String formatSequences(String format, AlignmentI alignment,
251           String[] omitHidden, int[] exportRange, ColumnSelection colSel,
252           SequenceGroup sgp)
253   {
254     return formatSequences(format, alignment, omitHidden, exportRange,
255             getCacheSuffixDefault(format), colSel, sgp);
256   }
257
258   /**
259    * hack function to replace seuqences with visible sequence strings before
260    * generating a string of the alignment in the given format.
261    * 
262    * @param format
263    * @param alignment
264    * @param omitHidden
265    *          sequence strings to write out in order of sequences in alignment
266    * @param colSel
267    *          defines hidden columns that are edited out of annotation
268    * @return string representation of the alignment formatted as format
269    */
270   public String formatSequences(String format, AlignmentI alignment,
271           String[] omitHidden, int[] exportRange, boolean suffix,
272           ColumnSelection colSel)
273   {
274     return formatSequences(format, alignment, omitHidden, exportRange,
275             suffix, colSel,
276             null);
277   }
278
279   public String formatSequences(String format, AlignmentI alignment,
280           String[] omitHidden, int[] exportRange, boolean suffix,
281           ColumnSelection colSel,
282           jalview.datamodel.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 }