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