JAL-1641 Re-implemented lost changes after sequenceFeature refactor
[jalview.git] / src / jalview / io / AlignFile.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.datamodel.Alignment;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.util.MessageManager;
30
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.Enumeration;
34 import java.util.Hashtable;
35 import java.util.List;
36 import java.util.Vector;
37
38 /**
39  * DOCUMENT ME!
40  * 
41  * @author $author$
42  * @version $Revision$
43  */
44 public abstract class AlignFile extends FileParse
45 {
46   int noSeqs = 0;
47
48   int maxLength = 0;
49
50   /**
51    * Sequences to be added to form a new alignment.
52    */
53   protected Vector<SequenceI> seqs;
54
55   /**
56    * annotation to be added to generated alignment object
57    */
58   protected Vector<AlignmentAnnotation> annotations;
59
60   /**
61    * SequenceGroups to be added to the alignment object
62    */
63   protected List<SequenceGroup> seqGroups;
64
65   /**
66    * Properties to be added to generated alignment object
67    */
68   protected Hashtable properties;
69
70   long start;
71
72   long end;
73
74   boolean jvSuffix = true;
75
76   private boolean parseCalled;
77
78   /**
79    * Creates a new AlignFile object.
80    */
81   public AlignFile()
82   {
83     // Shouldn't we init data structures (JBPNote: not sure - initData is for
84     // initialising the structures used for reading from a datasource, and the
85     // bare constructor hasn't got any datasource)
86     initData();
87   }
88
89   /**
90    * Constructor which parses the data from a file of some specified type.
91    * 
92    * @param inFile
93    *          Filename to read from.
94    * @param type
95    *          What type of file to read from (File, URL)
96    */
97   public AlignFile(String inFile, String type) throws IOException
98   {
99     this(true, inFile, type);
100   }
101   
102   /**
103    * Constructor which (optionally delays) parsing of data from a file of some specified type.
104    * 
105    * @param parseImmediately
106    *          if false, need to call 'doParse()' to begin parsing data
107    * @param inFile
108    *          Filename to read from.
109    * @param type
110    *          What type of file to read from (File, URL)
111    * @throws IOException
112    */
113   public AlignFile(boolean parseImmediately, String inFile, String type) throws IOException
114   {
115     super(inFile, type);
116     initData();
117     if (parseImmediately) {
118       doParse();
119     }
120   }
121   /**
122    * Attempt to read from the position where some other parsing process left
123    * off.
124    * 
125    * @param source
126    * @throws IOException
127    */
128   public AlignFile(FileParse source) throws IOException
129   {
130     this(true,source);
131   }
132   /**
133    * Construct a new parser to read from the position where some other parsing process left
134    * 
135    * @param parseImmediately
136    *          if false, need to call 'doParse()' to begin parsing data
137    * @param source
138    */
139   public AlignFile(boolean parseImmediately, FileParse source) throws IOException
140   {
141     super(source);
142     initData();
143     if (parseImmediately) {
144       doParse();
145     }
146   }
147   /**
148    * called if parsing was delayed till after parser was constructed
149    * @throws IOException
150    */
151   public void doParse() throws IOException
152   {
153     if (parseCalled)
154     {
155       throw new IOException(
156               "Implementation error: Parser called twice for same data.\n"
157                       + "Need to call initData() again before parsing can be reattempted.");
158     }
159     parseCalled=true;
160     parse();
161     // sets the index of each sequence in the alignment
162     for (int i = 0, c = seqs.size(); i < c; i++)
163     {
164       seqs.get(i).setIndex(i);
165     }
166   }
167
168
169   /**
170    * Return the seqs Vector
171    */
172   public Vector<SequenceI> getSeqs()
173   {
174     return seqs;
175   }
176
177   /**
178    * Return the Sequences in the seqs Vector as an array of Sequences
179    */
180   public SequenceI[] getSeqsAsArray()
181   {
182     SequenceI[] s = new SequenceI[seqs.size()];
183
184     for (int i = 0; i < seqs.size(); i++)
185     {
186       s[i] = seqs.elementAt(i);
187     }
188
189     return s;
190   }
191
192   /**
193    * called by AppletFormatAdapter to generate an annotated alignment, rather
194    * than bare sequences.
195    * 
196    * @param al
197    */
198   public void addAnnotations(Alignment al)
199   {
200     addProperties(al);
201     for (int i = 0; i < annotations.size(); i++)
202     {
203       // detect if annotations.elementAt(i) rna secondary structure
204       // if so then do:
205       /*
206        * SequenceFeature[] pairArray =
207        * Rna.GetBasePairsFromAlignmentAnnotation(annotations.elementAt(i));
208        * Rna.HelixMap(pairArray);
209        */
210       AlignmentAnnotation an = annotations
211               .elementAt(i);
212       an.validateRangeAndDisplay();
213       al.addAnnotation(an);
214     }
215
216   }
217
218   public void addSeqGroups(AlignmentI al)
219   {
220     this.seqGroups = al.getGroups();
221   }
222
223   /**
224    * Add any additional information extracted from the file to the alignment
225    * properties.
226    * 
227    * @note implicitly called by addAnnotations()
228    * @param al
229    */
230   public void addProperties(Alignment al)
231   {
232     if (properties != null && properties.size() > 0)
233     {
234       Enumeration keys = properties.keys();
235       Enumeration vals = properties.elements();
236       while (keys.hasMoreElements())
237       {
238         al.setProperty(keys.nextElement(), vals.nextElement());
239       }
240     }
241   }
242
243   /**
244    * Store a non-null key-value pair in a hashtable used to set alignment
245    * properties note: null keys will raise an error, null values will result in
246    * the key/value pair being silently ignored.
247    * 
248    * @param key
249    *          - non-null key object
250    * @param value
251    *          - non-null value
252    */
253   protected void setAlignmentProperty(Object key, Object value)
254   {
255     if (key == null)
256     {
257       throw new Error(MessageManager.getString("error.implementation_error_cannot_have_null_alignment"));
258     }
259     if (value == null)
260     {
261       return; // null properties are ignored.
262     }
263     if (properties == null)
264     {
265       properties = new Hashtable();
266     }
267     properties.put(key, value);
268   }
269
270   protected Object getAlignmentProperty(Object key)
271   {
272     if (properties != null && key != null)
273     {
274       return properties.get(key);
275     }
276     return null;
277   }
278
279   /**
280    * Initialise objects to store sequence data in.
281    */
282   protected void initData()
283   {
284     seqs = new Vector();
285     annotations = new Vector();
286     seqGroups = new ArrayList<SequenceGroup>();
287     parseCalled=false;
288   }
289
290   /**
291    * DOCUMENT ME!
292    * 
293    * @param s
294    *          DOCUMENT ME!
295    */
296   protected void setSeqs(SequenceI[] s)
297   {
298     seqs = new Vector();
299
300     for (int i = 0; i < s.length; i++)
301     {
302       seqs.addElement(s[i]);
303     }
304   }
305
306   /**
307    * This method must be implemented to parse the contents of the file.
308    */
309   public abstract void parse() throws IOException;
310
311   /**
312    * Print out in alignment file format the Sequences in the seqs Vector.
313    */
314   public abstract String print();
315
316   public void addJVSuffix(boolean b)
317   {
318     jvSuffix = b;
319   }
320
321   /**
322    * A general parser for ids.
323    * 
324    * @String id Id to be parsed
325    */
326   Sequence parseId(String id)
327   {
328     Sequence seq = null;
329     id = id.trim();
330     int space = id.indexOf(" ");
331     if (space > -1)
332     {
333       seq = new Sequence(id.substring(0, space), "");
334       seq.setDescription(id.substring(space + 1));
335     }
336     else
337     {
338       seq = new Sequence(id, "");
339     }
340
341     return seq;
342   }
343
344   /**
345    * Creates the output id. Adds prefix Uniprot format source|id And suffix
346    * Jalview /start-end
347    * 
348    * @String id Id to be parsed
349    */
350   String printId(SequenceI seq)
351   {
352     return seq.getDisplayId(jvSuffix);
353   }
354
355   /**
356    * vector of String[] treeName, newickString pairs
357    */
358   Vector newickStrings = null;
359
360   protected void addNewickTree(String treeName, String newickString)
361   {
362     if (newickStrings == null)
363     {
364       newickStrings = new Vector();
365     }
366     newickStrings.addElement(new String[]
367     { treeName, newickString });
368   }
369
370   protected int getTreeCount()
371   {
372     if (newickStrings == null)
373     {
374       return 0;
375     }
376     return newickStrings.size();
377   }
378
379 }