f816a0f5479ca4c8884986bf26ace247b96372ff
[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 #include "message.h"
22 #include <ctype.h>
23 #include <errno.h>
24 #include <float.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include "array.h"
28 #include "alloc.h"
29 #include "case.h"
30 #include "command.h"
31 #include "dictionary.h"
32 #include "message.h"
33 #include "lexer.h"
34 #include "misc.h"
35 #include "pool.h"
36 #include "settings.h"
37 #include "str.h"
38 #include "value.h"
39 #include "variable.h"
40 #include "procedure.h"
41
42 #ifdef HAVE_SYS_TYPES_H
43 #include <sys/types.h>
44 #endif
45
46 #include "gettext.h"
47 #define _(msgid) gettext (msgid)
48
49 /* List of variable names. */
50 struct varname
51   {
52     struct varname *next;
53     char name[SHORT_NAME_LEN + 1];
54   };
55
56 /* Represents a FLIP input program. */
57 struct flip_pgm 
58   {
59     struct pool *pool;          /* Pool containing FLIP data. */
60     struct variable **var;      /* Variables to transpose. */
61     int *idx_to_fv;             /* var[]->index to compacted sink case fv. */
62     size_t var_cnt;             /* Number of elements in `var'. */
63     int case_cnt;               /* Pre-flip case count. */
64     size_t case_size;           /* Post-flip bytes per case. */
65
66     union value *output_buf;            /* Case output buffer. */
67
68     struct variable *new_names; /* Variable containing new variable names. */
69     struct varname *new_names_head; /* First new variable. */
70     struct varname *new_names_tail; /* Last new variable. */
71
72     FILE *file;                 /* Temporary file containing data. */
73   };
74
75 static void destroy_flip_pgm (struct flip_pgm *);
76 static struct case_sink *flip_sink_create (struct flip_pgm *);
77 static struct case_source *flip_source_create (struct flip_pgm *);
78 static bool flip_file (struct flip_pgm *);
79 static int build_dictionary (struct flip_pgm *);
80
81 static const struct case_source_class flip_source_class;
82 static const struct case_sink_class flip_sink_class;
83
84 /* Parses and executes FLIP. */
85 int
86 cmd_flip (void)
87 {
88   struct flip_pgm *flip;
89   bool ok;
90
91   if (temporary != 0)
92     {
93       msg (SM, _("FLIP ignores TEMPORARY.  "
94                  "Temporary transformations will be made permanent."));
95       cancel_temporary (); 
96     }
97
98   flip = pool_create_container (struct flip_pgm, pool);
99   flip->var = NULL;
100   flip->idx_to_fv = dict_get_compacted_idx_to_fv (default_dict);
101   pool_register (flip->pool, free, flip->idx_to_fv);
102   flip->var_cnt = 0;
103   flip->case_cnt = 0;
104   flip->new_names = NULL;
105   flip->new_names_head = NULL;
106   flip->new_names_tail = NULL;
107   flip->file = NULL;
108
109   lex_match ('/');
110   if (lex_match_id ("VARIABLES"))
111     {
112       lex_match ('=');
113       if (!parse_variables (default_dict, &flip->var, &flip->var_cnt,
114                             PV_NO_DUPLICATE))
115         goto error;
116       lex_match ('/');
117     }
118   else
119     dict_get_vars (default_dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
120   pool_register (flip->pool, free, flip->var);
121
122   lex_match ('/');
123   if (lex_match_id ("NEWNAMES"))
124     {
125       lex_match ('=');
126       flip->new_names = parse_variable ();
127       if (!flip->new_names)
128         goto error;
129     }
130   else
131     flip->new_names = dict_lookup_var (default_dict, "CASE_LBL");
132
133   if (flip->new_names)
134     {
135       size_t i;
136       
137       for (i = 0; i < flip->var_cnt; i++)
138         if (flip->var[i] == flip->new_names)
139           {
140             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
141             flip->var_cnt--;
142             break;
143           }
144     }
145
146   /* Read the active file into a flip_sink. */
147   flip->case_cnt = 0;
148   temp_trns = temporary = 0;
149   vfm_sink = flip_sink_create (flip);
150   if (vfm_sink == NULL)
151     goto error;
152   flip->new_names_tail = NULL;
153   ok = procedure (NULL, NULL);
154
155   /* Flip the data we read. */
156   if (!flip_file (flip)) 
157     {
158       discard_variables ();
159       goto error;
160     }
161
162   /* Flip the dictionary. */
163   dict_clear (default_dict);
164   if (!build_dictionary (flip))
165     {
166       discard_variables ();
167       goto error;
168     }
169   flip->case_size = dict_get_case_size (default_dict);
170
171   /* Set up flipped data for reading. */
172   vfm_source = flip_source_create (flip);
173
174   return ok ? lex_end_of_command () : CMD_CASCADING_FAILURE;
175
176  error:
177   destroy_flip_pgm (flip);
178   return CMD_CASCADING_FAILURE;
179 }
180
181 /* Destroys FLIP. */
182 static void
183 destroy_flip_pgm (struct flip_pgm *flip) 
184 {
185   if (flip != NULL)
186     pool_destroy (flip->pool);
187 }
188
189 /* Make a new variable with base name NAME, which is bowdlerized and
190    mangled until acceptable, and returns success. */
191 static int
192 make_new_var (char name[])
193 {
194   char *cp;
195
196   /* Trim trailing spaces. */
197   cp = strchr (name, '\0');
198   while (cp > name && isspace ((unsigned char) cp[-1]))
199     *--cp = '\0';
200
201   /* Fix invalid characters. */
202   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
203     if (cp == name) 
204       {
205         if (!lex_is_id1 (*cp) || *cp == '$')
206           *cp = 'V';
207       }
208     else
209       {
210         if (!lex_is_idn (*cp))
211           *cp = '_'; 
212       }
213   *cp = '\0';
214   str_uppercase (name);
215   
216   if (dict_create_var (default_dict, name, 0))
217     return 1;
218
219   /* Add numeric extensions until acceptable. */
220   {
221     const int len = (int) strlen (name);
222     char n[SHORT_NAME_LEN + 1];
223     int i;
224
225     for (i = 1; i < 10000000; i++)
226       {
227         int ofs = min (7 - intlog10 (i), len);
228         memcpy (n, name, ofs);
229         sprintf (&n[ofs], "%d", i);
230
231         if (dict_create_var (default_dict, n, 0))
232           return 1;
233       }
234   }
235
236   msg (SE, _("Could not create acceptable variant for variable %s."), name);
237   return 0;
238 }
239
240 /* Make a new dictionary for all the new variable names. */
241 static int
242 build_dictionary (struct flip_pgm *flip)
243 {
244   dict_create_var_assert (default_dict, "CASE_LBL", 8);
245
246   if (flip->new_names_head == NULL)
247     {
248       int i;
249       
250       if (flip->case_cnt > 99999)
251         {
252           msg (SE, _("Cannot create more than 99999 variable names."));
253           return 0;
254         }
255       
256       for (i = 0; i < flip->case_cnt; i++)
257         {
258           struct variable *v;
259           char s[SHORT_NAME_LEN + 1];
260
261           sprintf (s, "VAR%03d", i);
262           v = dict_create_var_assert (default_dict, s, 0);
263         }
264     }
265   else
266     {
267       struct varname *v;
268
269       for (v = flip->new_names_head; v; v = v->next)
270         if (!make_new_var (v->name))
271           return 0;
272     }
273   
274   return 1;
275 }
276      
277 /* Creates a flip sink based on FLIP. */
278 static struct case_sink *
279 flip_sink_create (struct flip_pgm *flip) 
280 {
281   size_t i;
282
283   flip->output_buf = pool_nalloc (flip->pool,
284                                   flip->var_cnt, sizeof *flip->output_buf);
285
286   flip->file = pool_tmpfile (flip->pool);
287   if (flip->file == NULL)
288     {
289       msg (SE, _("Could not create temporary file for FLIP."));
290       return NULL;
291     }
292
293   /* Write variable names as first case. */
294   for (i = 0; i < flip->var_cnt; i++) 
295     buf_copy_str_rpad (flip->output_buf[i].s, MAX_SHORT_STRING,
296                        flip->var[i]->name);
297   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
298               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
299     {
300       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
301       return NULL;
302     }
303
304   flip->case_cnt = 1;
305
306   return create_case_sink (&flip_sink_class, default_dict, flip);
307 }
308
309 /* Writes case C to the FLIP sink.
310    Returns true if successful, false if an I/O error occurred. */
311 static bool
312 flip_sink_write (struct case_sink *sink, const struct ccase *c)
313 {
314   struct flip_pgm *flip = sink->aux;
315   size_t i;
316   
317   flip->case_cnt++;
318
319   if (flip->new_names != NULL)
320     {
321       struct varname *v = pool_alloc (flip->pool, sizeof *v);
322       v->next = NULL;
323       if (flip->new_names->type == NUMERIC) 
324         {
325           double f = case_num (c, flip->idx_to_fv[flip->new_names->index]);
326
327           if (f == SYSMIS)
328             strcpy (v->name, "VSYSMIS");
329           else if (f < INT_MIN)
330             strcpy (v->name, "VNEGINF");
331           else if (f > INT_MAX)
332             strcpy (v->name, "VPOSINF");
333           else 
334             {
335               char name[INT_DIGITS + 2];
336               sprintf (name, "V%d", (int) f);
337               str_copy_trunc (v->name, sizeof v->name, name);
338             }
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   };