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