output: Introduce pivot tables.
[pspp] / src / language / stats / means.c
index fec20877399aea3a12d20a9761714bea53a3d131..7e7642adf1fd2ff1a51c0492330e5a792e19b790 100644 (file)
@@ -1,5 +1,5 @@
 /* PSPP - a program for statistical analysis.
-   Copyright (C) 2011, 2012 Free Software Foundation, Inc.
+   Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -35,7 +35,7 @@
 #include "math/interaction.h"
 #include "math/moments.h"
 
-#include "output/tab.h"
+#include "output/pivot-table.h"
 
 #include <math.h>
 
@@ -384,7 +384,7 @@ first_update (void *stat, double w UNUSED, double x)
   double *f = stat;
 
   if (*f == SYSMIS)
-     *f = x;
+    *f = x;
 }
 
 static double
@@ -395,7 +395,7 @@ first_get (const struct per_var_data *pvd UNUSED,  void *stat)
   return *f;
 }
 
-enum 
+enum
   {
     MEANS_MEAN = 0,
     MEANS_N,
@@ -502,43 +502,40 @@ parse_means_table_syntax (struct lexer *lexer, const struct means *cmd, struct m
   table->ii = 0;
   table->n_layers = 0;
   table->layers = NULL;
+  table->interactions = NULL;
 
   /* Dependent variable (s) */
   if (!parse_variables_const_pool (lexer, cmd->pool, cmd->dict,
-                             &table->dep_vars, &table->n_dep_vars,
-                             PV_NO_DUPLICATE | PV_NUMERIC))
+                                  &table->dep_vars, &table->n_dep_vars,
+                                  PV_NO_DUPLICATE | PV_NUMERIC))
     return false;
 
   /* Factor variable (s) */
-  while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
+  while (lex_match (lexer, T_BY))
     {
-      if (lex_match (lexer, T_BY))
-       {
-         table->n_layers++;
-          table->layers = 
-           pool_realloc (cmd->pool, table->layers, 
+      table->n_layers++;
+      table->layers =
+       pool_realloc (cmd->pool, table->layers,
                      sizeof (*table->layers) * table->n_layers);
 
-         if (!parse_variables_const_pool 
-              (lexer, cmd->pool, cmd->dict,
-               &table->layers[table->n_layers - 1].factor_vars,
-               &table->layers[table->n_layers - 1].n_factor_vars,
-               PV_NO_DUPLICATE))
-           return false;
-
-       }
+      if (!parse_variables_const_pool
+         (lexer, cmd->pool, cmd->dict,
+          &table->layers[table->n_layers - 1].factor_vars,
+          &table->layers[table->n_layers - 1].n_factor_vars,
+          PV_NO_DUPLICATE))
+       return false;
     }
 
   /* There is always at least one layer.
      However the final layer is the total, and not
-     normally considered by the user as a 
+     normally considered by the user as a
      layer.
   */
 
   table->n_layers++;
-  table->layers = 
-    pool_realloc (cmd->pool, table->layers, 
-              sizeof (*table->layers) * table->n_layers);
+  table->layers =
+    pool_realloc (cmd->pool, table->layers,
+                 sizeof (*table->layers) * table->n_layers);
   table->layers[table->n_layers - 1].factor_vars = NULL;
   table->layers[table->n_layers - 1].n_factor_vars = 0;
 
@@ -596,7 +593,8 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
   /*   Optional TABLES =   */
   if (lex_match_id (lexer, "TABLES"))
     {
-      lex_force_match (lexer, T_EQUALS);
+      if (! lex_force_match (lexer, T_EQUALS))
+       goto error;
     }
 
 
@@ -607,7 +605,7 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
       means.n_tables ++;
       means.table = pool_realloc (means.pool, means.table, means.n_tables * sizeof (*means.table));
 
-      if (! parse_means_table_syntax (lexer, &means, 
+      if (! parse_means_table_syntax (lexer, &means,
                                      &means.table[means.n_tables - 1]))
        {
          goto error;
@@ -620,7 +618,7 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
          if (lex_is_variable (lexer, means.dict, 1) )
            {
              more_tables = true;
-             lex_force_match (lexer, T_SLASH);
+             lex_match (lexer, T_SLASH);
            }
        }
     }
@@ -633,10 +631,10 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
       if (lex_match_id (lexer, "MISSING"))
        {
          /*
-            If no MISSING subcommand is specified, each combination of
-            a dependent variable and categorical variables is handled
-            separately.
-          */
+           If no MISSING subcommand is specified, each combination of
+           a dependent variable and categorical variables is handled
+           separately.
+         */
          lex_match (lexer, T_EQUALS);
          if (lex_match_id (lexer, "INCLUDE"))
            {
@@ -661,17 +659,17 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
            }
          else if (lex_match_id (lexer, "DEPENDENT"))
            /*
-            Use the command "/MISSING=DEPENDENT" to
-            include user-missing values for the categorical variables, 
-            while excluding them for the dependent variables.
+             Use the command "/MISSING=DEPENDENT" to
+             include user-missing values for the categorical variables,
+             while excluding them for the dependent variables.
 
-            Cases are dropped only when user-missing values
-            appear in dependent  variables.  User-missing
-            values for categorical variables are treated according to
-            their face value.
+             Cases are dropped only when user-missing values
+             appear in dependent  variables.  User-missing
+             values for categorical variables are treated according to
+             their face value.
 
-            Cases are ALWAYS dropped when System Missing values appear 
-            in the categorical variables.
+             Cases are ALWAYS dropped when System Missing values appear
+             in the categorical variables.
            */
            {
              means.dep_exclude = MV_ANY;
@@ -698,7 +696,7 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
                  int x;
                  means.cells =
                    pool_realloc (means.pool, means.cells,
-                             (means.n_cells += n_C) * sizeof (*means.cells));
+                                 (means.n_cells += n_C) * sizeof (*means.cells));
 
                  for (x = 0; x < n_C; ++x)
                    means.cells[means.n_cells - (n_C - 1 - x) - 1] = x;
@@ -711,8 +709,8 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
                {
                  means.cells =
                    pool_realloc (means.pool, means.cells,
-                             (means.n_cells += 3) * sizeof (*means.cells));
-                 
+                                 (means.n_cells += 3) * sizeof (*means.cells));
+
                  means.cells[means.n_cells - 2 - 1] = MEANS_MEAN;
                  means.cells[means.n_cells - 1 - 1] = MEANS_N;
                  means.cells[means.n_cells - 0 - 1] = MEANS_STDDEV;
@@ -725,8 +723,8 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
                        {
                          means.cells =
                            pool_realloc (means.pool, means.cells,
-                                     ++means.n_cells * sizeof (*means.cells));
-                       
+                                         ++means.n_cells * sizeof (*means.cells));
+
                          means.cells[means.n_cells - 1] = k;
                          break;
                        }
@@ -749,28 +747,28 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
 
 
   for (t = 0; t < means.n_tables; ++t)
-  {
-    struct mtable *table = &means.table[t];
+    {
+      struct mtable *table = &means.table[t];
 
-    table->interactions =
-      pool_calloc (means.pool, table->n_layers, sizeof (*table->interactions));
+      table->interactions =
+       pool_calloc (means.pool, table->n_layers, sizeof (*table->interactions));
 
-    table->summary =
-      pool_calloc (means.pool, table->n_dep_vars * table->n_layers, sizeof (*table->summary));
+      table->summary =
+       pool_calloc (means.pool, table->n_dep_vars * table->n_layers, sizeof (*table->summary));
 
-    for (l = 0; l < table->n_layers; ++l)
-      {
-        int v;
-        const struct layer *lyr = &table->layers[l];
-       const int n_vars = lyr->n_factor_vars;
-        table->interactions[l] = interaction_create (NULL);
-        for (v = 0 ; v < n_vars ; ++v)
-          {
-            interaction_add_variable (table->interactions[l],
-                                      lyr->factor_vars[v]);
-          }
-      }
-  }
+      for (l = 0; l < table->n_layers; ++l)
+       {
+         int v;
+         const struct layer *lyr = &table->layers[l];
+         const int n_vars = lyr->n_factor_vars;
+         table->interactions[l] = interaction_create (NULL);
+         for (v = 0; v < n_vars ; ++v)
+           {
+             interaction_add_variable (table->interactions[l],
+                                       lyr->factor_vars[v]);
+           }
+       }
+    }
 
   {
     struct casegrouper *grouper;
@@ -786,11 +784,32 @@ cmd_means (struct lexer *lexer, struct dataset *ds)
     ok = proc_commit (ds) && ok;
   }
 
+  for (t = 0; t < means.n_tables; ++t)
+    {
+      int l;
+      struct mtable *table = &means.table[t];
+      if (table->interactions)
+       for (l = 0; l < table->n_layers; ++l)
+         {
+           interaction_destroy (table->interactions[l]);
+         }
+    }
 
   pool_destroy (means.pool);
   return CMD_SUCCESS;
 
-error:
+ error:
+
+  for (t = 0; t < means.n_tables; ++t)
+    {
+      int l;
+      struct mtable *table = &means.table[t];
+      if (table->interactions)
+       for (l = 0; l < table->n_layers; ++l)
+         {
+           interaction_destroy (table->interactions[l]);
+         }
+    }
 
   pool_destroy (means.pool);
   return CMD_FAILURE;
@@ -815,7 +834,8 @@ is_missing (const struct means *cmd,
   return false;
 }
 
-static void output_case_processing_summary (const struct mtable *);
+static void output_case_processing_summary (const struct mtable *,
+                                            const struct variable *wv);
 
 static void output_report (const struct means *, int, const struct mtable *);
 
@@ -827,6 +847,22 @@ struct per_cat_data
   bool warn;
 };
 
+
+static void
+destroy_n (const void *aux1 UNUSED, void *aux2, void *user_data)
+{
+  struct mtable *table = aux2;
+  int v;
+  struct per_cat_data *per_cat_data = user_data;
+  struct per_var_data *pvd = per_cat_data->pvd;
+
+  for (v = 0; v < table->n_dep_vars; ++v)
+    {
+      struct per_var_data *pp = &pvd[v];
+      moments1_destroy (pp->mom);
+    }
+}
+
 static void *
 create_n (const void *aux1, void *aux2)
 {
@@ -843,7 +879,7 @@ create_n (const void *aux1, void *aux2)
       struct per_var_data *pp = &pvd[v];
 
       pp->cell_stats = pool_calloc (means->pool, means->n_cells, sizeof *pp->cell_stats);
-      
+
 
       for (i = 0; i < means->n_cells; ++i)
        {
@@ -939,16 +975,17 @@ run_means (struct means *cmd, struct casereader *input,
   payload.create = create_n;
   payload.update = update_n;
   payload.calculate = calculate_n;
-  
+  payload.destroy = destroy_n;
+
   for (t = 0; t < cmd->n_tables; ++t)
-  {
-    struct mtable *table = &cmd->table[t];
-    table->cats
-      = categoricals_create (table->interactions,
-                            table->n_layers, wv, cmd->dep_exclude, cmd->exclude);
+    {
+      struct mtable *table = &cmd->table[t];
+      table->cats
+       = categoricals_create (table->interactions,
+                              table->n_layers, wv, cmd->exclude);
 
-    categoricals_set_payload (table->cats, &payload, cmd, table);
-  }
+      categoricals_set_payload (table->cats, &payload, cmd, table);
+    }
 
   for (reader = input;
        (c = casereader_read (reader)) != NULL; case_unref (c))
@@ -997,7 +1034,7 @@ run_means (struct means *cmd, struct casereader *input,
       int i;
       const struct mtable *table = &cmd->table[t];
 
-      output_case_processing_summary (table);
+      output_case_processing_summary (table, wv);
 
       for (i = 0; i < table->n_layers; ++i)
        {
@@ -1011,201 +1048,143 @@ run_means (struct means *cmd, struct casereader *input,
 
 
 static void
-output_case_processing_summary (const struct mtable *table)
+output_case_processing_summary (const struct mtable *mt,
+                                const struct variable *wv)
 {
-  int i, v;
-  const int heading_columns = 1;
-  const int heading_rows = 3;
-  struct tab_table *t;
-
-  const int nr = heading_rows + table->n_layers * table->n_dep_vars;
-  const int nc = 7;
-
-  t = tab_create (nc, nr);
-  tab_title (t, _("Case Processing Summary"));
-
-  tab_headers (t, heading_columns, 0, heading_rows, 0);
-
-  tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
-
-  tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
-  tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
-
+  struct pivot_table *table = pivot_table_create (
+    N_("Case Processing Summary"));
+  pivot_table_set_weight_var (table, wv);
 
-  tab_joint_text (t, heading_columns, 0,
-                 nc - 1, 0, TAB_CENTER | TAT_TITLE, _("Cases"));
+  pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
+                          N_("N"), PIVOT_RC_COUNT,
+                          N_("Percent"), PIVOT_RC_PERCENT);
+  pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Cases"),
+                          N_("Included"), N_("Excluded"), N_("Total"))
+    ->root->show_label = true;
 
-  tab_joint_text (t, 1, 1, 2, 1, TAB_CENTER | TAT_TITLE, _("Included"));
-  tab_joint_text (t, 3, 1, 4, 1, TAB_CENTER | TAT_TITLE, _("Excluded"));
-  tab_joint_text (t, 5, 1, 6, 1, TAB_CENTER | TAT_TITLE, _("Total"));
+  struct pivot_dimension *tables = pivot_dimension_create (
+    table, PIVOT_AXIS_ROW, N_("Tables"));
 
-  tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
-  tab_hline (t, TAL_1, heading_columns, nc - 1, 2);
-
-
-  for (i = 0; i < 3; ++i)
+  for (size_t v = 0; v < mt->n_dep_vars; ++v)
     {
-      tab_text (t, heading_columns + i * 2, 2, TAB_CENTER | TAT_TITLE,
-               _("N"));
-      tab_text (t, heading_columns + i * 2 + 1, 2, TAB_CENTER | TAT_TITLE,
-               _("Percent"));
-    }
-
-  for (v = 0; v < table->n_dep_vars; ++v)
-    {
-      const struct variable *var = table->dep_vars[v];
-      const char *dv_name = var_to_string (var);
-      for (i = 0; i < table->n_layers; ++i)
+      const struct variable *var = mt->dep_vars[v];
+      for (size_t i = 0; i < mt->n_layers; ++i)
        {
-         const int row = v * table->n_layers + i;
-         const struct interaction *iact = table->interactions[i];
-         casenumber n_total;
-
-         struct string str;
-         ds_init_cstr (&str, dv_name);
-         ds_put_cstr (&str, ": ");
+         const int row = v * mt->n_layers + i;
+         const struct interaction *iact = mt->interactions[i];
 
+         struct string str = DS_EMPTY_INITIALIZER;
+          ds_put_format (&str, "%s: ", var_to_string (var));
          interaction_to_string (iact, &str);
-
-         tab_text (t, 0, row + heading_rows,
-                   TAB_LEFT | TAT_TITLE, ds_cstr (&str));
-
-
-         n_total = table->summary[row].missing + 
-           table->summary[row].non_missing;
-
-         tab_double (t, 1, row + heading_rows,
-                     0, table->summary[row].non_missing, &F_8_0);
-
-         tab_text_format (t, 2, row + heading_rows,
-                          0, _("%g%%"), 
-                          table->summary[row].non_missing / (double) n_total * 100.0);
-
-
-         tab_double (t, 3, row + heading_rows,
-                     0, table->summary[row].missing, &F_8_0);
-
-
-         tab_text_format (t, 4, row + heading_rows,
-                          0, _("%g%%"), 
-                          table->summary[row].missing / (double) n_total * 100.0);
-
-
-         tab_double (t, 5, row + heading_rows,
-                     0, table->summary[row].missing + 
-                     table->summary[row].non_missing, &F_8_0);
-
-         tab_text_format (t, 6, row + heading_rows,
-                          0, _("%g%%"), 
-                          n_total / (double) n_total * 100.0);
-
-
-         ds_destroy (&str);
+          int table_idx = pivot_category_create_leaf (
+            tables->root, pivot_value_new_user_text_nocopy (
+              ds_steal_cstr (&str)));
+
+          const struct summary *s = &mt->summary[row];
+         double n_total = s->missing + s->non_missing;
+          struct entry
+            {
+              int stat_idx;
+              int case_idx;
+              double x;
+            }
+          entries[] =
+            {
+              { 0, 0, s->non_missing },
+              { 1, 0, s->non_missing / n_total * 100.0 },
+              { 0, 1, s->missing },
+              { 1, 1, s->missing / n_total * 100.0 },
+              { 0, 2, n_total },
+              { 1, 2, 100.0 },
+            };
+
+          for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
+            {
+              const struct entry *e = &entries[j];
+              pivot_table_put3 (table, e->stat_idx, e->case_idx, table_idx,
+                                pivot_value_new_number (e->x));
+            }
        }
     }
 
-  tab_submit (t);
+  pivot_table_submit (table);
 }
 
-
 static void
-output_report (const struct means *cmd,  int iact_idx,
-              const struct mtable *table)
+create_interaction_dimensions (struct pivot_table *table,
+                               const struct categoricals *cats,
+                               const struct interaction *iact)
 {
-  int grp;
-  int i;
-
-  const struct interaction *iact = table->interactions[iact_idx];
-
-  const int heading_columns = 1 + iact->n_vars;
-  const int heading_rows = 1;
-  struct tab_table *t;
-
-  const int n_cats = categoricals_n_count (table->cats, iact_idx);
-
-  const int nr = n_cats * table->n_dep_vars + heading_rows;
-
-  const int nc = heading_columns + cmd->n_cells;
-
-  t = tab_create (nc, nr);
-  tab_title (t, _("Report"));
-
-  tab_headers (t, heading_columns, 0, heading_rows, 0);
-
-  tab_box (t, TAL_2, TAL_2, -1, TAL_1, 0, 0, nc - 1, nr - 1);
-
-  tab_hline (t, TAL_2, 0, nc - 1, heading_rows);
-  tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
-
-  for (i = 0; i < iact->n_vars; ++i)
+  for (size_t i = iact->n_vars; i-- > 0; )
     {
-      tab_text (t, 1 + i, 0, TAB_CENTER | TAT_TITLE,
-               var_to_string (iact->vars[i]));
+      const struct variable *var = iact->vars[i];
+      struct pivot_dimension *d = pivot_dimension_create__ (
+        table, PIVOT_AXIS_ROW, pivot_value_new_variable (var));
+      d->root->show_label = true;
+
+      size_t n;
+      union value *values = categoricals_get_var_values (cats, var, &n);
+      for (size_t j = 0; j < n; j++)
+        pivot_category_create_leaf (
+          d->root, pivot_value_new_var_value (var, &values[j]));
     }
+}
 
-  for (i = 0; i < cmd->n_cells; ++i)
-    {
-      tab_text (t, heading_columns + i, 0,
-               TAB_CENTER | TAT_TITLE,
-               gettext (cell_spec[cmd->cells[i]].title));
-    }
-
-
-  for (i = 0; i < n_cats; ++i)
-    {
-      int v, dv;
-      const struct ccase *c =
-       categoricals_get_case_by_category_real (table->cats, iact_idx, i);
-
-      for (dv = 0; dv < table->n_dep_vars; ++dv)
-       {
-         tab_text (t, 0,
-                   heading_rows + dv * n_cats,
-                   TAB_RIGHT | TAT_TITLE,
-                   var_to_string (table->dep_vars[dv])
-                   );
+static void
+output_report (const struct means *cmd,  int iact_idx,
+              const struct mtable *mt)
+{
+  struct pivot_table *table = pivot_table_create (N_("Report"));
+  table->omit_empty = true;
 
-         if ( dv > 0)
-           tab_hline (t, TAL_1, 0, nc - 1, heading_rows + dv * n_cats);
+  struct pivot_dimension *statistics = pivot_dimension_create (
+    table, PIVOT_AXIS_COLUMN, N_("Statistics"));
+  for (int i = 0; i < cmd->n_cells; ++i)
+    pivot_category_create_leaf (
+      statistics->root, pivot_value_new_text (cell_spec[cmd->cells[i]].title));
 
-         for (v = 0; v < iact->n_vars; ++v)
-           {
-             const struct variable *var = iact->vars[v];
-             const union value *val = case_data (c, var);
-             struct string str;
-             ds_init_empty (&str);
-             var_append_value_name (var, val, &str);
+  const struct interaction *iact = mt->interactions[iact_idx];
+  create_interaction_dimensions (table, mt->cats, iact);
 
-             tab_text (t, 1 + v, heading_rows + dv * n_cats + i,
-                       TAB_RIGHT | TAT_TITLE, ds_cstr (&str));
+  struct pivot_dimension *dep_dim = pivot_dimension_create (
+    table, PIVOT_AXIS_ROW, N_("Dependent Variables"));
 
-             ds_destroy (&str);
-           }
-       }
-    }
+  size_t *indexes = xnmalloc (table->n_dimensions, sizeof *indexes);
 
-  for (grp = 0; grp < n_cats; ++grp)
+  size_t n_cats = categoricals_n_count (mt->cats, iact_idx);
+  for (size_t v = 0; v < mt->n_dep_vars; ++v)
     {
-      int dv;
-      struct per_cat_data *per_cat_data =
-       categoricals_get_user_data_by_category_real (table->cats, iact_idx, grp);
-
-      for (dv = 0; dv < table->n_dep_vars; ++dv)
-       {
-         const struct per_var_data *pvd = &per_cat_data->pvd[dv];
-         for (i = 0; i < cmd->n_cells; ++i)
-           {
-             const int csi = cmd->cells[i];
-             const struct cell_spec *cs = &cell_spec[csi];
-
-             double result = cs->sd (pvd, pvd->cell_stats[i]);
-
-             tab_double (t, heading_columns + i,
-                         heading_rows + grp + dv * n_cats,
-                         0, result, 0);
-           }
-       }
+      indexes[table->n_dimensions - 1] = pivot_category_create_leaf (
+        dep_dim->root, pivot_value_new_variable (mt->dep_vars[v]));
+
+      for (size_t i = 0; i < n_cats; ++i)
+        {
+          for (size_t j = 0; j < iact->n_vars; j++)
+            {
+              int idx = categoricals_get_value_index_by_category_real (
+                mt->cats, iact_idx, i, j);
+              indexes[table->n_dimensions - 2 - j] = idx;
+            }
+
+          struct per_cat_data *per_cat_data
+            = categoricals_get_user_data_by_category_real (
+              mt->cats, iact_idx, i);
+
+          const struct per_var_data *pvd = &per_cat_data->pvd[v];
+          for (int stat_idx = 0; stat_idx < cmd->n_cells; ++stat_idx)
+            {
+              indexes[0] = stat_idx;
+              const int csi = cmd->cells[stat_idx];
+              const struct cell_spec *cs = &cell_spec[csi];
+
+              double result = cs->sd (pvd, pvd->cell_stats[stat_idx]);
+              pivot_table_put (table, indexes, table->n_dimensions,
+                               pivot_value_new_number (result));
+            }
+        }
     }
+  free (indexes);
 
-  tab_submit (t);
+  pivot_table_submit (table);
 }
+