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