a5a7357005b6776adc2ed43dbf735567ffd822f1
[pspp-builds.git] / src / var.h
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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #if !var_h
21 #define var_h 1
22
23 #include "format.h"
24
25 /* Values. */
26
27 /* Definition of the max length of a short string value, generally
28    eight characters.  */
29 #define MAX_SHORT_STRING ((SIZEOF_DOUBLE)>=8 ? ((SIZEOF_DOUBLE)+1)/2*2 : 8)
30 #define MIN_LONG_STRING (MAX_SHORT_STRING+1)
31
32 /* FYI: It is a bad situation if sizeof(flt64) < MAX_SHORT_STRING:
33    then short string missing values can be truncated in system files
34    because there's only room for as many characters as can fit in a
35    flt64. */
36 #if MAX_SHORT_STRING > 8
37 #error MAX_SHORT_STRING must be less than 8.
38 #endif
39
40 /* Special values. */
41 #define SYSMIS (-DBL_MAX)
42 #define LOWEST second_lowest_value
43 #define HIGHEST DBL_MAX
44
45 /* Describes one value, which is either a floating-point number or a
46    short string. */
47 union value
48   {
49     /* A numeric value. */
50     double f;
51
52     /* A short-string value. */
53     unsigned char s[MAX_SHORT_STRING];
54
55     /* This member is used by data-in.c to return a string result,
56        since it may need to return a long string.  As currently
57        implemented, it's a pointer to a static internal buffer in
58        data-in.c.
59
60        Also used by evaluate_expression() to return a string result.
61        As currently implemented, it's a pointer to a dynamic buffer in
62        the appropriate expression.
63
64        Also used by the AGGREGATE procedure in handling string
65        values. */
66     unsigned char *c;
67
68     /* Sometimes we insert value's in a hash table. */
69     unsigned long hash[SIZEOF_DOUBLE / SIZEOF_LONG];
70   };
71 \f
72 /* Frequency tables. */
73
74 /* Frequency table entry. */
75 struct freq
76   {
77     union value v;              /* The value. */
78     double c;                   /* The number of occurrences of the value. */
79   };
80
81 /* Types of frequency tables. */
82 enum
83   {
84     FRQM_GENERAL,
85     FRQM_INTEGER
86   };
87
88 /* Entire frequency table. */
89 struct freq_tab
90   {
91     int mode;                   /* FRQM_GENERAL or FRQM_INTEGER. */
92
93     /* General mode. */
94     struct hsh_table *data;     /* Undifferentiated data. */
95
96     /* Integer mode. */
97     double *vector;             /* Frequencies proper. */
98     int min, max;               /* The boundaries of the table. */
99     double out_of_range;        /* Sum of weights of out-of-range values. */
100     double sysmis;              /* Sum of weights of SYSMIS values. */
101
102     /* All modes. */
103     struct freq *valid;         /* Valid freqs. */
104     int n_valid;                /* Number of total freqs. */
105
106     struct freq *missing;       /* Missing freqs. */
107     int n_missing;              /* Number of missing freqs. */
108
109     /* Statistics. */
110     double total_cases;         /* Sum of weights of all cases. */
111     double valid_cases;         /* Sum of weights of valid cases. */
112   };
113
114 /* A complete set of 3 frequency tables. */
115 struct freq_tab_set
116   {
117     struct freq_tab miss;       /* Includes user-missing values. */
118     struct freq_tab no_miss;    /* Excludes user-missing values. */
119     struct freq_tab sel;        /* Identical to either miss or no_miss. */
120   };
121 \f
122 /* Procedures' private per-variable data. */
123
124 /* Structure name suffixes for private data:
125    _proc: for a procedure (i.e., LIST -> list_proc).
126    _trns: for a transformation (i.e., COMPUTE -> compute_trns.
127    _pgm: for an input program (i.e., DATA LIST -> data_list_pgm). */
128
129 /* CROSSTABS private data. */
130 struct crosstab_proc
131   {
132     /* Integer mode only. */
133     int min;                    /* Minimum value. */
134     int max;                    /* Maximum value + 1. */
135     int count;                  /* max - min. */
136   };
137
138 /* FREQUENCIES private data. */
139 enum
140   {
141     frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
142     frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
143     frq_sum, frq_n_stats
144   };
145
146 struct frequencies_proc
147   {
148     /* General mode. */
149     struct freq_tab tab;        /* Frequencies table to use. */
150
151     /* Percentiles. */
152     int n_groups;               /* Number of groups. */
153     double *groups;             /* Groups. */
154
155     /* Statistics. */
156     double stat[frq_n_stats];
157   };
158
159 /* LIST private data. */
160 struct list_proc
161   {
162     int newline;                /* Whether a new line begins here. */
163     int width;                  /* Field width. */
164     int vert;                   /* Whether to print the varname vertically. */
165   };
166
167 /* DESCRIPTIVES private data.  Note that the DESCRIPTIVES procedure also
168    has a transformation, descriptives_trns. */
169 enum
170   {
171     /* As these are used as bit indexes, there must be 32 or fewer.
172        Be very careful in adjusting these, see the structure below
173        and the table in descriptives.q. */
174     dsc_mean = 0, dsc_semean, dsc_stddev, dsc_variance, dsc_kurt,
175     dsc_sekurt, dsc_skew, dsc_seskew, dsc_range, dsc_min,
176     dsc_max, dsc_sum, dsc_n_stats
177   };
178
179 struct descriptives_proc
180   {
181     /* Miscellaneous. */
182     int dup;                    /* Finds duplicates in list of
183                                    variables. */
184     char zname[10];             /* Name for z-score variable. */
185
186     /* Counts. */
187     double valid, miss;         /* Valid, missing--general. */
188
189     /* Mean, moments about the mean. */
190     double X_bar, M2, M3, M4;
191     double min, max;
192
193     /* Statistics. */
194     double stats[dsc_n_stats];  /* Everything glommed together. */
195   };
196
197 /* GET private data. */
198 struct get_proc
199   {
200     int fv, nv;                 /* First, last, # of values. */
201   };
202
203 /* Sort order. */
204 enum
205   {
206     SRT_ASCEND,                 /* A, B, C, ..., X, Y, Z. */
207     SRT_DESCEND                 /* Z, Y, X, ..., C, B, A. */
208   };
209
210 /* SORT CASES private data. */
211 struct sort_cases_proc
212   {
213     int order;                  /* SRT_ASCEND or SRT_DESCEND. */
214   };
215
216 /* MODIFY VARS private data. */
217 struct modify_vars_proc
218   {
219     char new_name[9];           /* Variable's new name. */
220     int drop_this_var;          /* 0=keep this var, 1=drop this var. */
221     struct variable *next;      /* Next in linked list. */
222   };
223
224 /* MEANS private data. */
225 struct means_proc
226   {
227     double min, max;            /* Range for integer mode. */
228   };
229
230 /* Different types of variables for MATRIX DATA procedure.  Order is
231    important: these are used for sort keys. */
232 enum
233   {
234     MXD_SPLIT,                  /* SPLIT FILE variables. */
235     MXD_ROWTYPE,                /* ROWTYPE_. */
236     MXD_FACTOR,                 /* Factor variables. */
237     MXD_VARNAME,                /* VARNAME_. */
238     MXD_CONTINUOUS,             /* Continuous variables. */
239
240     MXD_COUNT
241   };
242
243 /* MATRIX DATA private data. */
244 struct matrix_data_proc
245   {
246     int vartype;                /* Variable type. */
247     int subtype;                /* Subtype. */
248   };
249
250 /* MATCH FILES private data. */
251 struct match_files_proc
252   {
253     struct variable *master;    /* Corresponding master file variable. */
254   };
255
256 \f
257 /* Script variables. */
258
259 /* Variable type. */
260 enum
261   {
262     NUMERIC,                    /* A numeric variable. */
263     ALPHA                       /* A string variable.  (STRING is pre-empted by lexer.h) */
264   };
265
266 /* Types of missing values.  Order is significant, see
267    mis-val.c:parse_numeric(), sfm-read.c:sfm_read_dictionary()
268    sfm-write.c:sfm_write_dictionary(),
269    sysfile-info.c:cmd_sysfile_info(), mis-val.c:copy_missing_values(),
270    pfm-read.c:read_variables(), pfm-write.c:write_variables(),
271    apply-dict.c:cmd_apply_dictionary(), and more (?). */
272 enum
273   {
274     MISSING_NONE,               /* No user-missing values. */
275     MISSING_1,                  /* One user-missing value. */
276     MISSING_2,                  /* Two user-missing values. */
277     MISSING_3,                  /* Three user-missing values. */
278     MISSING_RANGE,              /* [a,b]. */
279     MISSING_LOW,                /* (-inf,a]. */
280     MISSING_HIGH,               /* (a,+inf]. */
281     MISSING_RANGE_1,            /* [a,b], c. */
282     MISSING_LOW_1,              /* (-inf,a], b. */
283     MISSING_HIGH_1,             /* (a,+inf), b. */
284     MISSING_COUNT
285   };
286
287 /* A variable's dictionary entry.  Note: don't reorder name[] from the
288    first element; a pointer to `variable' should be a pointer to
289    member `name'.*/
290 struct variable
291   {
292     /* Required by parse_variables() to be in this order.  */
293     char name[9];               /* As a string. */
294     int index;                  /* Index into its dictionary's var[]. */
295     int type;                   /* NUMERIC or ALPHA. */
296     int foo;                    /* Used for temporary storage. */
297
298     /* Also important but parse_variables() doesn't need it.  Still,
299        check before reordering. */
300     int width;                  /* Size of string variables in chars. */
301     int fv, nv;                 /* Index into `value's, number of values. */
302     int left;                   /* 0=do not LEAVE, 1=LEAVE. */
303
304     /* Missing values. */
305     int miss_type;              /* One of the MISSING_* constants. */
306     union value missing[3];     /* User-missing value. */
307
308     /* Display formats. */
309     struct fmt_spec print;      /* Default format for PRINT. */
310     struct fmt_spec write;      /* Default format for WRITE. */
311
312     /* Labels. */
313     struct val_labs *val_labs;
314     char *label;                /* Variable label. */
315
316     /* Per-procedure info. */
317     struct get_proc get;
318     union
319       {
320         struct crosstab_proc crs;
321         struct descriptives_proc dsc;
322         struct frequencies_proc frq;
323         struct list_proc lst;
324         struct means_proc mns;
325         struct sort_cases_proc srt;
326         struct modify_vars_proc mfv;
327         struct matrix_data_proc mxd;
328         struct match_files_proc mtf;
329       }
330     p;
331   };
332
333 int compare_variables (const void *, const void *, void *);
334 unsigned hash_variable (const void *, void *);
335 \f
336 /* Cases. */
337
338 /* A single case.  (This doesn't need to be a struct anymore, but it
339    remains so for hysterical raisins.) */
340 struct ccase
341   {
342     union value data[1];
343   };
344 \f
345 /* Dictionary. */ 
346
347 /* Complete dictionary state. */
348 struct dictionary
349   {
350     struct variable **var;      /* Variable descriptions. */
351     struct hsh_table *name_tab; /* Variables arranged by name. */
352     int nvar;                   /* Number of variables. */
353
354     int N;                      /* Current case limit (N command). */
355     int nval;                   /* Number of value structures per case. */
356
357     int n_splits;               /* Number of SPLIT FILE variables. */
358     struct variable **splits;   /* List of SPLIT FILE vars. */
359     
360     char *label;                /* File label. */
361
362     int n_documents;            /* Number of lines of documents. */
363     char *documents;            /* Documents; 80*n_documents bytes in size. */
364
365     int weight_index;           /* `value' index of $WEIGHT, or -1 if none.
366                                    Call update_weighting() before using! */
367     char weight_var[9];         /* Name of WEIGHT variable. */
368
369     char filter_var[9];         /* Name of FILTER variable. */
370     /* Do not make another field the last field! or see
371        temporary.c:restore_dictionary() before doing so! */
372   };
373
374 /* This is the active file dictionary. */
375 extern struct dictionary default_dict;
376 \f
377 /* Transformation state. */
378
379 /* Default file handle for DATA LIST, REREAD, REPEATING DATA
380    commands. */
381 extern struct file_handle *default_handle;
382
383 /* PROCESS IF expression. */
384 extern struct expression *process_if_expr;
385 \f
386 /* TEMPORARY support. */
387
388 /* 1=TEMPORARY has been executed at some point. */
389 extern int temporary;
390
391 /* If temporary!=0, the saved dictionary. */
392 extern struct dictionary *temp_dict;
393
394 /* If temporary!=0, index into t_trns[] (declared far below) that
395    gives the point at which data should be written out.  -1 means that
396    the data shouldn't be changed since all transformations are
397    temporary. */
398 extern int temp_trns;
399
400 /* If FILTER is active, whether it was executed before or after
401    TEMPORARY. */
402 extern int FILTER_before_TEMPORARY;
403
404 void cancel_temporary (void);
405 \f
406 /* Functions. */
407
408 int is_varname (const char *);
409 int is_dict_varname (const struct dictionary *, const char *);
410
411 /* Flags for passing to fill_all_vars(). */
412 enum
413   {
414     FV_NONE = 0,                /* No flags. */
415     FV_NO_SYSTEM = 001,         /* Don't include system variables. */
416     FV_NO_SCRATCH = 002         /* Don't include scratch variables. */
417   };
418
419 void fill_all_vars (struct variable ***, int *, int flags);
420
421 void dump_split_vars (const struct ccase *);
422
423 int is_num_user_missing (double, const struct variable *);
424 int is_str_user_missing (const unsigned char[], const struct variable *);
425 int is_missing (const union value *, const struct variable *);
426 int is_system_missing (const union value *, const struct variable *);
427 int is_user_missing (const union value *, const struct variable *);
428 void copy_missing_values (struct variable *dest, const struct variable *src);
429
430 #if GLOBAL_DEBUGGING
431 struct variable *force_create_variable (struct dictionary *, const char *name,
432                                         int type, int width);
433 struct variable *force_dup_variable (struct dictionary *,
434                                      const struct variable *src,
435                                      const char *name);
436 #else
437 #define force_create_variable(A, B, C, D)       \
438         create_variable (A, B, C, D)
439 #define force_dup_variable(A, B, C)             \
440         dup_variable (A, B, C)
441 #endif
442
443 struct variable *create_variable (struct dictionary *, const char *name,
444                                   int type, int width);
445 void delete_variable (struct dictionary *, struct variable *v);
446 struct variable *find_variable (const char *name);
447 struct variable *find_dict_variable (const struct dictionary *,
448                                      const char *name);
449 void init_variable (struct dictionary *, struct variable *, const char *name,
450                     int type, int width);
451 void replace_variable (struct variable *, const char *name,
452                        int type, int width);
453 void clear_variable (struct dictionary *, struct variable *);
454 void rename_variable (struct dictionary *, struct variable *v,
455                       const char *new_name);
456 void discard_variables (void);
457 void clear_default_dict (void);
458 void copy_variable (struct variable *dest, const struct variable *src);
459 struct variable *dup_variable (struct dictionary *dict,
460                                const struct variable *src, const char *name);
461
462 struct variable *update_weighting (struct dictionary *);
463 void stop_weighting (struct dictionary *);
464
465 struct dictionary *save_dictionary (void);
466 void restore_dictionary (struct dictionary *);
467 void free_dictionary (struct dictionary *);
468 struct dictionary *new_dictionary (int copy);
469 \f
470 /* Transformations. */
471
472 /* Header for all transformations. */
473 struct trns_header
474   {
475     /* Index into t_trns[]. */
476     int index;
477
478     /* Transformation proc. */
479     int (*proc) (struct trns_header *, struct ccase *);
480
481     /* Garbage collector proc. */
482     void (*free) (struct trns_header *);
483   };
484
485 /* Array of transformations */
486 extern struct trns_header **t_trns;
487
488 /* Number of transformations, maximum number in array currently. */
489 extern int n_trns, m_trns;
490
491 /* Index of first transformation that is really a transformation.  Any
492    transformations before this belong to INPUT PROGRAM. */
493 extern int f_trns;
494
495 void add_transformation (struct trns_header *trns);
496 void cancel_transformations (void);
497 \f
498 /* Variable parsers. */
499
500 /* Only parse_variables() supports options other than PV_APPEND,
501    PV_SINGLE. */
502 enum
503   {
504     PV_NONE = 0,                /* No options. */
505     PV_SINGLE = 0001,           /* Restrict to a single varname or TO use. */
506     PV_DUPLICATE = 0002,        /* Don't merge duplicates. */
507     PV_APPEND = 0004,           /* Append to existing list. */
508     PV_NO_DUPLICATE = 0010,     /* Error on duplicates. */
509     PV_NUMERIC = 0020,          /* Vars must be numeric. */
510     PV_STRING = 0040,           /* Vars must be string. */
511     PV_SAME_TYPE = 00100,       /* All vars must be the same type. */
512     PV_NO_SCRATCH = 00200       /* Disallow scratch variables. */
513   };
514
515 struct variable *parse_variable (void);
516 struct variable *parse_dict_variable (struct dictionary *);
517 int parse_variables (struct dictionary *dict, struct variable ***v,
518                      int *nv, int pv_opts);
519 int parse_DATA_LIST_vars (char ***names, int *nnames, int pv_opts);
520 int parse_mixed_vars (char ***names, int *nnames, int pv_opts);
521
522 #endif /* !var_h */