Fix memory leaks.
[pspp-builds.git] / src / frequencies.q
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 /*
21   TODO:
22
23   * Remember that histograms, bar charts need mean, stddev.
24 */
25
26 #include <config.h>
27 #include "error.h"
28 #include <math.h>
29 #include <stdlib.h>
30 #include "alloc.h"
31 #include "bitvector.h"
32 #include "case.h"
33 #include "hash.h"
34 #include "pool.h"
35 #include "command.h"
36 #include "lexer.h"
37 #include "moments.h"
38 #include "error.h"
39 #include "algorithm.h"
40 #include "magic.h"
41 #include "misc.h"
42 #include "output.h"
43 #include "som.h"
44 #include "str.h"
45 #include "tab.h"
46 #include "value-labels.h"
47 #include "var.h"
48 #include "vfm.h"
49 #include "settings.h"
50
51 #include "debug-print.h"
52
53 /* (specification)
54    FREQUENCIES (frq_):
55      *variables=custom;
56      format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
57             table:limit(n:limit,"%s>0")/notable/!table, 
58             labels:!labels/nolabels,
59             sort:!avalue/dvalue/afreq/dfreq,
60             spaces:!single/double,
61             paging:newpage/!oldpage;
62      missing=miss:include/!exclude;
63      barchart(ba_)=:minimum(d:min),
64             :maximum(d:max),
65             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
66      histogram(hi_)=:minimum(d:min),
67             :maximum(d:max),
68             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
69             norm:!nonormal/normal,
70             incr:increment(d:inc,"%s>0");
71      hbar(hb_)=:minimum(d:min),
72             :maximum(d:max),
73             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
74             norm:!nonormal/normal,
75             incr:increment(d:inc,"%s>0");
76      grouped=custom;
77      ntiles=custom;
78      percentiles=custom;
79      statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
80             7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
81             13|default,14|seskewness,15|sekurtosis,all,none.
82 */
83 /* (declarations) */
84 /* (functions) */
85
86 /* Description of a statistic. */
87 struct frq_info
88   {
89     int st_indx;                /* Index into a_statistics[]. */
90     const char *s10;            /* Identifying string. */
91   };
92
93 /* Table of statistics, indexed by dsc_*. */
94 static struct frq_info st_name[frq_n_stats + 1] =
95 {
96   {FRQ_ST_MEAN, N_("Mean")},
97   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
98   {FRQ_ST_MEDIAN, N_("Median")},
99   {FRQ_ST_MODE, N_("Mode")},
100   {FRQ_ST_STDDEV, N_("Std Dev")},
101   {FRQ_ST_VARIANCE, N_("Variance")},
102   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
103   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
104   {FRQ_ST_SKEWNESS, N_("Skewness")},
105   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
106   {FRQ_ST_RANGE, N_("Range")},
107   {FRQ_ST_MINIMUM, N_("Minimum")},
108   {FRQ_ST_MAXIMUM, N_("Maximum")},
109   {FRQ_ST_SUM, N_("Sum")},
110   {-1, 0},
111 };
112
113 /* Percentiles to calculate. */
114
115 struct percentile
116 {
117   double p;        /* the %ile to be calculated */
118   double value;    /* the %ile's value */
119   double x1;       /* The datum value <= the percentile */
120   double x2;       /* The datum value >= the percentile */
121   int flag;        
122   int flag2;       /* Set to 1 if this percentile value has been found */
123 };
124
125 static struct percentile *percentiles;
126 static int n_percentiles;
127
128 static int implicit_50th ; 
129
130 /* Groups of statistics. */
131 #define BI          BIT_INDEX
132 #define frq_default                                                     \
133         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
134 #define frq_all                                                 \
135         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
136          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
137          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
138          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
139          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
140
141 /* Statistics; number of statistics. */
142 static unsigned long stats;
143 static int n_stats;
144
145 /* Types of graphs. */
146 enum
147   {
148     GFT_NONE,                   /* Don't draw graphs. */
149     GFT_BAR,                    /* Draw bar charts. */
150     GFT_HIST,                   /* Draw histograms. */
151     GFT_HBAR                    /* Draw bar charts or histograms at our discretion. */
152   };
153
154 /* Parsed command. */
155 static struct cmd_frequencies cmd;
156
157 /* Summary of the barchart, histogram, and hbar subcommands. */
158 static int chart;               /* NONE/BAR/HIST/HBAR. */
159 static double min, max;         /* Minimum, maximum on y axis. */
160 static int format;              /* FREQ/PERCENT: Scaling of y axis. */
161 static double scale, incr;      /* FIXME */
162 static int normal;              /* FIXME */
163
164 /* Variables for which to calculate statistics. */
165 static int n_variables;
166 static struct variable **v_variables;
167
168 /* Arenas used to store semi-permanent storage. */
169 static struct pool *int_pool;   /* Integer mode. */
170 static struct pool *gen_pool;   /* General mode. */
171
172 /* Easier access to a_statistics. */
173 #define stat cmd.a_statistics
174
175 static void determine_charts (void);
176
177 static void precalc (void *);
178 static int calc (struct ccase *, void *);
179 static void postcalc (void *);
180
181 static void postprocess_freq_tab (struct variable *);
182 static void dump_full (struct variable *);
183 static void dump_condensed (struct variable *);
184 static void dump_statistics (struct variable *, int show_varname);
185 static void cleanup_freq_tab (struct variable *);
186
187 static hsh_hash_func hash_value_numeric, hash_value_alpha;
188 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
189 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
190 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
191 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
192 \f
193 /* Parser and outline. */
194
195 static int internal_cmd_frequencies (void);
196
197 int
198 cmd_frequencies (void)
199 {
200   int result;
201
202   int_pool = pool_create ();
203   result = internal_cmd_frequencies ();
204   pool_destroy (int_pool);
205   int_pool=0;
206   pool_destroy (gen_pool);
207   gen_pool=0;
208   free (v_variables);
209   v_variables=0;
210   return result;
211 }
212
213 static int
214 internal_cmd_frequencies (void)
215 {
216   int i;
217
218   n_percentiles = 0;
219   percentiles = NULL;
220
221   n_variables = 0;
222   v_variables = NULL;
223
224   for (i = 0; i < dict_get_var_cnt (default_dict); i++)
225     dict_get_var(default_dict, i)->p.frq.used = 0;
226
227   if (!parse_frequencies (&cmd))
228     return CMD_FAILURE;
229
230   if (cmd.onepage_limit == NOT_LONG)
231     cmd.onepage_limit = 50;
232
233   /* Figure out statistics to calculate. */
234   stats = 0;
235   if (stat[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
236     stats |= frq_default;
237   if (stat[FRQ_ST_ALL])
238     stats |= frq_all;
239   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
240     stats &= ~frq_median;
241   for (i = 0; i < frq_n_stats; i++)
242     if (stat[st_name[i].st_indx])
243       stats |= BIT_INDEX (i);
244   if (stats & frq_kurt)
245     stats |= frq_sekurt;
246   if (stats & frq_skew)
247     stats |= frq_seskew;
248
249   /* Calculate n_stats. */
250   n_stats = 0;
251   for (i = 0; i < frq_n_stats; i++)
252     if ((stats & BIT_INDEX (i)))
253       n_stats++;
254
255   /* Charting. */
256   determine_charts ();
257   if (chart != GFT_NONE || cmd.sbc_ntiles)
258     cmd.sort = FRQ_AVALUE;
259
260   /* Do it! */
261   procedure_with_splits (precalc, calc, postcalc, NULL);
262
263   return CMD_SUCCESS;
264 }
265
266 /* Figure out which charts the user requested.  */
267 static void
268 determine_charts (void)
269 {
270   int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) + (!!cmd.sbc_hbar);
271
272   if (!count)
273     {
274       chart = GFT_NONE;
275       return;
276     }
277   else if (count > 1)
278     {
279       chart = GFT_HBAR;
280       msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
281            "given.  HBAR will be assumed.  Argument values will be "
282            "given precedence increasing along the order given."));
283     }
284   else if (cmd.sbc_histogram)
285     chart = GFT_HIST;
286   else if (cmd.sbc_barchart)
287     chart = GFT_BAR;
288   else
289     chart = GFT_HBAR;
290
291   min = max = SYSMIS;
292   format = FRQ_FREQ;
293   scale = SYSMIS;
294   incr = SYSMIS;
295   normal = 0;
296
297   if (cmd.sbc_barchart)
298     {
299       if (cmd.ba_min != SYSMIS)
300         min = cmd.ba_min;
301       if (cmd.ba_max != SYSMIS)
302         max = cmd.ba_max;
303       if (cmd.ba_scale == FRQ_FREQ)
304         {
305           format = FRQ_FREQ;
306           scale = cmd.ba_freq;
307         }
308       else if (cmd.ba_scale == FRQ_PERCENT)
309         {
310           format = FRQ_PERCENT;
311           scale = cmd.ba_pcnt;
312         }
313     }
314
315   if (cmd.sbc_histogram)
316     {
317       if (cmd.hi_min != SYSMIS)
318         min = cmd.hi_min;
319       if (cmd.hi_max != SYSMIS)
320         max = cmd.hi_max;
321       if (cmd.hi_scale == FRQ_FREQ)
322         {
323           format = FRQ_FREQ;
324           scale = cmd.hi_freq;
325         }
326       else if (cmd.hi_scale == FRQ_PERCENT)
327         {
328           format = FRQ_PERCENT;
329           scale = cmd.ba_pcnt;
330         }
331       if (cmd.hi_norm)
332         normal = 1;
333       if (cmd.hi_incr == FRQ_INCREMENT)
334         incr = cmd.hi_inc;
335     }
336
337   if (cmd.sbc_hbar)
338     {
339       if (cmd.hb_min != SYSMIS)
340         min = cmd.hb_min;
341       if (cmd.hb_max != SYSMIS)
342         max = cmd.hb_max;
343       if (cmd.hb_scale == FRQ_FREQ)
344         {
345           format = FRQ_FREQ;
346           scale = cmd.hb_freq;
347         }
348       else if (cmd.hb_scale == FRQ_PERCENT)
349         {
350           format = FRQ_PERCENT;
351           scale = cmd.ba_pcnt;
352         }
353       if (cmd.hb_norm)
354         normal = 1;
355       if (cmd.hb_incr == FRQ_INCREMENT)
356         incr = cmd.hb_inc;
357     }
358
359   if (min != SYSMIS && max != SYSMIS && min >= max)
360     {
361       msg (SE, _("MAX must be greater than or equal to MIN, if both are "
362            "specified.  However, MIN was specified as %g and MAX as %g.  "
363            "MIN and MAX will be ignored."), min, max);
364       min = max = SYSMIS;
365     }
366 }
367
368 /* Add data from case C to the frequency table. */
369 static int
370 calc (struct ccase *c, void *aux UNUSED)
371 {
372   double weight;
373   int i;
374   int bad_warn = 1;
375
376   weight = dict_get_case_weight (default_dict, c, &bad_warn);
377
378   for (i = 0; i < n_variables; i++)
379     {
380       struct variable *v = v_variables[i];
381       const union value *val = case_data (c, v->fv);
382       struct freq_tab *ft = &v->p.frq.tab;
383
384       switch (v->p.frq.tab.mode)
385         {
386           case FRQM_GENERAL:
387             {
388               /* General mode. */
389               struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
390           
391               if (*fpp != NULL)
392                 (*fpp)->c += weight;
393               else
394                 {
395                   struct freq *fp = *fpp = pool_alloc (gen_pool, sizeof *fp);
396                   fp->v = *val;
397                   fp->c = weight;
398                 }
399             }
400           break;
401         case FRQM_INTEGER:
402           /* Integer mode. */
403           if (val->f == SYSMIS)
404             v->p.frq.tab.sysmis += weight;
405           else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
406             {
407               int i = val->f;
408               if (i >= v->p.frq.tab.min && i <= v->p.frq.tab.max)
409                 v->p.frq.tab.vector[i - v->p.frq.tab.min] += weight;
410             }
411           else
412             v->p.frq.tab.out_of_range += weight;
413           break;
414         default:
415           assert (0);
416         }
417     }
418   return 1;
419 }
420
421 /* Prepares each variable that is the target of FREQUENCIES by setting
422    up its hash table. */
423 static void
424 precalc (void *aux UNUSED)
425 {
426   int i;
427
428   pool_destroy (gen_pool);
429   gen_pool = pool_create ();
430   
431   for (i = 0; i < n_variables; i++)
432     {
433       struct variable *v = v_variables[i];
434
435       if (v->p.frq.tab.mode == FRQM_GENERAL)
436         {
437           hsh_hash_func *hash;
438           hsh_compare_func *compare;
439
440           if (v->type == NUMERIC) 
441             {
442               hash = hash_value_numeric;
443               compare = compare_value_numeric_a; 
444             }
445           else 
446             {
447               hash = hash_value_alpha;
448               compare = compare_value_alpha_a;
449             }
450           v->p.frq.tab.data = hsh_create (16, compare, hash, NULL, v);
451         }
452       else
453         {
454           int j;
455
456           for (j = (v->p.frq.tab.max - v->p.frq.tab.min); j >= 0; j--)
457             v->p.frq.tab.vector[j] = 0.0;
458           v->p.frq.tab.out_of_range = 0.0;
459           v->p.frq.tab.sysmis = 0.0;
460         }
461     }
462 }
463
464 /* Finishes up with the variables after frequencies have been
465    calculated.  Displays statistics, percentiles, ... */
466 static void
467 postcalc (void *aux UNUSED)
468 {
469   int i;
470
471   for (i = 0; i < n_variables; i++)
472     {
473       struct variable *v = v_variables[i];
474       int n_categories;
475       int dumped_freq_tab = 1;
476
477       postprocess_freq_tab (v);
478
479       /* Frequencies tables. */
480       n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
481       if (cmd.table == FRQ_TABLE
482           || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
483         switch (cmd.cond)
484           {
485           case FRQ_CONDENSE:
486             dump_condensed (v);
487             break;
488           case FRQ_STANDARD:
489             dump_full (v);
490             break;
491           case FRQ_ONEPAGE:
492             if (n_categories > cmd.onepage_limit)
493               dump_condensed (v);
494             else
495               dump_full (v);
496             break;
497           default:
498             assert (0);
499           }
500       else
501         dumped_freq_tab = 0;
502
503       /* Statistics. */
504       if (n_stats)
505         dump_statistics (v, !dumped_freq_tab);
506
507       cleanup_freq_tab (v);
508     }
509 }
510
511 /* Returns the comparison function that should be used for
512    sorting a frequency table by FRQ_SORT using VAR_TYPE
513    variables. */
514 static hsh_compare_func *
515 get_freq_comparator (int frq_sort, int var_type) 
516 {
517   /* Note that q2c generates tags beginning with 1000. */
518   switch (frq_sort | (var_type << 16))
519     {
520     case FRQ_AVALUE | (NUMERIC << 16):  return compare_value_numeric_a;
521     case FRQ_AVALUE | (ALPHA << 16):    return compare_value_alpha_a;
522     case FRQ_DVALUE | (NUMERIC << 16):  return compare_value_numeric_d;
523     case FRQ_DVALUE | (ALPHA << 16):    return compare_value_alpha_d;
524     case FRQ_AFREQ | (NUMERIC << 16):   return compare_freq_numeric_a;
525     case FRQ_AFREQ | (ALPHA << 16):     return compare_freq_alpha_a;
526     case FRQ_DFREQ | (NUMERIC << 16):   return compare_freq_numeric_d;
527     case FRQ_DFREQ | (ALPHA << 16):     return compare_freq_alpha_d;
528     default: assert (0);
529     }
530
531   return 0;
532 }
533
534 /* Returns nonzero iff the value in struct freq F is non-missing
535    for variable V. */
536 static int
537 not_missing (const void *f_, void *v_) 
538 {
539   const struct freq *f = f_;
540   struct variable *v = v_;
541
542   return !is_missing (&f->v, v);
543 }
544
545 /* Summarizes the frequency table data for variable V. */
546 static void
547 postprocess_freq_tab (struct variable *v)
548 {
549   hsh_compare_func *compare;
550   struct freq_tab *ft;
551   size_t count;
552   void **data;
553   struct freq *freqs, *f;
554   size_t i;
555
556   assert (v->p.frq.tab.mode == FRQM_GENERAL);
557   compare = get_freq_comparator (cmd.sort, v->type);
558   ft = &v->p.frq.tab;
559
560   /* Extract data from hash table. */
561   count = hsh_count (ft->data);
562   data = hsh_data (ft->data);
563
564   /* Copy dereferenced data into freqs. */
565   freqs = xmalloc (count * sizeof *freqs);
566   for (i = 0; i < count; i++) 
567     {
568       struct freq *f = data[i];
569       freqs[i] = *f; 
570     }
571
572   /* Put data into ft. */
573   ft->valid = freqs;
574   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
575   ft->missing = freqs + ft->n_valid;
576   ft->n_missing = count - ft->n_valid;
577
578   /* Sort data. */
579   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
580   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
581
582   /* Summary statistics. */
583   ft->valid_cases = 0.0;
584   for(i = 0 ;  i < ft->n_valid ; ++i ) 
585     {
586       f = &ft->valid[i];
587       ft->valid_cases += f->c;
588
589     }
590
591   ft->total_cases = ft->valid_cases ; 
592   for(i = 0 ;  i < ft->n_missing ; ++i ) 
593     {
594       f = &ft->missing[i];
595       ft->total_cases += f->c;
596     }
597
598 }
599
600 /* Frees the frequency table for variable V. */
601 static void
602 cleanup_freq_tab (struct variable *v)
603 {
604   assert (v->p.frq.tab.mode == FRQM_GENERAL);
605   free (v->p.frq.tab.valid);
606   hsh_destroy (v->p.frq.tab.data);
607 }
608
609 /* Parses the VARIABLES subcommand, adding to
610    {n_variables,v_variables}. */
611 static int
612 frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
613 {
614   int mode;
615   int min = 0, max = 0;
616
617   int old_n_variables = n_variables;
618   int i;
619
620   lex_match ('=');
621   if (token != T_ALL && (token != T_ID
622                          || dict_lookup_var (default_dict, tokid) == NULL))
623     return 2;
624
625   if (!parse_variables (default_dict, &v_variables, &n_variables,
626                         PV_APPEND | PV_NO_SCRATCH))
627     return 0;
628
629   for (i = old_n_variables; i < n_variables; i++)
630     v_variables[i]->p.frq.tab.mode = FRQM_GENERAL;
631
632   if (!lex_match ('('))
633     mode = FRQM_GENERAL;
634   else
635     {
636       mode = FRQM_INTEGER;
637       if (!lex_force_int ())
638         return 0;
639       min = lex_integer ();
640       lex_get ();
641       if (!lex_force_match (','))
642         return 0;
643       if (!lex_force_int ())
644         return 0;
645       max = lex_integer ();
646       lex_get ();
647       if (!lex_force_match (')'))
648         return 0;
649       if (max < min)
650         {
651           msg (SE, _("Upper limit of integer mode value range must be "
652                      "greater than lower limit."));
653           return 0;
654         }
655     }
656
657   for (i = old_n_variables; i < n_variables; i++)
658     {
659       struct variable *v = v_variables[i];
660
661       if (v->p.frq.used != 0)
662         {
663           msg (SE, _("Variable %s specified multiple times on VARIABLES "
664                      "subcommand."), v->name);
665           return 0;
666         }
667       
668       v->p.frq.used = 1;                /* Used simply as a marker. */
669
670       v->p.frq.tab.valid = v->p.frq.tab.missing = NULL;
671
672       if (mode == FRQM_INTEGER)
673         {
674           if (v->type != NUMERIC)
675             {
676               msg (SE, _("Integer mode specified, but %s is not a numeric "
677                          "variable."), v->name);
678               return 0;
679             }
680           
681           v->p.frq.tab.min = min;
682           v->p.frq.tab.max = max;
683           v->p.frq.tab.vector = pool_alloc (int_pool,
684                                             sizeof (struct freq) * (max - min + 1));
685         }
686       else
687         v->p.frq.tab.vector = NULL;
688
689       v->p.frq.n_groups = 0;
690       v->p.frq.groups = NULL;
691     }
692   return 1;
693 }
694
695 /* Parses the GROUPED subcommand, setting the frq.{n_grouped,grouped}
696    fields of specified variables. */
697 static int
698 frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
699 {
700   lex_match ('=');
701   if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
702       || token == T_ID)
703     for (;;)
704       {
705         int i;
706
707         /* Max, current size of list; list itself. */
708         int nl, ml;
709         double *dl;
710
711         /* Variable list. */
712         int n;
713         struct variable **v;
714
715         if (!parse_variables (default_dict, &v, &n,
716                               PV_NO_DUPLICATE | PV_NUMERIC))
717           return 0;
718         if (lex_match ('('))
719           {
720             nl = ml = 0;
721             dl = NULL;
722             while (token == T_NUM)
723               {
724                 if (nl >= ml)
725                   {
726                     ml += 16;
727                     dl = pool_realloc (int_pool, dl, ml * sizeof (double));
728                   }
729                 dl[nl++] = tokval;
730                 lex_get ();
731                 lex_match (',');
732               }
733             /* Note that nl might still be 0 and dl might still be
734                NULL.  That's okay. */
735             if (!lex_match (')'))
736               {
737                 free (v);
738                 msg (SE, _("`)' expected after GROUPED interval list."));
739                 return 0;
740               }
741           }
742         else 
743           {
744             nl = 0;
745             dl = NULL;
746           }
747
748         for (i = 0; i < n; i++)
749           {
750             if (v[i]->p.frq.used == 0)
751               msg (SE, _("Variables %s specified on GROUPED but not on "
752                    "VARIABLES."), v[i]->name);
753             if (v[i]->p.frq.groups != NULL)
754               msg (SE, _("Variables %s specified multiple times on GROUPED "
755                    "subcommand."), v[i]->name);
756             else
757               {
758                 v[i]->p.frq.n_groups = nl;
759                 v[i]->p.frq.groups = dl;
760               }
761           }
762         free (v);
763         if (!lex_match ('/'))
764           break;
765         if ((token != T_ID || dict_lookup_var (default_dict, tokid) != NULL)
766             && token != T_ALL)
767           {
768             lex_put_back ('/');
769             break;
770           }
771       }
772
773   return 1;
774 }
775
776 /* Adds X to the list of percentiles, keeping the list in proper
777    order. */
778 static void
779 add_percentile (double x)
780 {
781   int i;
782
783   for (i = 0; i < n_percentiles; i++)
784     if (x <= percentiles[i].p)
785       break;
786
787   if (i >= n_percentiles || tokval != percentiles[i].p)
788     {
789       percentiles
790         = pool_realloc (int_pool, percentiles,
791                         (n_percentiles + 1) * sizeof (struct percentile ));
792
793       if (i < n_percentiles)
794           memmove (&percentiles[i + 1], &percentiles[i],
795                    (n_percentiles - i) * sizeof (struct percentile) );
796
797       percentiles[i].p = x;
798       n_percentiles++;
799     }
800 }
801
802 /* Parses the PERCENTILES subcommand, adding user-specified
803    percentiles to the list. */
804 static int
805 frq_custom_percentiles (struct cmd_frequencies *cmd UNUSED)
806 {
807   lex_match ('=');
808   if (token != T_NUM)
809     {
810       msg (SE, _("Percentile list expected after PERCENTILES."));
811       return 0;
812     }
813   
814   do
815     {
816       if (tokval < 0 || tokval > 100)
817         {
818           msg (SE, _("Percentiles must be between 0 and 100."));
819           return 0;
820         }
821       
822       add_percentile (tokval / 100.0);
823       lex_get ();
824       lex_match (',');
825     }
826   while (token == T_NUM);
827   return 1;
828 }
829
830 /* Parses the NTILES subcommand, adding the percentiles that
831    correspond to the specified evenly-distributed ntiles. */
832 static int
833 frq_custom_ntiles (struct cmd_frequencies *cmd UNUSED)
834 {
835   int i;
836
837   lex_match ('=');
838   if (!lex_force_int ())
839     return 0;
840   for (i = 1; i < lex_integer (); i++)
841     add_percentile (1.0 / lex_integer () * i);
842   lex_get ();
843   return 1;
844 }
845 \f
846 /* Comparison functions. */
847
848 /* Hash of numeric values. */
849 static unsigned
850 hash_value_numeric (const void *value_, void *foo UNUSED)
851 {
852   const struct freq *value = value_;
853   return hsh_hash_double (value->v.f);
854 }
855
856 /* Hash of string values. */
857 static unsigned
858 hash_value_alpha (const void *value_, void *v_)
859 {
860   const struct freq *value = value_;
861   struct variable *v = v_;
862
863   return hsh_hash_bytes (value->v.s, v->width);
864 }
865
866 /* Ascending numeric compare of values. */
867 static int
868 compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
869 {
870   const struct freq *a = a_;
871   const struct freq *b = b_;
872
873   if (a->v.f > b->v.f)
874     return 1;
875   else if (a->v.f < b->v.f)
876     return -1;
877   else
878     return 0;
879 }
880
881 /* Ascending string compare of values. */
882 static int
883 compare_value_alpha_a (const void *a_, const void *b_, void *v_)
884 {
885   const struct freq *a = a_;
886   const struct freq *b = b_;
887   const struct variable *v = v_;
888
889   return memcmp (a->v.s, b->v.s, v->width);
890 }
891
892 /* Descending numeric compare of values. */
893 static int
894 compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
895 {
896   return -compare_value_numeric_a (a, b, foo);
897 }
898
899 /* Descending string compare of values. */
900 static int
901 compare_value_alpha_d (const void *a, const void *b, void *v)
902 {
903   return -compare_value_alpha_a (a, b, v);
904 }
905
906 /* Ascending numeric compare of frequency;
907    secondary key on ascending numeric value. */
908 static int
909 compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
910 {
911   const struct freq *a = a_;
912   const struct freq *b = b_;
913
914   if (a->c > b->c)
915     return 1;
916   else if (a->c < b->c)
917     return -1;
918
919   if (a->v.f > b->v.f)
920     return 1;
921   else if (a->v.f < b->v.f)
922     return -1;
923   else
924     return 0;
925 }
926
927 /* Ascending numeric compare of frequency;
928    secondary key on ascending string value. */
929 static int
930 compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
931 {
932   const struct freq *a = a_;
933   const struct freq *b = b_;
934   const struct variable *v = v_;
935
936   if (a->c > b->c)
937     return 1;
938   else if (a->c < b->c)
939     return -1;
940   else
941     return memcmp (a->v.s, b->v.s, v->width);
942 }
943
944 /* Descending numeric compare of frequency;
945    secondary key on ascending numeric value. */
946 static int
947 compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
948 {
949   const struct freq *a = a_;
950   const struct freq *b = b_;
951
952   if (a->c > b->c)
953     return -1;
954   else if (a->c < b->c)
955     return 1;
956
957   if (a->v.f > b->v.f)
958     return 1;
959   else if (a->v.f < b->v.f)
960     return -1;
961   else
962     return 0;
963 }
964
965 /* Descending numeric compare of frequency;
966    secondary key on ascending string value. */
967 static int
968 compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
969 {
970   const struct freq *a = a_;
971   const struct freq *b = b_;
972   const struct variable *v = v_;
973
974   if (a->c > b->c)
975     return -1;
976   else if (a->c < b->c)
977     return 1;
978   else
979     return memcmp (a->v.s, b->v.s, v->width);
980 }
981 \f
982 /* Frequency table display. */
983
984 /* Sets the widths of all the columns and heights of all the rows in
985    table T for driver D. */
986 static void
987 full_dim (struct tab_table *t, struct outp_driver *d)
988 {
989   int lab = cmd.labels == FRQ_LABELS;
990   int i;
991
992   if (lab)
993     t->w[0] = min (tab_natural_width (t, d, 0), d->prop_em_width * 15);
994   for (i = lab; i < lab + 5; i++)
995     t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
996   for (i = 0; i < t->nr; i++)
997     t->h[i] = d->font_height;
998 }
999
1000 /* Displays a full frequency table for variable V. */
1001 static void
1002 dump_full (struct variable * v)
1003 {
1004   int n_categories;
1005   struct freq *f;
1006   struct tab_table *t;
1007   int r;
1008   double cum_total = 0.0;
1009   double cum_freq = 0.0;
1010
1011   struct init
1012     {
1013       int c, r;
1014       const char *s;
1015     };
1016
1017   struct init *p;
1018
1019   static struct init vec[] =
1020   {
1021     {4, 0, N_("Valid")},
1022     {5, 0, N_("Cum")},
1023     {1, 1, N_("Value")},
1024     {2, 1, N_("Frequency")},
1025     {3, 1, N_("Percent")},
1026     {4, 1, N_("Percent")},
1027     {5, 1, N_("Percent")},
1028     {0, 0, NULL},
1029     {1, 0, NULL},
1030     {2, 0, NULL},
1031     {3, 0, NULL},
1032     {-1, -1, NULL},
1033   };
1034
1035   int lab = cmd.labels == FRQ_LABELS;
1036
1037   n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
1038   t = tab_create (5 + lab, n_categories + 3, 0);
1039   tab_headers (t, 0, 0, 2, 0);
1040   tab_dim (t, full_dim);
1041
1042   if (lab)
1043     tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1044   for (p = vec; p->s; p++)
1045     tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1046                   TAB_CENTER | TAT_TITLE, gettext (p->s));
1047
1048   r = 2;
1049   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1050     {
1051       double percent, valid_percent;
1052
1053       cum_freq += f->c;
1054
1055       percent = f->c / v->p.frq.tab.total_cases * 100.0;
1056       valid_percent = f->c / v->p.frq.tab.valid_cases * 100.0;
1057       cum_total += valid_percent;
1058
1059       if (lab)
1060         {
1061           const char *label = val_labs_find (v->val_labs, f->v);
1062           if (label != NULL)
1063             tab_text (t, 0, r, TAB_LEFT, label);
1064         }
1065
1066       tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1067       tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1068       tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1069       tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1070       tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1071       r++;
1072     }
1073   for (; f < &v->p.frq.tab.valid[n_categories]; f++)
1074     {
1075       cum_freq += f->c;
1076
1077       if (lab)
1078         {
1079           const char *label = val_labs_find (v->val_labs, f->v);
1080           if (label != NULL)
1081             tab_text (t, 0, r, TAB_LEFT, label);
1082         }
1083
1084       tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1085       tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1086       tab_float (t, 2 + lab, r, TAB_NONE,
1087                      f->c / v->p.frq.tab.total_cases * 100.0, 5, 1);
1088       tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1089       r++;
1090     }
1091
1092   tab_box (t, TAL_1, TAL_1,
1093            cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1094            0, 0, 4 + lab, r);
1095   tab_hline (t, TAL_2, 0, 4 + lab, 2);
1096   tab_hline (t, TAL_2, 0, 4 + lab, r);
1097   tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1098   tab_vline (t, TAL_0, 1, r, r);
1099   tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1100   tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1101   tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1102
1103   tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1104   tab_submit (t);
1105 }
1106
1107 /* Sets the widths of all the columns and heights of all the rows in
1108    table T for driver D. */
1109 static void
1110 condensed_dim (struct tab_table *t, struct outp_driver *d)
1111 {
1112   int cum_w = max (outp_string_width (d, _("Cum")),
1113                    max (outp_string_width (d, _("Cum")),
1114                         outp_string_width (d, "000")));
1115
1116   int i;
1117
1118   for (i = 0; i < 2; i++)
1119     t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1120   for (i = 2; i < 4; i++)
1121     t->w[i] = cum_w;
1122   for (i = 0; i < t->nr; i++)
1123     t->h[i] = d->font_height;
1124 }
1125
1126 /* Display condensed frequency table for variable V. */
1127 static void
1128 dump_condensed (struct variable * v)
1129 {
1130   int n_categories;
1131   struct freq *f;
1132   struct tab_table *t;
1133   int r;
1134   double cum_total = 0.0;
1135
1136   n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
1137   t = tab_create (4, n_categories + 2, 0);
1138
1139   tab_headers (t, 0, 0, 2, 0);
1140   tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1141   tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1142   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1143   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1144   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1145   tab_dim (t, condensed_dim);
1146
1147   r = 2;
1148   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1149     {
1150       double percent;
1151
1152       percent = f->c / v->p.frq.tab.total_cases * 100.0;
1153       cum_total += f->c / v->p.frq.tab.valid_cases * 100.0;
1154
1155       tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1156       tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1157       tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1158       tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1159       r++;
1160     }
1161   for (; f < &v->p.frq.tab.valid[n_categories]; f++)
1162     {
1163       tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1164       tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1165       tab_float (t, 2, r, TAB_NONE,
1166                  f->c / v->p.frq.tab.total_cases * 100.0, 3, 0);
1167       r++;
1168     }
1169
1170   tab_box (t, TAL_1, TAL_1,
1171            cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1172            0, 0, 3, r - 1);
1173   tab_hline (t, TAL_2, 0, 3, 2);
1174   tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1175   tab_columns (t, SOM_COL_DOWN, 1);
1176   tab_submit (t);
1177 }
1178 \f
1179 /* Statistical display. */
1180
1181 /* Calculates all the pertinent statistics for variable V, putting
1182    them in array D[].  FIXME: This could be made much more optimal. */
1183 static void
1184 calc_stats (struct variable * v, double d[frq_n_stats])
1185 {
1186   double W = v->p.frq.tab.valid_cases;
1187   struct moments *m;
1188   struct freq *f=0; 
1189   int most_often;
1190   double X_mode;
1191
1192   double rank;
1193   int i = 0;
1194   int idx;
1195   double *median_value;
1196
1197   /* Calculate percentiles. */
1198
1199   /* If the 50th percentile was not explicitly requested then we must 
1200      calculate it anyway --- it's the median */
1201   median_value = 0 ;
1202   for (i = 0; i < n_percentiles; i++) 
1203     {
1204       if (percentiles[i].p == 0.5)
1205         {
1206           median_value = &percentiles[i].value;
1207           break;
1208         }
1209     }
1210
1211   if ( 0 == median_value )  
1212     {
1213       add_percentile (0.5);
1214       implicit_50th = 1;
1215     }
1216
1217   for (i = 0; i < n_percentiles; i++) 
1218     {
1219       percentiles[i].flag = 0;
1220       percentiles[i].flag2 = 0;
1221     }
1222
1223   rank = 0;
1224   for (idx = 0; idx < v->p.frq.tab.n_valid; ++idx)
1225     {
1226       static double prev_value = SYSMIS;
1227       f = &v->p.frq.tab.valid[idx]; 
1228       rank += f->c ;
1229       for (i = 0; i < n_percentiles; i++) 
1230         {
1231           double tp;
1232           if ( percentiles[i].flag2  ) continue ; 
1233
1234           if ( get_algorithm() != COMPATIBLE ) 
1235             tp = 
1236               (v->p.frq.tab.valid_cases - 1) *  percentiles[i].p;
1237           else
1238             tp = 
1239               (v->p.frq.tab.valid_cases + 1) *  percentiles[i].p - 1;
1240
1241           if ( percentiles[i].flag ) 
1242             {
1243               percentiles[i].x2 = f->v.f;
1244               percentiles[i].x1 = prev_value;
1245               percentiles[i].flag2 = 1;
1246               continue;
1247             }
1248
1249           if (rank >  tp ) 
1250           {
1251             if ( f->c > 1 && rank - (f->c - 1) > tp ) 
1252               {
1253                 percentiles[i].x2 = percentiles[i].x1 = f->v.f;
1254                 percentiles[i].flag2 = 1;
1255               }
1256             else
1257               {
1258                 percentiles[i].flag=1;
1259               }
1260
1261             continue;
1262           }
1263         }
1264       prev_value = f->v.f;
1265     }
1266
1267   for (i = 0; i < n_percentiles; i++) 
1268     {
1269       /* Catches the case when p == 100% */
1270       if ( ! percentiles[i].flag2 ) 
1271         percentiles[i].x1 = percentiles[i].x2 = f->v.f;
1272
1273       /*
1274       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1275              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1276       */
1277     }
1278
1279   for (i = 0; i < n_percentiles; i++) 
1280     {
1281       struct freq_tab *ft = &v->p.frq.tab;
1282       double s;
1283
1284       double dummy;
1285       if ( get_algorithm() != COMPATIBLE ) 
1286         {
1287           s = modf((ft->valid_cases - 1) *  percentiles[i].p , &dummy);
1288         }
1289       else
1290         {
1291           s = modf((ft->valid_cases + 1) *  percentiles[i].p -1, &dummy);
1292         }
1293
1294       percentiles[i].value = percentiles[i].x1 + 
1295         ( percentiles[i].x2 - percentiles[i].x1) * s ; 
1296
1297       if ( percentiles[i].p == 0.50) 
1298         median_value = &percentiles[i].value; 
1299     }
1300
1301
1302   /* Calculate the mode. */
1303   most_often = -1;
1304   X_mode = SYSMIS;
1305   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1306     {
1307       if (most_often < f->c) 
1308         {
1309           most_often = f->c;
1310           X_mode = f->v.f;
1311         }
1312       else if (most_often == f->c) 
1313         {
1314           /* A duplicate mode is undefined.
1315              FIXME: keep track of *all* the modes. */
1316           X_mode = SYSMIS;
1317         }
1318     }
1319
1320   /* Calculate moments. */
1321   m = moments_create (MOMENT_KURTOSIS);
1322   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1323     moments_pass_one (m, f->v.f, f->c);
1324   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1325     moments_pass_two (m, f->v.f, f->c);
1326   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1327                      &d[frq_skew], &d[frq_kurt]);
1328   moments_destroy (m);
1329                      
1330   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1331   d[frq_min] = v->p.frq.tab.valid[0].v.f;
1332   d[frq_max] = v->p.frq.tab.valid[v->p.frq.tab.n_valid - 1].v.f;
1333   d[frq_mode] = X_mode;
1334   d[frq_range] = d[frq_max] - d[frq_min];
1335   d[frq_median] = *median_value;
1336   d[frq_sum] = d[frq_mean] * W;
1337   d[frq_stddev] = sqrt (d[frq_variance]);
1338   d[frq_semean] = d[frq_stddev] / sqrt (W);
1339   d[frq_seskew] = calc_seskew (W);
1340   d[frq_sekurt] = calc_sekurt (W);
1341 }
1342
1343 /* Displays a table of all the statistics requested for variable V. */
1344 static void
1345 dump_statistics (struct variable * v, int show_varname)
1346 {
1347   double stat_value[frq_n_stats];
1348   struct tab_table *t;
1349   int i, r;
1350
1351   int n_explicit_percentiles = n_percentiles;
1352
1353   if ( implicit_50th && n_percentiles > 0 ) 
1354     --n_percentiles;
1355
1356   if (v->type == ALPHA)
1357     return;
1358   if (v->p.frq.tab.n_valid == 0)
1359     {
1360       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1361            v->name);
1362       return;
1363     }
1364   calc_stats (v, stat_value);
1365
1366   t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1367   tab_dim (t, tab_natural_dimensions);
1368
1369   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1370
1371
1372   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1373   tab_vline (t, TAL_1 | TAL_SPACING , 1, 0, tab_nr(t) - 1 ) ;
1374   
1375   r=2; /* N missing and N valid are always dumped */
1376
1377   for (i = 0; i < frq_n_stats; i++)
1378     if (stats & BIT_INDEX (i))
1379       {
1380         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1381                       gettext (st_name[i].s10));
1382         tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1383         r++;
1384       }
1385
1386   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1387   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1388   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1389
1390   tab_float(t, 2, 0, TAB_NONE, v->p.frq.tab.valid_cases, 11, 0);
1391   tab_float(t, 2, 1, TAB_NONE, 
1392             v->p.frq.tab.total_cases - v->p.frq.tab.valid_cases, 11, 0);
1393
1394
1395   for (i = 0; i < n_explicit_percentiles; i++, r++) 
1396     {
1397       if ( i == 0 ) 
1398         { 
1399           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1400         }
1401
1402       tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1403       tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1404
1405     }
1406
1407   tab_columns (t, SOM_COL_DOWN, 1);
1408   if (show_varname)
1409     {
1410       if (v->label)
1411         tab_title (t, 1, "%s: %s", v->name, v->label);
1412       else
1413         tab_title (t, 0, v->name);
1414     }
1415   else
1416     tab_flags (t, SOMF_NO_TITLE);
1417
1418
1419   tab_submit (t);
1420 }
1421 /* 
1422    Local Variables:
1423    mode: c
1424    End:
1425 */