FLIP: Don't change new variables to upper case.
[pspp] / src / language / stats / flip.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include "config.h"
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <float.h>
22 #include <limits.h>
23 #include <stdlib.h>
24
25 #include <data/case.h>
26 #include <data/casereader.h>
27 #include <data/casereader-provider.h>
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/settings.h>
31 #include <data/short-names.h>
32 #include <data/value.h>
33 #include <data/variable.h>
34 #include <language/command.h>
35 #include <language/lexer/lexer.h>
36 #include <language/lexer/variable-parser.h>
37 #include <libpspp/array.h>
38 #include <libpspp/assertion.h>
39 #include <libpspp/message.h>
40 #include <libpspp/misc.h>
41 #include <libpspp/pool.h>
42 #include <libpspp/str.h>
43 #include <data/data-in.h>
44 #include <data/data-out.h>
45 #include "intprops.h"
46 #include "minmax.h"
47 #include "xalloc.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51
52 /* List of variable names. */
53 struct var_names
54   {
55     const char **names;
56     size_t n_names, allocated_names;
57   };
58
59 static void var_names_init (struct var_names *);
60 static void var_names_add (struct pool *, struct var_names *, const char *);
61
62 /* Represents a FLIP input program. */
63 struct flip_pgm
64   {
65     struct pool *pool;          /* Pool containing FLIP data. */
66     size_t n_vars;              /* Pre-flip number of variables. */
67     int n_cases;                /* Pre-flip number of cases. */
68
69     struct variable *new_names_var; /* Variable with new variable names. */
70     struct dictionary *dict;     /* Dictionary of the names */
71     struct var_names old_names; /* Variable names before FLIP. */
72     struct var_names new_names; /* Variable names after FLIP. */
73
74     FILE *file;                 /* Temporary file containing data. */
75     size_t cases_read;          /* Number of cases already read. */
76     bool error;                 /* Error reading temporary file? */
77   };
78
79 static const struct casereader_class flip_casereader_class;
80
81 static void destroy_flip_pgm (struct flip_pgm *);
82 static bool flip_file (struct flip_pgm *);
83 static void make_new_var (struct dictionary *, const char *name);
84
85 /* Parses and executes FLIP. */
86 int
87 cmd_flip (struct lexer *lexer, struct dataset *ds)
88 {
89   struct dictionary *dict = dataset_dict (ds);
90   const struct variable **vars;
91   struct flip_pgm *flip;
92   struct casereader *input, *reader;
93   struct ccase *c;
94   size_t i;
95   bool ok;
96
97   if (proc_make_temporary_transformations_permanent (ds))
98     msg (SW, _("FLIP ignores TEMPORARY.  "
99                "Temporary transformations will be made permanent."));
100
101   flip = pool_create_container (struct flip_pgm, pool);
102   flip->n_vars = 0;
103   flip->n_cases = 0;
104   flip->new_names_var = NULL;
105   var_names_init (&flip->old_names);
106   var_names_init (&flip->new_names);
107   flip->file = NULL;
108   flip->cases_read = 0;
109   flip->error = false;
110   flip->dict = dict;
111
112   lex_match (lexer, '/');
113   if (lex_match_id (lexer, "VARIABLES"))
114     {
115       lex_match (lexer, '=');
116       if (!parse_variables_const (lexer, dict, &vars, &flip->n_vars,
117                                   PV_NO_DUPLICATE))
118         goto error;
119       lex_match (lexer, '/');
120     }
121   else
122     dict_get_vars (dict, &vars, &flip->n_vars, DC_SYSTEM);
123   pool_register (flip->pool, free, vars);
124
125   lex_match (lexer, '/');
126   if (lex_match_id (lexer, "NEWNAMES"))
127     {
128       lex_match (lexer, '=');
129       flip->new_names_var = parse_variable (lexer, dict);
130       if (!flip->new_names_var)
131         goto error;
132     }
133   else
134     flip->new_names_var = dict_lookup_var (dict, "CASE_LBL");
135
136   if (flip->new_names_var)
137     {
138       for (i = 0; i < flip->n_vars; i++)
139         if (vars[i] == flip->new_names_var)
140           {
141             remove_element (vars, flip->n_vars, sizeof *vars, i);
142             flip->n_vars--;
143             break;
144           }
145     }
146
147   flip->file = pool_create_temp_file (flip->pool);
148   if (flip->file == NULL)
149     {
150       msg (SE, _("Could not create temporary file for FLIP."));
151       goto error;
152     }
153
154   /* Save old variable names for use as values of CASE_LBL
155      variable in flipped file. */
156   for (i = 0; i < flip->n_vars; i++)
157     var_names_add (flip->pool, &flip->old_names,
158                    pool_strdup (flip->pool, var_get_name (vars[i])));
159
160   /* Read the active file into a flip_sink. */
161   proc_discard_output (ds);
162
163   input = proc_open (ds);
164   while ((c = casereader_read (input)) != NULL)
165     {
166       flip->n_cases++;
167       for (i = 0; i < flip->n_vars; i++)
168         {
169           const struct variable *v = vars[i];
170           double out = var_is_numeric (v) ? case_num (c, v) : SYSMIS;
171           fwrite (&out, sizeof out, 1, flip->file);
172         }
173       if (flip->new_names_var != NULL)
174         {
175           const union value *value = case_data (c, flip->new_names_var);
176           const char *name;
177           if (var_is_numeric (flip->new_names_var))
178             {
179               double f = value->f;
180               name = (f == SYSMIS ? "VSYSMIS"
181                       : f < INT_MIN ? "VNEGINF"
182                       : f > INT_MAX ? "VPOSINF"
183                       : pool_asprintf (flip->pool, "V%d", (int) f));
184             }
185           else
186             {
187               name = data_out_pool (value, dict_get_encoding (flip->dict), var_get_write_format (flip->new_names_var),
188                  flip->pool);
189             }
190           var_names_add (flip->pool, &flip->new_names, name);
191         }
192       case_unref (c);
193     }
194   ok = casereader_destroy (input);
195   ok = proc_commit (ds) && ok;
196
197   /* Flip the data we read. */
198   if (!ok || !flip_file (flip))
199     {
200       proc_discard_active_file (ds);
201       goto error;
202     }
203
204   /* Flip the dictionary. */
205   dict_clear (dict);
206   dict_create_var_assert (dict, "CASE_LBL", 8);
207   for (i = 0; i < flip->n_cases; i++)
208     if (flip->new_names.n_names)
209       make_new_var (dict, flip->new_names.names[i]);
210     else
211       {
212         char s[VAR_NAME_LEN + 1];
213         sprintf (s, "VAR%03zu", i);
214         dict_create_var_assert (dict, s, 0);
215       }
216
217   /* Set up flipped data for reading. */
218   reader = casereader_create_sequential (NULL, dict_get_proto (dict),
219                                          flip->n_vars,
220                                          &flip_casereader_class, flip);
221   proc_set_active_file_data (ds, reader);
222   return lex_end_of_command (lexer);
223
224  error:
225   destroy_flip_pgm (flip);
226   return CMD_CASCADING_FAILURE;
227 }
228
229 /* Destroys FLIP. */
230 static void
231 destroy_flip_pgm (struct flip_pgm *flip)
232 {
233   if (flip != NULL)
234     pool_destroy (flip->pool);
235 }
236
237 /* Make a new variable with base name NAME, which is bowdlerized and
238    mangled until acceptable. */
239 static void
240 make_new_var (struct dictionary *dict, const char *name_)
241 {
242   char *name = xstrdup (name_);
243   char *cp;
244
245   /* Trim trailing spaces. */
246   cp = strchr (name, '\0');
247   while (cp > name && isspace ((unsigned char) cp[-1]))
248     *--cp = '\0';
249
250   /* Fix invalid characters. */
251   for (cp = name; *cp && cp < name + VAR_NAME_LEN; cp++)
252     if (cp == name)
253       {
254         if (!lex_is_id1 (*cp) || *cp == '$')
255           *cp = 'V';
256       }
257     else
258       {
259         if (!lex_is_idn (*cp))
260           *cp = '_';
261       }
262   *cp = '\0';
263
264   /* Use the mangled name, if it is available, or add numeric
265      extensions until we find one that is. */
266   if (!dict_create_var (dict, name, 0))
267     {
268       int len = strlen (name);
269       int i;
270       for (i = 1; ; i++)
271         {
272           char n[VAR_NAME_LEN + 1];
273           int ofs = MIN (VAR_NAME_LEN - 1 - intlog10 (i), len);
274           strncpy (n, name, ofs);
275           sprintf (&n[ofs], "%d", i);
276
277           if (dict_create_var (dict, n, 0))
278             break;
279         }
280     }
281   free (name);
282 }
283
284 /* Transposes the external file into a new file. */
285 static bool
286 flip_file (struct flip_pgm *flip)
287 {
288   size_t case_bytes;
289   size_t case_capacity;
290   size_t case_idx;
291   double *input_buf, *output_buf;
292   FILE *input_file, *output_file;
293
294   /* Allocate memory for many cases. */
295   case_bytes = flip->n_vars * sizeof *input_buf;
296   case_capacity = settings_get_workspace () / case_bytes;
297   if (case_capacity > flip->n_cases * 2)
298     case_capacity = flip->n_cases * 2;
299   if (case_capacity < 2)
300     case_capacity = 2;
301   for (;;)
302     {
303       size_t bytes = case_bytes * case_capacity;
304       if (case_capacity > 2)
305         input_buf = malloc (bytes);
306       else
307         input_buf = xmalloc (bytes);
308       if (input_buf != NULL)
309         break;
310
311       case_capacity /= 2;
312       if (case_capacity < 2)
313         case_capacity = 2;
314     }
315   pool_register (flip->pool, free, input_buf);
316
317   /* Use half the allocated memory for input_buf, half for
318      output_buf. */
319   case_capacity /= 2;
320   output_buf = input_buf + flip->n_vars * case_capacity;
321
322   input_file = flip->file;
323   if (fseeko (input_file, 0, SEEK_SET) != 0)
324     {
325       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
326       return false;
327     }
328
329   output_file = pool_create_temp_file (flip->pool);
330   if (output_file == NULL)
331     {
332       msg (SE, _("Error creating FLIP source file."));
333       return false;
334     }
335
336   for (case_idx = 0; case_idx < flip->n_cases; )
337     {
338       unsigned long read_cases = MIN (flip->n_cases - case_idx,
339                                       case_capacity);
340       size_t i;
341
342       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
343         {
344           if (ferror (input_file))
345             msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
346           else
347             msg (SE, _("Unexpected end of file reading FLIP file."));
348           return false;
349         }
350
351       for (i = 0; i < flip->n_vars; i++)
352         {
353           unsigned long j;
354
355           for (j = 0; j < read_cases; j++)
356             output_buf[j] = input_buf[i + j * flip->n_vars];
357
358           if (fseeko (output_file,
359                       sizeof *input_buf * (case_idx
360                                            + (off_t) i * flip->n_cases),
361                       SEEK_SET) != 0)
362             {
363               msg (SE, _("Error seeking FLIP source file: %s."),
364                    strerror (errno));
365               return false;
366             }
367
368           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
369               != read_cases)
370             {
371               msg (SE, _("Error writing FLIP source file: %s."),
372                    strerror (errno));
373               return false;
374             }
375         }
376
377       case_idx += read_cases;
378     }
379
380   pool_fclose_temp_file (flip->pool, input_file);
381   pool_unregister (flip->pool, input_buf);
382   free (input_buf);
383
384   if (fseeko (output_file, 0, SEEK_SET) != 0)
385     {
386       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
387       return false;
388     }
389   flip->file = output_file;
390
391   return true;
392 }
393
394 /* Reads and returns one case.
395    Returns a null pointer at end of file or if an I/O error occurred. */
396 static struct ccase *
397 flip_casereader_read (struct casereader *reader, void *flip_)
398 {
399   struct flip_pgm *flip = flip_;
400   struct ccase *c;
401   size_t i;
402
403   if (flip->error || flip->cases_read >= flip->n_vars)
404     return false;
405
406   c = case_create (casereader_get_proto (reader));
407   data_in (ss_cstr (flip->old_names.names[flip->cases_read]), dict_get_encoding (flip->dict), 
408         FMT_A, 0,
409         0, 0,
410         flip->dict, 
411         case_data_rw_idx (c, 0), 8);
412         
413   for (i = 0; i < flip->n_cases; i++)
414     {
415       double in;
416       if (fread (&in, sizeof in, 1, flip->file) != 1)
417         {
418           case_unref (c);
419           if (ferror (flip->file))
420             msg (SE, _("Error reading FLIP temporary file: %s."),
421                  strerror (errno));
422           else if (feof (flip->file))
423             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
424           else
425             NOT_REACHED ();
426           flip->error = true;
427           return NULL;
428         }
429       case_data_rw_idx (c, i + 1)->f = in;
430     }
431
432   flip->cases_read++;
433
434   return c;
435 }
436
437 /* Destroys the source.
438    Returns true if successful read, false if an I/O occurred
439    during destruction or previously. */
440 static void
441 flip_casereader_destroy (struct casereader *reader UNUSED, void *flip_)
442 {
443   struct flip_pgm *flip = flip_;
444   if (flip->error)
445     casereader_force_error (reader);
446   destroy_flip_pgm (flip);
447 }
448
449 static const struct casereader_class flip_casereader_class =
450   {
451     flip_casereader_read,
452     flip_casereader_destroy,
453     NULL,
454     NULL,
455   };
456 \f
457 static void
458 var_names_init (struct var_names *vn)
459 {
460   vn->names = NULL;
461   vn->n_names = 0;
462   vn->allocated_names = 0;
463 }
464
465 static void
466 var_names_add (struct pool *pool, struct var_names *vn, const char *name)
467 {
468   if (vn->n_names >= vn->allocated_names)
469     vn->names = pool_2nrealloc (pool, vn->names, &vn->allocated_names,
470                                 sizeof *vn->names);
471   vn->names[vn->n_names++] = name;
472 }
473