* psppire-dict.c (psppire_dict_dump): Don't use
[pspp-builds.git] / src / language / stats / flip.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000 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 #ifdef HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif
27
28 #include <data/case.h>
29 #include <data/casereader.h>
30 #include <data/casereader-provider.h>
31 #include <data/dictionary.h>
32 #include <data/procedure.h>
33 #include <data/settings.h>
34 #include <data/value.h>
35 #include <data/variable.h>
36 #include <language/command.h>
37 #include <language/lexer/lexer.h>
38 #include <language/lexer/variable-parser.h>
39 #include <libpspp/alloc.h>
40 #include <libpspp/array.h>
41 #include <libpspp/assertion.h>
42 #include <libpspp/message.h>
43 #include <libpspp/misc.h>
44 #include <libpspp/pool.h>
45 #include <libpspp/str.h>
46
47 #include "intprops.h"
48 #include "minmax.h"
49
50 #include "gettext.h"
51 #define _(msgid) gettext (msgid)
52
53 /* List of variable names. */
54 struct varname
55   {
56     struct varname *next;
57     char name[SHORT_NAME_LEN + 1];
58   };
59
60 /* Represents a FLIP input program. */
61 struct flip_pgm
62   {
63     struct pool *pool;          /* Pool containing FLIP data. */
64     const struct variable **var;      /* Variables to transpose. */
65     size_t var_cnt;             /* Number of elements in `var'. */
66     int case_cnt;               /* Pre-flip case count. */
67
68     struct variable *new_names; /* Variable containing new variable names. */
69     struct varname *new_names_head; /* First new variable. */
70     struct varname *new_names_tail; /* Last new variable. */
71
72     FILE *file;                 /* Temporary file containing data. */
73     union value *input_buf;     /* Input buffer for temporary file. */
74     size_t cases_read;          /* Number of cases already read. */
75     bool error;                 /* Error reading temporary file? */
76   };
77
78 static const struct casereader_class flip_casereader_class;
79
80 static void destroy_flip_pgm (struct flip_pgm *);
81 static bool flip_file (struct flip_pgm *);
82 static bool build_dictionary (struct dictionary *, struct flip_pgm *);
83 static bool write_flip_case (struct flip_pgm *, const struct ccase *);
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   struct flip_pgm *flip;
91   struct casereader *input, *reader;
92   union value *output_buf;
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->var = NULL;
103   flip->var_cnt = 0;
104   flip->case_cnt = 0;
105   flip->new_names = NULL;
106   flip->new_names_head = NULL;
107   flip->new_names_tail = NULL;
108   flip->file = NULL;
109   flip->input_buf = NULL;
110   flip->cases_read = 0;
111   flip->error = false;
112
113   lex_match (lexer, '/');
114   if (lex_match_id (lexer, "VARIABLES"))
115     {
116       lex_match (lexer, '=');
117       if (!parse_variables_const (lexer, dict, &flip->var, &flip->var_cnt,
118                                   PV_NO_DUPLICATE))
119         goto error;
120       lex_match (lexer, '/');
121     }
122   else
123     dict_get_vars (dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
124   pool_register (flip->pool, free, flip->var);
125
126   lex_match (lexer, '/');
127   if (lex_match_id (lexer, "NEWNAMES"))
128     {
129       lex_match (lexer, '=');
130       flip->new_names = parse_variable (lexer, dict);
131       if (!flip->new_names)
132         goto error;
133     }
134   else
135     flip->new_names = dict_lookup_var (dict, "CASE_LBL");
136
137   if (flip->new_names)
138     {
139       for (i = 0; i < flip->var_cnt; i++)
140         if (flip->var[i] == flip->new_names)
141           {
142             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
143             flip->var_cnt--;
144             break;
145           }
146     }
147
148   output_buf = pool_nalloc (flip->pool, flip->var_cnt, sizeof *output_buf);
149
150   flip->file = pool_tmpfile (flip->pool);
151   if (flip->file == NULL)
152     {
153       msg (SE, _("Could not create temporary file for FLIP."));
154       goto error;
155     }
156
157   /* Write variable names as first case. */
158   for (i = 0; i < flip->var_cnt; i++)
159     buf_copy_str_rpad (output_buf[i].s, MAX_SHORT_STRING,
160                        var_get_name (flip->var[i]));
161   if (fwrite (output_buf, sizeof *output_buf,
162               flip->var_cnt, flip->file) != (size_t) flip->var_cnt)
163     {
164       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
165       goto error;
166     }
167
168   flip->case_cnt = 1;
169
170   /* Read the active file into a flip_sink. */
171   proc_discard_output (ds);
172
173   input = proc_open (ds);
174   while (casereader_read (input, &c))
175     {
176       write_flip_case (flip, &c);
177       case_destroy (&c);
178     }
179   ok = casereader_destroy (input);
180   ok = proc_commit (ds) && ok;
181
182   /* Flip the data we read. */
183   if (!ok || !flip_file (flip))
184     {
185       proc_discard_active_file (ds);
186       goto error;
187     }
188
189   /* Flip the dictionary. */
190   dict_clear (dict);
191   if (!build_dictionary (dict, flip))
192     {
193       proc_discard_active_file (ds);
194       goto error;
195     }
196
197   /* Set up flipped data for reading. */
198   reader = casereader_create_sequential (NULL, dict_get_next_value_idx (dict),
199                                          flip->var_cnt,
200                                          &flip_casereader_class, flip);
201   proc_set_active_file_data (ds, reader);
202   return lex_end_of_command (lexer);
203
204  error:
205   destroy_flip_pgm (flip);
206   return CMD_CASCADING_FAILURE;
207 }
208
209 /* Destroys FLIP. */
210 static void
211 destroy_flip_pgm (struct flip_pgm *flip)
212 {
213   if (flip != NULL)
214     pool_destroy (flip->pool);
215 }
216
217 /* Make a new variable with base name NAME, which is bowdlerized and
218    mangled until acceptable, and returns success. */
219 static int
220 make_new_var (struct dictionary *dict, char name[])
221 {
222   char *cp;
223
224   /* Trim trailing spaces. */
225   cp = strchr (name, '\0');
226   while (cp > name && isspace ((unsigned char) cp[-1]))
227     *--cp = '\0';
228
229   /* Fix invalid characters. */
230   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
231     if (cp == name)
232       {
233         if (!lex_is_id1 (*cp) || *cp == '$')
234           *cp = 'V';
235       }
236     else
237       {
238         if (!lex_is_idn (*cp))
239           *cp = '_';
240       }
241   *cp = '\0';
242   str_uppercase (name);
243
244   if (dict_create_var (dict, name, 0))
245     return 1;
246
247   /* Add numeric extensions until acceptable. */
248   {
249     const int len = (int) strlen (name);
250     char n[SHORT_NAME_LEN + 1];
251     int i;
252
253     for (i = 1; i < 10000000; i++)
254       {
255         int ofs = MIN (7 - intlog10 (i), len);
256         memcpy (n, name, ofs);
257         sprintf (&n[ofs], "%d", i);
258
259         if (dict_create_var (dict, n, 0))
260           return 1;
261       }
262   }
263
264   msg (SE, _("Could not create acceptable variant for variable %s."), name);
265   return 0;
266 }
267
268 /* Make a new dictionary for all the new variable names. */
269 static bool
270 build_dictionary (struct dictionary *dict, struct flip_pgm *flip)
271 {
272   dict_create_var_assert (dict, "CASE_LBL", 8);
273
274   if (flip->new_names_head == NULL)
275     {
276       int i;
277
278       if (flip->case_cnt > 99999)
279         {
280           msg (SE, _("Cannot create more than 99999 variable names."));
281           return false;
282         }
283
284       for (i = 0; i < flip->case_cnt - 1; i++)
285         {
286           struct variable *v;
287           char s[SHORT_NAME_LEN + 1];
288
289           sprintf (s, "VAR%03d", i);
290           v = dict_create_var_assert (dict, s, 0);
291         }
292     }
293   else
294     {
295       struct varname *v;
296
297       for (v = flip->new_names_head; v; v = v->next)
298         if (!make_new_var (dict, v->name))
299           return false;
300     }
301
302   return true;
303 }
304
305 /* Writes case C to the FLIP sink.
306    Returns true if successful, false if an I/O error occurred. */
307 static bool
308 write_flip_case (struct flip_pgm *flip, const struct ccase *c)
309 {
310   size_t i;
311
312   flip->case_cnt++;
313
314   if (flip->new_names != NULL)
315     {
316       struct varname *v = pool_alloc (flip->pool, sizeof *v);
317       v->next = NULL;
318       if (var_is_numeric (flip->new_names))
319         {
320           double f = case_num (c, flip->new_names);
321
322           if (f == SYSMIS)
323             strcpy (v->name, "VSYSMIS");
324           else if (f < INT_MIN)
325             strcpy (v->name, "VNEGINF");
326           else if (f > INT_MAX)
327             strcpy (v->name, "VPOSINF");
328           else
329             snprintf (v->name, sizeof v->name, "V%d", (int) f);
330         }
331       else
332         {
333           int width = MIN (var_get_width (flip->new_names), MAX_SHORT_STRING);
334           memcpy (v->name, case_str (c, flip->new_names), width);
335           v->name[width] = 0;
336         }
337
338       if (flip->new_names_head == NULL)
339         flip->new_names_head = v;
340       else
341         flip->new_names_tail->next = v;
342       flip->new_names_tail = v;
343     }
344
345   /* Write to external file. */
346   for (i = 0; i < flip->var_cnt; i++)
347     {
348       const struct variable *v = flip->var[i];
349       double out = var_is_numeric (v) ? case_num (c, v) : SYSMIS;
350       fwrite (&out, sizeof out, 1, flip->file);
351     }
352   return true;
353 }
354
355 /* Transposes the external file into a new file. */
356 static bool
357 flip_file (struct flip_pgm *flip)
358 {
359   size_t case_bytes;
360   size_t case_capacity;
361   size_t case_idx;
362   union value *input_buf, *output_buf;
363   FILE *input_file, *output_file;
364
365   /* Allocate memory for many cases. */
366   case_bytes = flip->var_cnt * sizeof *input_buf;
367   case_capacity = get_workspace () / case_bytes;
368   if (case_capacity > flip->case_cnt * 2)
369     case_capacity = flip->case_cnt * 2;
370   if (case_capacity < 2)
371     case_capacity = 2;
372   for (;;)
373     {
374       size_t bytes = case_bytes * case_capacity;
375       if (case_capacity > 2)
376         input_buf = malloc (bytes);
377       else
378         input_buf = xmalloc (bytes);
379       if (input_buf != NULL)
380         break;
381
382       case_capacity /= 2;
383       if (case_capacity < 2)
384         case_capacity = 2;
385     }
386   pool_register (flip->pool, free, input_buf);
387
388   /* Use half the allocated memory for input_buf, half for
389      output_buf. */
390   case_capacity /= 2;
391   output_buf = input_buf + flip->var_cnt * case_capacity;
392
393   input_file = flip->file;
394   if (fseek (input_file, 0, SEEK_SET) != 0)
395     {
396       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
397       return false;
398     }
399
400   output_file = pool_tmpfile (flip->pool);
401   if (output_file == NULL)
402     {
403       msg (SE, _("Error creating FLIP source file."));
404       return false;
405     }
406
407   for (case_idx = 0; case_idx < flip->case_cnt; )
408     {
409       unsigned long read_cases = MIN (flip->case_cnt - case_idx,
410                                       case_capacity);
411       size_t i;
412
413       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
414         {
415           if (ferror (input_file))
416             msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
417           else
418             msg (SE, _("Unexpected end of file reading FLIP file."));
419           return false;
420         }
421
422       for (i = 0; i < flip->var_cnt; i++)
423         {
424           unsigned long j;
425
426           for (j = 0; j < read_cases; j++)
427             output_buf[j] = input_buf[i + j * flip->var_cnt];
428
429 #ifndef HAVE_FSEEKO
430 #define fseeko fseek
431 #endif
432
433 #ifndef HAVE_OFF_T
434 #define off_t long int
435 #endif
436
437           if (fseeko (output_file,
438                       sizeof *input_buf * (case_idx
439                                            + (off_t) i * flip->case_cnt),
440                       SEEK_SET) != 0)
441             {
442               msg (SE, _("Error seeking FLIP source file: %s."),
443                    strerror (errno));
444               return false;
445             }
446
447           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
448               != read_cases)
449             {
450               msg (SE, _("Error writing FLIP source file: %s."),
451                    strerror (errno));
452               return false;
453             }
454         }
455
456       case_idx += read_cases;
457     }
458
459   if (pool_fclose (flip->pool, input_file) == EOF)
460     {
461       msg (SE, _("Error closing FLIP source file: %s."), strerror (errno));
462       return false;
463     }
464   pool_unregister (flip->pool, input_buf);
465   free (input_buf);
466
467   if (fseek (output_file, 0, SEEK_SET) != 0)
468     {
469       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
470       return false;
471     }
472   flip->file = output_file;
473
474   return true;
475 }
476
477 /* Reads one case into C.
478    Returns true if successful, false at end of file or if an
479    I/O error occurred. */
480 static bool
481 flip_casereader_read (struct casereader *reader UNUSED, void *flip_,
482                       struct ccase *c)
483 {
484   struct flip_pgm *flip = flip_;
485   size_t i;
486
487   if (flip->error || flip->cases_read >= flip->var_cnt)
488     return false;
489
490   case_create (c, flip->case_cnt);
491   for (i = 0; i < flip->case_cnt; i++)
492     {
493       double in;
494       if (fread (&in, sizeof in, 1, flip->file) != 1)
495         {
496           case_destroy (c);
497           if (ferror (flip->file))
498             msg (SE, _("Error reading FLIP temporary file: %s."),
499                  strerror (errno));
500           else if (feof (flip->file))
501             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
502           else
503             NOT_REACHED ();
504           flip->error = true;
505           return false;
506         }
507       case_data_rw_idx (c, i)->f = in;
508     }
509
510   flip->cases_read++;
511
512   return true;
513 }
514
515 /* Destroys the source.
516    Returns true if successful read, false if an I/O occurred
517    during destruction or previously. */
518 static void
519 flip_casereader_destroy (struct casereader *reader UNUSED, void *flip_)
520 {
521   struct flip_pgm *flip = flip_;
522   if (flip->error)
523     casereader_force_error (reader);
524   destroy_flip_pgm (flip);
525 }
526
527 static const struct casereader_class flip_casereader_class =
528   {
529     flip_casereader_read,
530     flip_casereader_destroy,
531     NULL,
532     NULL,
533   };