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