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