Continue reforming procedure execution. In this phase, move
[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 <data/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
49 #include "intprops.h"
50
51 #include "gettext.h"
52 #define _(msgid) gettext (msgid)
53
54 /* List of variable names. */
55 struct varname
56   {
57     struct varname *next;
58     char name[SHORT_NAME_LEN + 1];
59   };
60
61 /* Represents a FLIP input program. */
62 struct flip_pgm 
63   {
64     struct pool *pool;          /* Pool containing FLIP data. */
65     struct variable **var;      /* Variables to transpose. */
66     int *idx_to_fv;             /* var[]->index to compacted sink case fv. */
67     size_t var_cnt;             /* Number of elements in `var'. */
68     int case_cnt;               /* Pre-flip case count. */
69     size_t case_size;           /* Post-flip bytes per case. */
70
71     union value *output_buf;            /* Case output buffer. */
72
73     struct variable *new_names; /* Variable containing new variable names. */
74     struct varname *new_names_head; /* First new variable. */
75     struct varname *new_names_tail; /* Last new variable. */
76
77     FILE *file;                 /* Temporary file containing data. */
78   };
79
80 static void destroy_flip_pgm (struct flip_pgm *);
81 static struct case_sink *flip_sink_create (struct flip_pgm *);
82 static struct case_source *flip_source_create (struct flip_pgm *);
83 static bool flip_file (struct flip_pgm *);
84 static int build_dictionary (struct flip_pgm *);
85
86 static const struct case_source_class flip_source_class;
87 static const struct case_sink_class flip_sink_class;
88
89 /* Parses and executes FLIP. */
90 int
91 cmd_flip (void)
92 {
93   struct flip_pgm *flip;
94   struct case_sink *sink;
95   bool ok;
96
97   if (proc_make_temporary_transformations_permanent ())
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->idx_to_fv = dict_get_compacted_idx_to_fv (default_dict);
104   pool_register (flip->pool, free, flip->idx_to_fv);
105   flip->var_cnt = 0;
106   flip->case_cnt = 0;
107   flip->new_names = NULL;
108   flip->new_names_head = NULL;
109   flip->new_names_tail = NULL;
110   flip->file = NULL;
111
112   lex_match ('/');
113   if (lex_match_id ("VARIABLES"))
114     {
115       lex_match ('=');
116       if (!parse_variables (default_dict, &flip->var, &flip->var_cnt,
117                             PV_NO_DUPLICATE))
118         goto error;
119       lex_match ('/');
120     }
121   else
122     dict_get_vars (default_dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
123   pool_register (flip->pool, free, flip->var);
124
125   lex_match ('/');
126   if (lex_match_id ("NEWNAMES"))
127     {
128       lex_match ('=');
129       flip->new_names = parse_variable ();
130       if (!flip->new_names)
131         goto error;
132     }
133   else
134     flip->new_names = dict_lookup_var (default_dict, "CASE_LBL");
135
136   if (flip->new_names)
137     {
138       size_t i;
139       
140       for (i = 0; i < flip->var_cnt; i++)
141         if (flip->var[i] == flip->new_names)
142           {
143             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
144             flip->var_cnt--;
145             break;
146           }
147     }
148
149   /* Read the active file into a flip_sink. */
150   flip->case_cnt = 0;
151   proc_make_temporary_transformations_permanent ();
152   sink = flip_sink_create (flip);
153   if (sink == NULL)
154     goto error;
155   proc_set_sink (sink);
156   flip->new_names_tail = NULL;
157   ok = procedure (NULL, NULL);
158
159   /* Flip the data we read. */
160   if (!flip_file (flip)) 
161     {
162       discard_variables ();
163       goto error;
164     }
165
166   /* Flip the dictionary. */
167   dict_clear (default_dict);
168   if (!build_dictionary (flip))
169     {
170       discard_variables ();
171       goto error;
172     }
173   flip->case_size = dict_get_case_size (default_dict);
174
175   /* Set up flipped data for reading. */
176   proc_set_source (flip_source_create (flip));
177
178   return ok ? lex_end_of_command () : CMD_CASCADING_FAILURE;
179
180  error:
181   destroy_flip_pgm (flip);
182   return CMD_CASCADING_FAILURE;
183 }
184
185 /* Destroys FLIP. */
186 static void
187 destroy_flip_pgm (struct flip_pgm *flip) 
188 {
189   if (flip != NULL)
190     pool_destroy (flip->pool);
191 }
192
193 /* Make a new variable with base name NAME, which is bowdlerized and
194    mangled until acceptable, and returns success. */
195 static int
196 make_new_var (char name[])
197 {
198   char *cp;
199
200   /* Trim trailing spaces. */
201   cp = strchr (name, '\0');
202   while (cp > name && isspace ((unsigned char) cp[-1]))
203     *--cp = '\0';
204
205   /* Fix invalid characters. */
206   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
207     if (cp == name) 
208       {
209         if (!lex_is_id1 (*cp) || *cp == '$')
210           *cp = 'V';
211       }
212     else
213       {
214         if (!lex_is_idn (*cp))
215           *cp = '_'; 
216       }
217   *cp = '\0';
218   str_uppercase (name);
219   
220   if (dict_create_var (default_dict, name, 0))
221     return 1;
222
223   /* Add numeric extensions until acceptable. */
224   {
225     const int len = (int) strlen (name);
226     char n[SHORT_NAME_LEN + 1];
227     int i;
228
229     for (i = 1; i < 10000000; i++)
230       {
231         int ofs = min (7 - intlog10 (i), len);
232         memcpy (n, name, ofs);
233         sprintf (&n[ofs], "%d", i);
234
235         if (dict_create_var (default_dict, n, 0))
236           return 1;
237       }
238   }
239
240   msg (SE, _("Could not create acceptable variant for variable %s."), name);
241   return 0;
242 }
243
244 /* Make a new dictionary for all the new variable names. */
245 static int
246 build_dictionary (struct flip_pgm *flip)
247 {
248   dict_create_var_assert (default_dict, "CASE_LBL", 8);
249
250   if (flip->new_names_head == NULL)
251     {
252       int i;
253       
254       if (flip->case_cnt > 99999)
255         {
256           msg (SE, _("Cannot create more than 99999 variable names."));
257           return 0;
258         }
259       
260       for (i = 0; i < flip->case_cnt; i++)
261         {
262           struct variable *v;
263           char s[SHORT_NAME_LEN + 1];
264
265           sprintf (s, "VAR%03d", i);
266           v = dict_create_var_assert (default_dict, s, 0);
267         }
268     }
269   else
270     {
271       struct varname *v;
272
273       for (v = flip->new_names_head; v; v = v->next)
274         if (!make_new_var (v->name))
275           return 0;
276     }
277   
278   return 1;
279 }
280      
281 /* Creates a flip sink based on FLIP. */
282 static struct case_sink *
283 flip_sink_create (struct flip_pgm *flip) 
284 {
285   size_t i;
286
287   flip->output_buf = pool_nalloc (flip->pool,
288                                   flip->var_cnt, sizeof *flip->output_buf);
289
290   flip->file = pool_tmpfile (flip->pool);
291   if (flip->file == NULL)
292     {
293       msg (SE, _("Could not create temporary file for FLIP."));
294       return NULL;
295     }
296
297   /* Write variable names as first case. */
298   for (i = 0; i < flip->var_cnt; i++) 
299     buf_copy_str_rpad (flip->output_buf[i].s, MAX_SHORT_STRING,
300                        flip->var[i]->name);
301   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
302               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
303     {
304       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
305       return NULL;
306     }
307
308   flip->case_cnt = 1;
309
310   return create_case_sink (&flip_sink_class, default_dict, flip);
311 }
312
313 /* Writes case C to the FLIP sink.
314    Returns true if successful, false if an I/O error occurred. */
315 static bool
316 flip_sink_write (struct case_sink *sink, const struct ccase *c)
317 {
318   struct flip_pgm *flip = sink->aux;
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       v->next = NULL;
327       if (flip->new_names->type == NUMERIC) 
328         {
329           double f = case_num (c, flip->idx_to_fv[flip->new_names->index]);
330
331           if (f == SYSMIS)
332             strcpy (v->name, "VSYSMIS");
333           else if (f < INT_MIN)
334             strcpy (v->name, "VNEGINF");
335           else if (f > INT_MAX)
336             strcpy (v->name, "VPOSINF");
337           else
338             snprintf (v->name, sizeof v->name, "V%d", (int) f);
339         }
340       else
341         {
342           int width = min (flip->new_names->width, MAX_SHORT_STRING);
343           memcpy (v->name, case_str (c, flip->idx_to_fv[flip->new_names->index]),
344                   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 (flip->var[i]->type == NUMERIC)
361         out = case_num (c, flip->idx_to_fv[flip->var[i]->index]);
362       else
363         out = SYSMIS;
364       flip->output_buf[i].f = out;
365     }
366           
367   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
368               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
369     {
370       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
371       return false; 
372     }
373   return true;
374 }
375
376 /* Transposes the external file into a new file. */
377 static bool
378 flip_file (struct flip_pgm *flip)
379 {
380   size_t case_bytes;
381   size_t case_capacity;
382   size_t case_idx;
383   union value *input_buf, *output_buf;
384   FILE *input_file, *output_file;
385
386   /* Allocate memory for many cases. */
387   case_bytes = flip->var_cnt * sizeof *input_buf;
388   case_capacity = get_workspace () / case_bytes;
389   if (case_capacity > flip->case_cnt * 2)
390     case_capacity = flip->case_cnt * 2;
391   if (case_capacity < 2)
392     case_capacity = 2;
393   for (;;)
394     {
395       size_t bytes = case_bytes * case_capacity;
396       if (case_capacity > 2)
397         input_buf = malloc (bytes);
398       else
399         input_buf = xmalloc (bytes);
400       if (input_buf != NULL)
401         break;
402
403       case_capacity /= 2;
404       if (case_capacity < 2)
405         case_capacity = 2;
406     }
407   pool_register (flip->pool, free, input_buf);
408
409   /* Use half the allocated memory for input_buf, half for
410      output_buf. */
411   case_capacity /= 2;
412   output_buf = input_buf + flip->var_cnt * case_capacity;
413
414   input_file = flip->file;
415   if (fseek (input_file, 0, SEEK_SET) != 0) 
416     {
417       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
418       return false;
419     }
420       
421   output_file = pool_tmpfile (flip->pool);
422   if (output_file == NULL) 
423     {
424       msg (SE, _("Error creating FLIP source file."));
425       return false;
426     }
427   
428   for (case_idx = 0; case_idx < flip->case_cnt; )
429     {
430       unsigned long read_cases = min (flip->case_cnt - case_idx,
431                                       case_capacity);
432       size_t i;
433
434       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file)) 
435         {
436           msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
437           return false;
438         }
439
440       for (i = 0; i < flip->var_cnt; i++)
441         {
442           unsigned long j;
443           
444           for (j = 0; j < read_cases; j++)
445             output_buf[j] = input_buf[i + j * flip->var_cnt];
446
447 #ifndef HAVE_FSEEKO
448 #define fseeko fseek
449 #endif
450
451 #ifndef HAVE_OFF_T
452 #define off_t long int
453 #endif
454
455           if (fseeko (output_file,
456                       sizeof *input_buf * (case_idx
457                                            + (off_t) i * flip->case_cnt),
458                       SEEK_SET) != 0) 
459             {
460               msg (SE, _("Error seeking FLIP source file: %s."),
461                    strerror (errno));
462               return false;
463             }
464
465           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
466               != read_cases) 
467             {
468               msg (SE, _("Error writing FLIP source file: %s."),
469                    strerror (errno));
470               return false; 
471             }
472         }
473
474       case_idx += read_cases;
475     }
476
477   pool_fclose (flip->pool, input_file);
478   pool_unregister (flip->pool, input_buf);
479   free (input_buf);
480   
481   if (fseek (output_file, 0, SEEK_SET) != 0) 
482     {
483       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
484       return false; 
485     }
486   flip->file = output_file;
487
488   return true;
489 }
490
491 /* FLIP sink class. */
492 static const struct case_sink_class flip_sink_class = 
493   {
494     "FLIP",
495     NULL,
496     flip_sink_write,
497     NULL,
498     NULL,
499   };
500
501 /* Creates and returns a FLIP source based on PGM,
502    which should have already been used as a sink. */
503 static struct case_source *
504 flip_source_create (struct flip_pgm *pgm)
505 {
506   return create_case_source (&flip_source_class, pgm);
507 }
508
509 /* Reads the FLIP stream.  Copies each case into C and calls
510    WRITE_CASE passing WC_DATA.
511    Returns true if successful, false if an I/O error occurred. */
512 static bool
513 flip_source_read (struct case_source *source,
514                   struct ccase *c,
515                   write_case_func *write_case, write_case_data wc_data)
516 {
517   struct flip_pgm *flip = source->aux;
518   union value *input_buf;
519   size_t i;
520   bool ok = true;
521
522   input_buf = xnmalloc (flip->case_cnt, sizeof *input_buf);
523   for (i = 0; ok && i < flip->var_cnt; i++)
524     {
525       size_t j;
526       
527       if (fread (input_buf, sizeof *input_buf, flip->case_cnt,
528                  flip->file) != flip->case_cnt) 
529         {
530           if (ferror (flip->file))
531             msg (SE, _("Error reading FLIP temporary file: %s."),
532                  strerror (errno));
533           else if (feof (flip->file))
534             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
535           else
536             abort ();
537           ok = false;
538           break;
539         }
540
541       for (j = 0; j < flip->case_cnt; j++)
542         case_data_rw (c, j)->f = input_buf[j].f;
543       ok = write_case (wc_data);
544     }
545   free (input_buf);
546
547   return ok;
548 }
549
550 /* Destroy internal data in SOURCE. */
551 static void
552 flip_source_destroy (struct case_source *source)
553 {
554   struct flip_pgm *flip = source->aux;
555
556   destroy_flip_pgm (flip);
557 }
558
559 static const struct case_source_class flip_source_class = 
560   {
561     "FLIP",
562     NULL,
563     flip_source_read,
564     flip_source_destroy
565   };