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