c2d06a071dac88cf276657b63591c1321ed2cb17
[pspp] / src / language / data-io / matrix-reader.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2017, 2019 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "matrix-reader.h"
20
21 #include <stdbool.h>
22 #include <math.h>
23
24 #include "data/casegrouper.h"
25 #include "data/casereader.h"
26 #include "data/data-out.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/variable.h"
31 #include "language/command.h"
32 #include "libpspp/i18n.h"
33 #include "libpspp/message.h"
34 #include "libpspp/str.h"
35 #include "output/pivot-table.h"
36
37 #include "gettext.h"
38 #define _(msgid) gettext (msgid)
39 #define N_(msgid) msgid
40
41 struct lexer;
42
43 /*
44 This module interprets a "data matrix", typically generated by the command
45 MATRIX DATA.  The dictionary of such a matrix takes the form:
46
47  s_0, s_1, ... s_m, ROWTYPE_, VARNAME_, v_0, v_1, .... v_n
48
49 where s_0, s_1 ... s_m are the variables defining the splits, and
50 v_0, v_1 ... v_n are the continuous variables.
51
52 m >= 0; n >= 0
53
54 The ROWTYPE_ variable is of type A8.
55 The VARNAME_ variable is a string type whose width is not predetermined.
56 The variables s_x are of type F4.0 (although this reader accepts any type),
57 and v_x are of any numeric type.
58
59 The values of the ROWTYPE_ variable are in the set {MEAN, STDDEV, N, CORR, COV}
60 and determine the purpose of that case.
61 The values of the VARNAME_ variable must correspond to the names of the varibles
62 in {v_0, v_1 ... v_n} and indicate the rows of the correlation or covariance
63 matrices.
64
65
66
67 A typical example is as follows:
68
69 s_0 ROWTYPE_   VARNAME_   v_0         v_1         v_2
70
71 0   MEAN                5.0000       4.0000       3.0000
72 0   STDDEV              1.0000       2.0000       3.0000
73 0   N                   9.0000       9.0000       9.0000
74 0   CORR       V1       1.0000        .6000        .7000
75 0   CORR       V2        .6000       1.0000        .8000
76 0   CORR       V3        .7000        .8000       1.0000
77 1   MEAN                9.0000       8.0000       7.0000
78 1   STDDEV              5.0000       6.0000       7.0000
79 1   N                   9.0000       9.0000       9.0000
80 1   CORR       V1       1.0000        .4000        .3000
81 1   CORR       V2        .4000       1.0000        .2000
82 1   CORR       V3        .3000        .2000       1.0000
83
84 */
85
86 void
87 matrix_material_uninit (struct matrix_material *mm)
88 {
89   gsl_matrix_free (mm->corr);
90   gsl_matrix_free (mm->cov);
91   gsl_matrix_free (mm->n);
92   gsl_matrix_free (mm->mean_matrix);
93   gsl_matrix_free (mm->var_matrix);
94 }
95 \f
96 static const struct variable *
97 find_matrix_string_var (const struct dictionary *dict, const char *name)
98 {
99   const struct variable *var = dict_lookup_var (dict, name);
100   if (var == NULL)
101     {
102       msg (ME, _("Matrix dataset lacks a variable called %s."), name);
103       return NULL;
104     }
105   if (!var_is_alpha (var))
106     {
107       msg (ME, _("Matrix dataset variable %s should be of string type."), name);
108       return NULL;
109     }
110   return var;
111 }
112
113 struct matrix_reader *
114 matrix_reader_create (const struct dictionary *dict,
115                       struct casereader *in_reader)
116 {
117   const struct variable *varname = find_matrix_string_var (dict, "VARNAME_");
118   const struct variable *rowtype = find_matrix_string_var (dict, "ROWTYPE_");
119   if (!varname || !rowtype)
120     return NULL;
121
122   size_t varname_idx = var_get_dict_index (varname);
123   size_t rowtype_idx = var_get_dict_index (rowtype);
124   if (varname_idx < rowtype_idx)
125     {
126       msg (ME, _("Variable %s must precede %s in matrix file dictionary."),
127            "ROWTYPE_", "VARNAME_");
128       return NULL;
129     }
130
131   for (size_t i = 0; i < dict_get_var_cnt (dict); i++)
132     {
133       const struct variable *v = dict_get_var (dict, i);
134       if (!var_is_numeric (v) && v != rowtype && v != varname)
135         {
136           msg (ME, _("Matrix dataset variable %s should be numeric."),
137                var_get_name (v));
138           return NULL;
139         }
140     }
141
142   size_t n_vars;
143   const struct variable **vars;
144   dict_get_vars (dict, &vars, &n_vars, DC_SCRATCH);
145
146   /* Different kinds of variables. */
147   size_t first_svar = 0;
148   size_t n_svars = rowtype_idx;
149   size_t first_fvar = rowtype_idx + 1;
150   size_t n_fvars = varname_idx - rowtype_idx - 1;
151   size_t first_cvar = varname_idx + 1;
152   size_t n_cvars = n_vars - varname_idx - 1;
153   if (!n_cvars)
154     {
155       msg (ME, _("Matrix dataset does not have any continuous variables."));
156       free (vars);
157       return NULL;
158     }
159
160   struct matrix_reader *mr = xmalloc (sizeof *mr);
161   *mr = (struct matrix_reader) {
162     .dict = dict,
163     .grouper = casegrouper_create_vars (in_reader, &vars[first_svar], n_svars),
164     .svars = xmemdup (vars + first_svar, n_svars * sizeof *mr->svars),
165     .n_svars = n_svars,
166     .rowtype = rowtype,
167     .fvars = xmemdup (vars + first_fvar, n_fvars * sizeof *mr->fvars),
168     .n_fvars = n_fvars,
169     .varname = varname,
170     .cvars = xmemdup (vars + first_cvar, n_cvars * sizeof *mr->cvars),
171     .n_cvars = n_cvars,
172   };
173   free (vars);
174
175   return mr;
176 }
177
178 bool
179 matrix_reader_destroy (struct matrix_reader *mr)
180 {
181   if (mr == NULL)
182     return false;
183   bool ret = casegrouper_destroy (mr->grouper);
184   free (mr);
185   return ret;
186 }
187
188
189 /*
190    Allocates MATRIX if necessary,
191    and populates row MROW, from the data in C corresponding to
192    variables in VARS. N_VARS is the length of VARS.
193 */
194 static void
195 matrix_fill_row (gsl_matrix **matrix,
196       const struct ccase *c, int mrow,
197       const struct variable **vars, size_t n_vars)
198 {
199   int col;
200   if (*matrix == NULL)
201     {
202       *matrix = gsl_matrix_alloc (n_vars, n_vars);
203       gsl_matrix_set_all (*matrix, SYSMIS);
204     }
205
206   for (col = 0; col < n_vars; ++col)
207     {
208       const struct variable *cv = vars [col];
209       double x = case_num (c, cv);
210       assert (col  < (*matrix)->size2);
211       assert (mrow < (*matrix)->size1);
212       gsl_matrix_set (*matrix, mrow, col, x);
213     }
214 }
215
216 static int
217 find_varname (const struct variable **vars, int n_vars,
218               const char *varname)
219 {
220   for (int i = 0; i < n_vars; i++)
221     if (!strcasecmp (var_get_name (vars[i]), varname))
222       return i;
223   return -1;
224 }
225
226 struct substring
227 matrix_reader_get_string (const struct ccase *c, const struct variable *var)
228 {
229   struct substring s = case_ss (c, var);
230   ss_rtrim (&s, ss_cstr (CC_SPACES));
231   return s;
232 }
233
234 void
235 matrix_reader_set_string (struct ccase *c, const struct variable *var,
236                           struct substring src)
237 {
238   struct substring dst = case_ss (c, var);
239   for (size_t i = 0; i < dst.length; i++)
240     dst.string[i] = i < src.length ? src.string[i] : ' ';
241 }
242
243 bool
244 matrix_reader_next (struct matrix_material *mm, struct matrix_reader *mr,
245                     struct casereader **groupp)
246 {
247   struct casereader *group;
248   if (!casegrouper_get_next_group (mr->grouper, &group))
249     {
250       *mm = (struct matrix_material) MATRIX_MATERIAL_INIT;
251       if (groupp)
252         *groupp = NULL;
253       return false;
254     }
255
256   if (groupp)
257     *groupp = casereader_clone (group);
258
259   const struct variable **vars = mr->cvars;
260   size_t n_vars = mr->n_cvars;
261
262   *mm = (struct matrix_material) {
263     .n = gsl_matrix_calloc (n_vars, n_vars),
264     .mean_matrix = gsl_matrix_calloc (n_vars, n_vars),
265     .var_matrix = gsl_matrix_calloc (n_vars, n_vars),
266   };
267
268   struct matrix
269     {
270       const char *name;
271       gsl_matrix **m;
272       size_t good_rows;
273       size_t bad_rows;
274     };
275   struct matrix matrices[] = {
276     { .name = "CORR", .m = &mm->corr },
277     { .name = "COV", .m = &mm->cov },
278   };
279   enum { N_MATRICES = 2 };
280
281   struct ccase *c;
282   for (; (c = casereader_read (group)); case_unref (c))
283     {
284       struct substring rowtype = matrix_reader_get_string (c, mr->rowtype);
285
286       gsl_matrix *v
287         = (ss_equals_case (rowtype, ss_cstr ("N")) ? mm->n
288            : ss_equals_case (rowtype, ss_cstr ("MEAN")) ? mm->mean_matrix
289            : ss_equals_case (rowtype, ss_cstr ("STDDEV")) ? mm->var_matrix
290            : NULL);
291       if (v)
292         {
293           for (int x = 0; x < n_vars; ++x)
294             {
295               double n = case_num (c, vars[x]);
296               if (v == mm->var_matrix)
297                 n *= n;
298               for (int y = 0; y < n_vars; ++y)
299                 gsl_matrix_set (v, y, x, n);
300             }
301           continue;
302         }
303
304       struct matrix *m = NULL;
305       for (size_t i = 0; i < N_MATRICES; i++)
306         if (ss_equals_case (rowtype, ss_cstr (matrices[i].name)))
307           {
308             m = &matrices[i];
309             break;
310           }
311       if (m)
312         {
313           struct substring varname_raw = case_ss (c, mr->varname);
314           struct substring varname = ss_cstr (
315             recode_string (UTF8, dict_get_encoding (mr->dict),
316                            varname_raw.string, varname_raw.length));
317           ss_rtrim (&varname, ss_cstr (CC_SPACES));
318           varname.string[varname.length] = '\0';
319
320           int y = find_varname (vars, n_vars, varname.string);
321           if (y >= 0)
322             {
323               m->good_rows++;
324               matrix_fill_row (m->m, c, y, vars, n_vars);
325             }
326           else
327             m->bad_rows++;
328           ss_dealloc (&varname);
329         }
330     }
331   casereader_destroy (group);
332
333   for (size_t i = 0; i < N_MATRICES; i++)
334     if (matrices[i].good_rows && matrices[i].good_rows != n_vars)
335       msg (SW, _("%s matrix has %zu columns but %zu rows named variables "
336                  "to be analyzed (and %zu rows named unknown variables)."),
337            matrices[i].name, n_vars, matrices[i].good_rows,
338            matrices[i].bad_rows);
339
340   return true;
341 }
342
343 int
344 cmd_debug_matrix_read (struct lexer *lexer UNUSED, struct dataset *ds)
345 {
346   struct matrix_reader *mr = matrix_reader_create (dataset_dict (ds),
347                                                    proc_open (ds));
348   if (!mr)
349     return CMD_FAILURE;
350
351   struct pivot_table *pt = pivot_table_create ("Debug Matrix Reader");
352
353   enum mm_stat
354     {
355       MM_CORR,
356       MM_COV,
357       MM_N,
358       MM_MEAN,
359       MM_STDDEV,
360     };
361   const char *mm_stat_names[] = {
362     [MM_CORR] = "Correlation",
363     [MM_COV] = "Covariance",
364     [MM_N] = "N",
365     [MM_MEAN] = "Mean",
366     [MM_STDDEV] = "Standard Deviation",
367   };
368   enum { N_STATS = sizeof mm_stat_names / sizeof *mm_stat_names };
369   for (size_t i = 0; i < 2; i++)
370     {
371       struct pivot_dimension *d = pivot_dimension_create (
372         pt,
373         i ? PIVOT_AXIS_COLUMN : PIVOT_AXIS_ROW,
374         i ? "Column" : "Row");
375       if (!i)
376         pivot_category_create_leaf_rc (d->root, pivot_value_new_text ("Value"),
377                                        PIVOT_RC_CORRELATION);
378       for (size_t j = 0; j < mr->n_cvars; j++)
379         pivot_category_create_leaf_rc (
380           d->root, pivot_value_new_variable (mr->cvars[j]),
381           PIVOT_RC_CORRELATION);
382     }
383
384   struct pivot_dimension *stat = pivot_dimension_create (pt, PIVOT_AXIS_ROW,
385                                                          "Statistic");
386   for (size_t i = 0; i < N_STATS; i++)
387     pivot_category_create_leaf (stat->root,
388                                 pivot_value_new_text (mm_stat_names[i]));
389
390   struct pivot_dimension *split = pivot_dimension_create (
391     pt, PIVOT_AXIS_ROW, "Split");
392
393   int split_num = 0;
394
395   struct matrix_material mm = MATRIX_MATERIAL_INIT;
396   while (matrix_reader_next (&mm, mr, NULL))
397     {
398       pivot_category_create_leaf (split->root,
399                                   pivot_value_new_integer (split_num + 1));
400
401       const gsl_matrix *m[N_STATS] = {
402         [MM_CORR] = mm.corr,
403         [MM_COV] = mm.cov,
404         [MM_N] = mm.n,
405         [MM_MEAN] = mm.mean_matrix,
406         [MM_STDDEV] = mm.var_matrix,
407       };
408
409       for (size_t i = 0; i < N_STATS; i++)
410         if (m[i])
411           {
412             if (i == MM_COV || i == MM_CORR)
413               {
414                 for (size_t y = 0; y < mr->n_cvars; y++)
415                   for (size_t x = 0; x < mr->n_cvars; x++)
416                     pivot_table_put4 (
417                       pt, y + 1, x, i, split_num,
418                       pivot_value_new_number (gsl_matrix_get (m[i], y, x)));
419               }
420             else
421               for (size_t x = 0; x < mr->n_cvars; x++)
422                 {
423                   double n = gsl_matrix_get (m[i], 0, x);
424                   if (i == MM_STDDEV)
425                     n = sqrt (n);
426                   pivot_table_put4 (pt, 0, x, i, split_num,
427                                     pivot_value_new_number (n));
428                 }
429           }
430
431       split_num++;
432       matrix_material_uninit (&mm);
433     }
434   pivot_table_submit (pt);
435
436   proc_commit (ds);
437
438   matrix_reader_destroy (mr);
439   return CMD_SUCCESS;
440 }