Continue reforming procedure execution. In this phase, get rid of
[pspp-builds.git] / src / language / stats / flip.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include "config.h"
21
22 #include <ctype.h>
23 #include <errno.h>
24 #include <float.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30
31 #include <data/case-sink.h>
32 #include <data/case-source.h>
33 #include <data/case.h>
34 #include <data/dictionary.h>
35 #include <procedure.h>
36 #include <data/settings.h>
37 #include <data/value.h>
38 #include <data/variable.h>
39 #include <language/command.h>
40 #include <language/lexer/lexer.h>
41 #include <libpspp/alloc.h>
42 #include <libpspp/array.h>
43 #include <libpspp/message.h>
44 #include <libpspp/message.h>
45 #include <libpspp/misc.h>
46 #include <libpspp/pool.h>
47 #include <libpspp/str.h>
48 #include <procedure.h>
49
50 #include "intprops.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     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     union value *output_buf;            /* Case output buffer. */
73
74     struct variable *new_names; /* Variable containing new variable names. */
75     struct varname *new_names_head; /* First new variable. */
76     struct varname *new_names_tail; /* Last new variable. */
77
78     FILE *file;                 /* Temporary file containing data. */
79   };
80
81 static void destroy_flip_pgm (struct flip_pgm *);
82 static struct case_sink *flip_sink_create (struct flip_pgm *);
83 static struct case_source *flip_source_create (struct flip_pgm *);
84 static bool flip_file (struct flip_pgm *);
85 static int build_dictionary (struct flip_pgm *);
86
87 static const struct case_source_class flip_source_class;
88 static const struct case_sink_class flip_sink_class;
89
90 /* Parses and executes FLIP. */
91 int
92 cmd_flip (void)
93 {
94   struct flip_pgm *flip;
95   struct case_sink *sink;
96   bool ok;
97
98   if (proc_make_temporary_transformations_permanent ())
99     msg (SW, _("FLIP ignores TEMPORARY.  "
100                "Temporary transformations will be made permanent."));
101
102   flip = pool_create_container (struct flip_pgm, pool);
103   flip->var = NULL;
104   flip->idx_to_fv = dict_get_compacted_idx_to_fv (default_dict);
105   pool_register (flip->pool, free, flip->idx_to_fv);
106   flip->var_cnt = 0;
107   flip->case_cnt = 0;
108   flip->new_names = NULL;
109   flip->new_names_head = NULL;
110   flip->new_names_tail = NULL;
111   flip->file = NULL;
112
113   lex_match ('/');
114   if (lex_match_id ("VARIABLES"))
115     {
116       lex_match ('=');
117       if (!parse_variables (default_dict, &flip->var, &flip->var_cnt,
118                             PV_NO_DUPLICATE))
119         goto error;
120       lex_match ('/');
121     }
122   else
123     dict_get_vars (default_dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
124   pool_register (flip->pool, free, flip->var);
125
126   lex_match ('/');
127   if (lex_match_id ("NEWNAMES"))
128     {
129       lex_match ('=');
130       flip->new_names = parse_variable ();
131       if (!flip->new_names)
132         goto error;
133     }
134   else
135     flip->new_names = dict_lookup_var (default_dict, "CASE_LBL");
136
137   if (flip->new_names)
138     {
139       size_t i;
140       
141       for (i = 0; i < flip->var_cnt; i++)
142         if (flip->var[i] == flip->new_names)
143           {
144             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
145             flip->var_cnt--;
146             break;
147           }
148     }
149
150   /* Read the active file into a flip_sink. */
151   flip->case_cnt = 0;
152   proc_make_temporary_transformations_permanent ();
153   sink = flip_sink_create (flip);
154   if (sink == NULL)
155     goto error;
156   proc_set_sink (sink);
157   flip->new_names_tail = NULL;
158   ok = procedure (NULL, NULL);
159
160   /* Flip the data we read. */
161   if (!flip_file (flip)) 
162     {
163       discard_variables ();
164       goto error;
165     }
166
167   /* Flip the dictionary. */
168   dict_clear (default_dict);
169   if (!build_dictionary (flip))
170     {
171       discard_variables ();
172       goto error;
173     }
174   flip->case_size = dict_get_case_size (default_dict);
175
176   /* Set up flipped data for reading. */
177   proc_set_source (flip_source_create (flip));
178
179   return ok ? lex_end_of_command () : CMD_CASCADING_FAILURE;
180
181  error:
182   destroy_flip_pgm (flip);
183   return CMD_CASCADING_FAILURE;
184 }
185
186 /* Destroys FLIP. */
187 static void
188 destroy_flip_pgm (struct flip_pgm *flip) 
189 {
190   if (flip != NULL)
191     pool_destroy (flip->pool);
192 }
193
194 /* Make a new variable with base name NAME, which is bowdlerized and
195    mangled until acceptable, and returns success. */
196 static int
197 make_new_var (char name[])
198 {
199   char *cp;
200
201   /* Trim trailing spaces. */
202   cp = strchr (name, '\0');
203   while (cp > name && isspace ((unsigned char) cp[-1]))
204     *--cp = '\0';
205
206   /* Fix invalid characters. */
207   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
208     if (cp == name) 
209       {
210         if (!lex_is_id1 (*cp) || *cp == '$')
211           *cp = 'V';
212       }
213     else
214       {
215         if (!lex_is_idn (*cp))
216           *cp = '_'; 
217       }
218   *cp = '\0';
219   str_uppercase (name);
220   
221   if (dict_create_var (default_dict, name, 0))
222     return 1;
223
224   /* Add numeric extensions until acceptable. */
225   {
226     const int len = (int) strlen (name);
227     char n[SHORT_NAME_LEN + 1];
228     int i;
229
230     for (i = 1; i < 10000000; i++)
231       {
232         int ofs = min (7 - intlog10 (i), len);
233         memcpy (n, name, ofs);
234         sprintf (&n[ofs], "%d", i);
235
236         if (dict_create_var (default_dict, n, 0))
237           return 1;
238       }
239   }
240
241   msg (SE, _("Could not create acceptable variant for variable %s."), name);
242   return 0;
243 }
244
245 /* Make a new dictionary for all the new variable names. */
246 static int
247 build_dictionary (struct flip_pgm *flip)
248 {
249   dict_create_var_assert (default_dict, "CASE_LBL", 8);
250
251   if (flip->new_names_head == NULL)
252     {
253       int i;
254       
255       if (flip->case_cnt > 99999)
256         {
257           msg (SE, _("Cannot create more than 99999 variable names."));
258           return 0;
259         }
260       
261       for (i = 0; i < flip->case_cnt; i++)
262         {
263           struct variable *v;
264           char s[SHORT_NAME_LEN + 1];
265
266           sprintf (s, "VAR%03d", i);
267           v = dict_create_var_assert (default_dict, s, 0);
268         }
269     }
270   else
271     {
272       struct varname *v;
273
274       for (v = flip->new_names_head; v; v = v->next)
275         if (!make_new_var (v->name))
276           return 0;
277     }
278   
279   return 1;
280 }
281      
282 /* Creates a flip sink based on FLIP. */
283 static struct case_sink *
284 flip_sink_create (struct flip_pgm *flip) 
285 {
286   size_t i;
287
288   flip->output_buf = pool_nalloc (flip->pool,
289                                   flip->var_cnt, sizeof *flip->output_buf);
290
291   flip->file = pool_tmpfile (flip->pool);
292   if (flip->file == NULL)
293     {
294       msg (SE, _("Could not create temporary file for FLIP."));
295       return NULL;
296     }
297
298   /* Write variable names as first case. */
299   for (i = 0; i < flip->var_cnt; i++) 
300     buf_copy_str_rpad (flip->output_buf[i].s, MAX_SHORT_STRING,
301                        flip->var[i]->name);
302   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
303               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
304     {
305       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
306       return NULL;
307     }
308
309   flip->case_cnt = 1;
310
311   return create_case_sink (&flip_sink_class, default_dict, flip);
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 flip_sink_write (struct case_sink *sink, const struct ccase *c)
318 {
319   struct flip_pgm *flip = sink->aux;
320   size_t i;
321   
322   flip->case_cnt++;
323
324   if (flip->new_names != NULL)
325     {
326       struct varname *v = pool_alloc (flip->pool, sizeof *v);
327       v->next = NULL;
328       if (flip->new_names->type == NUMERIC) 
329         {
330           double f = case_num (c, flip->idx_to_fv[flip->new_names->index]);
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 (flip->new_names->width, MAX_SHORT_STRING);
344           memcpy (v->name, case_str (c, flip->idx_to_fv[flip->new_names->index]),
345                   width);
346           v->name[width] = 0;
347         }
348       
349       if (flip->new_names_head == NULL)
350         flip->new_names_head = v;
351       else
352         flip->new_names_tail->next = v;
353       flip->new_names_tail = v;
354     }
355
356   /* Write to external file. */
357   for (i = 0; i < flip->var_cnt; i++)
358     {
359       double out;
360       
361       if (flip->var[i]->type == NUMERIC)
362         out = case_num (c, flip->idx_to_fv[flip->var[i]->index]);
363       else
364         out = SYSMIS;
365       flip->output_buf[i].f = out;
366     }
367           
368   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
369               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
370     {
371       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
372       return false; 
373     }
374   return true;
375 }
376
377 /* Transposes the external file into a new file. */
378 static bool
379 flip_file (struct flip_pgm *flip)
380 {
381   size_t case_bytes;
382   size_t case_capacity;
383   size_t case_idx;
384   union value *input_buf, *output_buf;
385   FILE *input_file, *output_file;
386
387   /* Allocate memory for many cases. */
388   case_bytes = flip->var_cnt * sizeof *input_buf;
389   case_capacity = get_workspace () / case_bytes;
390   if (case_capacity > flip->case_cnt * 2)
391     case_capacity = flip->case_cnt * 2;
392   if (case_capacity < 2)
393     case_capacity = 2;
394   for (;;)
395     {
396       size_t bytes = case_bytes * case_capacity;
397       if (case_capacity > 2)
398         input_buf = malloc (bytes);
399       else
400         input_buf = xmalloc (bytes);
401       if (input_buf != NULL)
402         break;
403
404       case_capacity /= 2;
405       if (case_capacity < 2)
406         case_capacity = 2;
407     }
408   pool_register (flip->pool, free, input_buf);
409
410   /* Use half the allocated memory for input_buf, half for
411      output_buf. */
412   case_capacity /= 2;
413   output_buf = input_buf + flip->var_cnt * case_capacity;
414
415   input_file = flip->file;
416   if (fseek (input_file, 0, SEEK_SET) != 0) 
417     {
418       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
419       return false;
420     }
421       
422   output_file = pool_tmpfile (flip->pool);
423   if (output_file == NULL) 
424     {
425       msg (SE, _("Error creating FLIP source file."));
426       return false;
427     }
428   
429   for (case_idx = 0; case_idx < flip->case_cnt; )
430     {
431       unsigned long read_cases = min (flip->case_cnt - case_idx,
432                                       case_capacity);
433       size_t i;
434
435       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file)) 
436         {
437           msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
438           return false;
439         }
440
441       for (i = 0; i < flip->var_cnt; i++)
442         {
443           unsigned long j;
444           
445           for (j = 0; j < read_cases; j++)
446             output_buf[j] = input_buf[i + j * flip->var_cnt];
447
448 #ifndef HAVE_FSEEKO
449 #define fseeko fseek
450 #endif
451
452 #ifndef HAVE_OFF_T
453 #define off_t long int
454 #endif
455
456           if (fseeko (output_file,
457                       sizeof *input_buf * (case_idx
458                                            + (off_t) i * flip->case_cnt),
459                       SEEK_SET) != 0) 
460             {
461               msg (SE, _("Error seeking FLIP source file: %s."),
462                    strerror (errno));
463               return false;
464             }
465
466           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
467               != read_cases) 
468             {
469               msg (SE, _("Error writing FLIP source file: %s."),
470                    strerror (errno));
471               return false; 
472             }
473         }
474
475       case_idx += read_cases;
476     }
477
478   pool_fclose (flip->pool, input_file);
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 /* FLIP sink class. */
493 static const struct case_sink_class flip_sink_class = 
494   {
495     "FLIP",
496     NULL,
497     flip_sink_write,
498     NULL,
499     NULL,
500   };
501
502 /* Creates and returns a FLIP source based on PGM,
503    which should have already been used as a sink. */
504 static struct case_source *
505 flip_source_create (struct flip_pgm *pgm)
506 {
507   return create_case_source (&flip_source_class, pgm);
508 }
509
510 /* Reads the FLIP stream.  Copies each case into C and calls
511    WRITE_CASE passing WC_DATA.
512    Returns true if successful, false if an I/O error occurred. */
513 static bool
514 flip_source_read (struct case_source *source,
515                   struct ccase *c,
516                   write_case_func *write_case, write_case_data wc_data)
517 {
518   struct flip_pgm *flip = source->aux;
519   union value *input_buf;
520   size_t i;
521   bool ok = true;
522
523   input_buf = xnmalloc (flip->case_cnt, sizeof *input_buf);
524   for (i = 0; ok && i < flip->var_cnt; i++)
525     {
526       size_t j;
527       
528       if (fread (input_buf, sizeof *input_buf, flip->case_cnt,
529                  flip->file) != flip->case_cnt) 
530         {
531           if (ferror (flip->file))
532             msg (SE, _("Error reading FLIP temporary file: %s."),
533                  strerror (errno));
534           else if (feof (flip->file))
535             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
536           else
537             abort ();
538           ok = false;
539           break;
540         }
541
542       for (j = 0; j < flip->case_cnt; j++)
543         case_data_rw (c, j)->f = input_buf[j].f;
544       ok = write_case (wc_data);
545     }
546   free (input_buf);
547
548   return ok;
549 }
550
551 /* Destroy internal data in SOURCE. */
552 static void
553 flip_source_destroy (struct case_source *source)
554 {
555   struct flip_pgm *flip = source->aux;
556
557   destroy_flip_pgm (flip);
558 }
559
560 static const struct case_source_class flip_source_class = 
561   {
562     "FLIP",
563     NULL,
564     flip_source_read,
565     flip_source_destroy
566   };