1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
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.
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.
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
21 #include "por-file-writer.h"
35 #include "dictionary.h"
36 #include "file-handle-def.h"
38 #include "missing-values.h"
39 #include "stat-macros.h"
40 #include "value-labels.h"
43 #include <libpspp/alloc.h>
44 #include <libpspp/hash.h>
45 #include <libpspp/magic.h>
46 #include <libpspp/message.h>
47 #include <libpspp/misc.h>
48 #include <libpspp/str.h>
49 #include <libpspp/version.h>
52 #define _(msgid) gettext (msgid)
54 /* Portable file writer. */
57 struct file_handle *fh; /* File handle. */
58 FILE *file; /* File stream. */
60 int lc; /* Number of characters on this line so far. */
62 size_t var_cnt; /* Number of variables. */
63 struct pfm_var *vars; /* Variables. */
65 int digits; /* Digits of precision. */
68 /* A variable to write to the portable file. */
71 int width; /* 0=numeric, otherwise string var width. */
72 int fv; /* Starting case index. */
75 static void buf_write (struct pfm_writer *, const void *, size_t);
76 static void write_header (struct pfm_writer *);
77 static void write_version_data (struct pfm_writer *);
78 static void write_variables (struct pfm_writer *, struct dictionary *);
79 static void write_value_labels (struct pfm_writer *,
80 const struct dictionary *);
82 static void format_trig_double (long double, int base_10_precision, char[]);
83 static char *format_trig_int (int, bool force_sign, char[]);
85 /* Returns default options for writing a portable file. */
86 struct pfm_write_options
87 pfm_writer_default_options (void)
89 struct pfm_write_options opts;
90 opts.create_writeable = true;
92 opts.digits = DBL_DIG;
96 /* Writes the dictionary DICT to portable file HANDLE according
97 to the given OPTS. Returns nonzero only if successful. DICT
98 will not be modified, except to assign short names. */
100 pfm_open_writer (struct file_handle *fh, struct dictionary *dict,
101 struct pfm_write_options opts)
103 struct pfm_writer *w = NULL;
109 mode = S_IRUSR | S_IRGRP | S_IROTH;
110 if (opts.create_writeable)
111 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
112 fd = open (fh_get_file_name (fh), O_WRONLY | O_CREAT | O_TRUNC, mode);
116 /* Open file handle. */
117 if (!fh_open (fh, FH_REF_FILE, "portable file", "we"))
120 /* Initialize data structures. */
121 w = xmalloc (sizeof *w);
123 w->file = fdopen (fd, "w");
134 w->var_cnt = dict_get_var_cnt (dict);
135 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
136 for (i = 0; i < w->var_cnt; i++)
138 const struct variable *dv = dict_get_var (dict, i);
139 struct pfm_var *pv = &w->vars[i];
140 pv->width = var_get_width (dv);
141 pv->fv = var_get_case_index (dv);
144 w->digits = opts.digits;
147 msg (ME, _("Invalid decimal digits count %d. Treating as %d."),
152 /* Write file header. */
154 write_version_data (w);
155 write_variables (w, dict);
156 write_value_labels (w, dict);
157 buf_write (w, "F", 1);
158 if (pfm_write_error (w))
163 pfm_close_writer (w);
167 msg (ME, _("An error occurred while opening \"%s\" for writing "
168 "as a portable file: %s."),
169 fh_get_file_name (fh), strerror (errno));
173 /* Write NBYTES starting at BUF to the portable file represented by
174 H. Break lines properly every 80 characters. */
176 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
178 const char *buf = buf_;
180 if (ferror (w->file))
183 assert (buf != NULL);
184 while (nbytes + w->lc >= 80)
186 size_t n = 80 - w->lc;
189 fwrite (buf, n, 1, w->file);
190 fwrite ("\r\n", 2, 1, w->file);
196 fwrite (buf, nbytes, 1, w->file);
201 /* Write D to the portable file as a floating-point field. */
203 write_float (struct pfm_writer *w, double d)
206 format_trig_double (d, floor (d) == d ? DBL_DIG : w->digits, buffer);
207 buf_write (w, buffer, strlen (buffer));
208 buf_write (w, "/", 1);
211 /* Write N to the portable file as an integer field. */
213 write_int (struct pfm_writer *w, int n)
216 format_trig_int (n, false, buffer);
217 buf_write (w, buffer, strlen (buffer));
218 buf_write (w, "/", 1);
221 /* Write S to the portable file as a string field. */
223 write_string (struct pfm_writer *w, const char *s)
225 size_t n = strlen (s);
226 write_int (w, (int) n);
230 /* Write file header. */
232 write_header (struct pfm_writer *w)
234 static const char spss2ascii[256] =
236 "0000000000000000000000000000000000000000000000000000000000000000"
237 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
238 "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
239 "0000000000000000000000000000000000000000000000000000000000000000"
243 for (i = 0; i < 5; i++)
244 buf_write (w, "ASCII SPSS PORT FILE ", 40);
246 buf_write (w, spss2ascii, 256);
247 buf_write (w, "SPSSPORT", 8);
250 /* Writes version, date, and identification records. */
252 write_version_data (struct pfm_writer *w)
260 if ((time_t) -1 == time (&t))
262 tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
267 tmp = localtime (&t);
269 sprintf (date_str, "%04d%02d%02d",
270 tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
271 sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
272 buf_write (w, "A", 1);
273 write_string (w, date_str);
274 write_string (w, time_str);
276 /* Product identification. */
277 buf_write (w, "1", 1);
278 write_string (w, version);
280 /* Subproduct identification. */
281 buf_write (w, "3", 1);
282 write_string (w, host_system);
285 /* Write format F to file H. */
287 write_format (struct pfm_writer *w, const struct fmt_spec *f)
289 write_int (w, fmt_to_io (f->type));
294 /* Write value V for variable VV to file H. */
296 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
298 if (var_is_numeric (vv))
299 write_float (w, v->f);
302 write_int (w, var_get_width (vv));
303 buf_write (w, v->s, var_get_width (vv));
307 /* Write variable records. */
309 write_variables (struct pfm_writer *w, struct dictionary *dict)
313 dict_assign_short_names (dict);
315 buf_write (w, "4", 1);
316 write_int (w, dict_get_var_cnt (dict));
319 for (i = 0; i < dict_get_var_cnt (dict); i++)
321 struct variable *v = dict_get_var (dict, i);
322 struct missing_values mv;
324 buf_write (w, "7", 1);
325 write_int (w, var_get_width (v));
326 write_string (w, var_get_short_name (v));
327 write_format (w, var_get_print_format (v));
328 write_format (w, var_get_write_format (v));
330 /* Write missing values. */
331 mv_copy (&mv, var_get_missing_values (v));
332 while (mv_has_range (&mv))
335 mv_pop_range (&mv, &x, &y);
338 buf_write (w, "9", 1);
341 else if (y == HIGHEST)
343 buf_write (w, "A", 1);
348 buf_write (w, "B", 1);
353 while (mv_has_value (&mv))
356 mv_pop_value (&mv, &value);
357 buf_write (w, "8", 1);
358 write_value (w, &value, v);
361 if (var_get_label (v) != NULL)
363 buf_write (w, "C", 1);
364 write_string (w, var_get_label (v));
369 /* Write value labels to disk. FIXME: Inefficient. */
371 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
375 for (i = 0; i < dict_get_var_cnt (dict); i++)
377 struct val_labs_iterator *j;
378 struct variable *v = dict_get_var (dict, i);
379 const struct val_labs *val_labs = var_get_value_labels (v);
382 if (val_labs == NULL)
385 buf_write (w, "D", 1);
387 write_string (w, var_get_short_name (v));
388 write_int (w, val_labs_count (val_labs));
390 for (vl = val_labs_first_sorted (val_labs, &j); vl != NULL;
391 vl = val_labs_next (val_labs, &j))
393 write_value (w, &vl->value, v);
394 write_string (w, vl->label);
399 /* Writes case ELEM to the portable file represented by H. */
401 pfm_write_case (struct pfm_writer *w, const struct ccase *c)
405 if (ferror (w->file))
408 for (i = 0; i < w->var_cnt; i++)
410 struct pfm_var *v = &w->vars[i];
413 write_float (w, case_num_idx (c, v->fv));
416 write_int (w, v->width);
417 buf_write (w, case_str_idx (c, v->fv), v->width);
421 return !pfm_write_error (w);
425 pfm_write_error (const struct pfm_writer *w)
427 return ferror (w->file);
430 /* Closes a portable file after we're done with it.
431 Returns true if successful, false if an I/O error occurred. */
433 pfm_close_writer (struct pfm_writer *w)
444 memset (buf, 'Z', sizeof buf);
445 buf_write (w, buf, w->lc >= 80 ? 80 : 80 - w->lc);
447 ok = !pfm_write_error (w);
448 if (fclose (w->file) == EOF)
452 msg (ME, _("An I/O error occurred writing portable file \"%s\"."),
453 fh_get_file_name (w->fh));
456 fh_close (w->fh, "portable file", "we");
464 /* Base-30 conversion.
466 Portable files represent numbers in base-30 format, so we need
467 to be able to convert real and integer number to that base.
468 Older versions of PSPP used libgmp to do so, but this added a
469 big library dependency to do just one thing. Now we do it
470 ourselves internally.
472 Important fact: base 30 is called "trigesimal". */
474 /* Conversion base. */
475 #define BASE 30 /* As an integer. */
476 #define LDBASE ((long double) BASE) /* As a long double. */
478 /* This is floor(log30(2**31)), the minimum number of trigesimal
479 digits that a `long int' can hold. */
482 /* pow_tab[i] = pow (30, pow (2, i)) */
483 static long double pow_tab[16];
485 /* Initializes pow_tab[]. */
489 static bool did_init = false;
493 /* Only initialize once. */
498 /* Set each element of pow_tab[] until we run out of numerical
501 for (power = 30.0L; power < DBL_MAX; power *= power)
503 assert (i < sizeof pow_tab / sizeof *pow_tab);
504 pow_tab[i++] = power;
508 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
510 pow30_nonnegative (int exponent)
515 assert (exponent >= 0);
516 assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
519 for (i = 0; exponent > 0; exponent >>= 1, i++)
526 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
532 return pow30_nonnegative (exponent);
534 return 1.L / pow30_nonnegative (-exponent);
537 /* Returns the character corresponding to TRIG. */
539 trig_to_char (int trig)
541 assert (trig >= 0 && trig < 30);
542 return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
545 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
546 null-terminated STRING. The trigesimal point is inserted
547 after TRIG_PLACES characters have been printed, if necessary
548 adding extra zeros at either end for correctness. Returns the
549 character after the formatted number. */
551 format_trig_digits (char *string,
552 const char trigs[], int trig_cnt, int trig_places)
557 while (trig_places++ < 0)
561 while (trig_cnt-- > 0)
563 if (trig_places-- == 0)
565 *string++ = trig_to_char (*trigs++);
567 while (trig_places-- > 0)
573 /* Helper function for format_trig_int() that formats VALUE as a
574 trigesimal integer at CP. VALUE must be nonnegative.
575 Returns the character following the formatted integer. */
577 recurse_format_trig_int (char *cp, int value)
579 int trig = value % BASE;
582 cp = recurse_format_trig_int (cp, value);
583 *cp++ = trig_to_char (trig);
587 /* Formats VALUE as a trigesimal integer in null-terminated
588 STRING[]. VALUE must be in the range -DBL_MAX...DBL_MAX. If
589 FORCE_SIGN is true, a sign is always inserted; otherwise, a
590 sign is only inserted if VALUE is negative. */
592 format_trig_int (int value, bool force_sign, char string[])
603 /* Format integer. */
604 string = recurse_format_trig_int (string, value);
609 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
610 rounding up or down. Returns true if TRIGS[] represents a
611 value greater than half, false if less than half. If TRIGS[]
612 is exactly half, examines TRIGS[-1] and returns true if odd,
613 false if even ("round to even"). */
615 should_round_up (const char trigs[], int trig_cnt)
617 assert (trig_cnt > 0);
619 if (*trigs < BASE / 2)
621 /* Less than half: round down. */
624 else if (*trigs > BASE / 2)
626 /* Greater than half: round up. */
631 /* Approximately half: look more closely. */
633 for (i = 1; i < trig_cnt; i++)
636 /* Slightly greater than half: round up. */
640 /* Exactly half: round to even. */
641 return trigs[-1] % 2;
645 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
646 carrying to the left as necessary. Returns true if
647 successful, false on failure (due to a carry out of the
648 leftmost position). */
650 try_round_up (char *trigs, int trig_cnt)
654 char *round_trig = trigs + --trig_cnt;
655 if (*round_trig != BASE - 1)
657 /* Round this trig up to the next value. */
662 /* Carry over to the next trig to the left. */
666 /* Ran out of trigs to carry. */
670 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
671 equivalent of at least BASE_10_PRECISION decimal digits of
672 precision. The output format may use conventional or
673 scientific notation. Missing, infinite, and extreme values
674 are represented with "*.". */
676 format_trig_double (long double value, int base_10_precision, char output[])
678 /* Original VALUE was negative? */
681 /* Number of significant trigesimals. */
682 int base_30_precision;
684 /* Base-2 significand and exponent for original VALUE. */
688 /* VALUE as a set of trigesimals. */
689 char buffer[DBL_DIG + 16];
693 /* Number of trigesimal places for trigs.
694 trigs[0] has coefficient 30**(trig_places - 1),
695 trigs[1] has coefficient 30**(trig_places - 2),
697 In other words, the trigesimal point is just before trigs[0].
701 /* Number of trigesimal places left to write into BUFFER. */
706 /* Handle special cases. */
712 /* Make VALUE positive. */
721 /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
722 point left or right as necessary. We approximate the
723 base-30 exponent by obtaining the base-2 exponent, then
724 multiplying by log30(2). This approximation is sufficient
725 to ensure that the adjusted VALUE is always in the range
726 0...30**6, an invariant of the loop below. */
728 base_2_sig = frexp (value, &base_2_exp);
729 if (errno != 0 || !finite (base_2_sig))
731 if (base_2_exp == 0 && base_2_sig == 0.)
733 if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
735 trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
736 value *= pow30 (CHUNK_SIZE - trig_places);
738 /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
741 for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
743 trigs_to_output -= CHUNK_SIZE)
748 /* The current chunk is just the integer part of VALUE,
749 truncated to the nearest integer. The chunk fits in a
752 assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
753 assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
757 /* Append the chunk, in base 30, to trigs[]. */
758 for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
760 trigs[trig_cnt + --trigs_left] = chunk % 30;
763 while (trigs_left > 0)
764 trigs[trig_cnt + --trigs_left] = 0;
765 trig_cnt += CHUNK_SIZE;
767 /* Proceed to the next chunk. */
770 value *= pow (LDBASE, CHUNK_SIZE);
773 /* Strip leading zeros. */
774 while (trig_cnt > 1 && *trigs == 0)
781 /* Round to requested precision, conservatively estimating the
782 required base-30 precision as 2/3 of the base-10 precision
783 (log30(10) = .68). */
784 assert (base_10_precision > 0);
785 if (base_10_precision > LDBL_DIG)
786 base_10_precision = LDBL_DIG;
787 base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
788 if (trig_cnt > base_30_precision)
790 if (should_round_up (trigs + base_30_precision,
791 trig_cnt - base_30_precision))
793 /* Try to round up. */
794 if (try_round_up (trigs, base_30_precision))
796 /* Rounding up worked. */
797 trig_cnt = base_30_precision;
801 /* Couldn't round up because we ran out of trigs to
802 carry into. Do the carry here instead. */
811 trig_cnt = base_30_precision;
816 /* No rounding required: fewer digits available than
820 /* Strip trailing zeros. */
821 while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
827 if (trig_places >= -1 && trig_places < trig_cnt + 3)
829 /* Use conventional notation. */
830 format_trig_digits (output, trigs, trig_cnt, trig_places);
834 /* Use scientific notation. */
836 op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
837 op = format_trig_int (trig_places - trig_cnt, true, op);
842 strcpy (output, "0");
846 strcpy (output, "*.");