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