MATRIX DATA: Cope with long variable names
[pspp] / src / language / data-io / matrix-data.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2017 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 "data/case.h"
20 #include "data/casereader.h"
21 #include "data/casewriter.h"
22 #include "data/dataset.h"
23 #include "data/dictionary.h"
24 #include "data/format.h"
25 #include "data/transformations.h"
26 #include "data/variable.h"
27 #include "language/command.h"
28 #include "language/data-io/data-parser.h"
29 #include "language/data-io/data-reader.h"
30 #include "language/data-io/file-handle.h"
31 #include "language/data-io/inpt-pgm.h"
32 #include "language/data-io/placement-parser.h"
33 #include "language/lexer/lexer.h"
34 #include "language/lexer/variable-parser.h"
35 #include "libpspp/i18n.h"
36 #include "libpspp/message.h"
37 #include "libpspp/misc.h"
38
39 #include "gl/xsize.h"
40 #include "gl/xalloc.h"
41
42 #include "gettext.h"
43 #define _(msgid) gettext (msgid)
44 \f
45 /* DATA LIST transformation data. */
46 struct data_list_trns
47   {
48     struct data_parser *parser; /* Parser. */
49     struct dfm_reader *reader;  /* Data file reader. */
50     struct variable *end;       /* Variable specified on END subcommand. */
51   };
52
53 static trns_free_func data_list_trns_free;
54 static trns_proc_func data_list_trns_proc;
55
56 enum diagonal
57   {
58     DIAGONAL,
59     NO_DIAGONAL
60   };
61
62 enum triangle
63   {
64     LOWER,
65     UPPER,
66     FULL
67   };
68
69 static const int ROWTYPE_WIDTH = 8;
70
71 struct matrix_format
72 {
73   enum triangle triangle;
74   enum diagonal diagonal;
75   const struct variable *rowtype;
76   const struct variable *varname;
77   int n_continuous_vars;
78   struct variable **split_vars;
79   size_t n_split_vars;
80 };
81
82 /*
83 valid rowtype_ values:
84   CORR,
85   COV,
86   MAT,
87
88
89   MSE,
90   DFE,
91   MEAN,
92   STDDEV (or SD),
93   N_VECTOR (or N),
94   N_SCALAR,
95   N_MATRIX,
96   COUNT,
97   PROX.
98 */
99
100 /* Sets the value of OUTCASE which corresponds to VNAME
101    to the value STR.  VNAME must be of type string.
102  */
103 static void
104 set_varname_column (struct ccase *outcase, const struct variable *vname,
105      const char *str)
106 {
107   int len = var_get_width (vname);
108   uint8_t *s = value_str_rw (case_data_rw (outcase, vname), len);
109
110   strncpy ((char *) s, str, len);
111 }
112
113 static void
114 blank_varname_column (struct ccase *outcase, const struct variable *vname)
115 {
116   int len = var_get_width (vname);
117   uint8_t *s = value_str_rw (case_data_rw (outcase, vname), len);
118
119   memset (s, ' ', len);
120 }
121
122 static struct casereader *
123 preprocess (struct casereader *casereader0, const struct dictionary *dict, void *aux)
124 {
125   struct matrix_format *mformat = aux;
126   const struct caseproto *proto = casereader_get_proto (casereader0);
127   struct casewriter *writer;
128   writer = autopaging_writer_create (proto);
129
130   double **matrices = NULL;
131   size_t n_splits = 0;
132
133   const size_t sizeof_matrix =
134     sizeof (double) * mformat->n_continuous_vars * mformat->n_continuous_vars;
135
136
137   /* Make an initial pass to populate our temporary matrix */
138   struct casereader *pass0 = casereader_clone (casereader0);
139   struct ccase *c;
140   unsigned int prev_split_hash = 1;
141   int row = (mformat->triangle == LOWER && mformat->diagonal == NO_DIAGONAL) ? 1 : 0;
142   for (; (c = casereader_read (pass0)) != NULL; case_unref (c))
143     {
144       int s;
145       unsigned int split_hash = 0;
146       for (s = 0; s < mformat->n_split_vars; ++s)
147         {
148           const struct variable *svar = mformat->split_vars[s];
149           const union value *sv = case_data (c, svar);
150           split_hash = value_hash (sv, var_get_width (svar), split_hash);
151         }
152
153       if (matrices == NULL || prev_split_hash != split_hash)
154         {
155           row = (mformat->triangle == LOWER && mformat->diagonal == NO_DIAGONAL) ?
156             1 : 0;
157
158           n_splits++;
159           matrices = xrealloc (matrices, sizeof (double*)  * n_splits);
160           matrices[n_splits - 1] = xmalloc (sizeof_matrix);
161         }
162
163       prev_split_hash = split_hash;
164
165       int c_offset = (mformat->triangle == UPPER) ? row : 0;
166       if (mformat->triangle == UPPER && mformat->diagonal == NO_DIAGONAL)
167         c_offset++;
168       const union value *v = case_data (c, mformat->rowtype);
169       const char *val = (const char *) value_str (v, ROWTYPE_WIDTH);
170       if (0 == strncasecmp (val, "corr    ", ROWTYPE_WIDTH) ||
171           0 == strncasecmp (val, "cov     ", ROWTYPE_WIDTH))
172         {
173           int col;
174           for (col = c_offset; col < mformat->n_continuous_vars; ++col)
175             {
176               const struct variable *var =
177                 dict_get_var (dict,
178                               1 + col - c_offset +
179                               var_get_dict_index (mformat->varname));
180
181               double e = case_data (c, var)->f;
182               if (e == SYSMIS)
183                 continue;
184
185
186               (matrices[n_splits-1])[col + mformat->n_continuous_vars * row] = e;
187               (matrices[n_splits-1]) [row + mformat->n_continuous_vars * col] = e;
188             }
189           row++;
190         }
191     }
192   casereader_destroy (pass0);
193
194   /* Now make a second pass to fill in the other triangle from our
195      temporary matrix */
196   const int idx = var_get_dict_index (mformat->varname);
197   row = 0;
198   struct ccase *prev_case = NULL;
199   prev_split_hash = 1;
200   n_splits = 0;
201   for (; (c = casereader_read (casereader0)) != NULL; prev_case = c)
202     {
203       int s;
204       unsigned int split_hash = 0;
205       for (s = 0; s < mformat->n_split_vars; ++s)
206         {
207           const struct variable *svar = mformat->split_vars[s];
208           const union value *sv = case_data (c, svar);
209           split_hash = value_hash (sv, var_get_width (svar), split_hash);
210         }
211       if (prev_split_hash != split_hash)
212         {
213           n_splits++;
214           row = 0;
215         }
216
217       prev_split_hash = split_hash;
218
219       case_unref (prev_case);
220       struct ccase *outcase = case_create (proto);
221       case_copy (outcase, 0, c, 0, caseproto_get_n_widths (proto));
222       const union value *v = case_data (c, mformat->rowtype);
223       const char *val = (const char *) value_str (v, ROWTYPE_WIDTH);
224       if (0 == strncasecmp (val, "corr    ", ROWTYPE_WIDTH) ||
225           0 == strncasecmp (val, "cov     ", ROWTYPE_WIDTH))
226         {
227           int col;
228           const struct variable *var = dict_get_var (dict, idx + 1 + row);
229           set_varname_column (outcase, mformat->varname, var_get_name (var));
230           value_copy (case_data_rw (outcase, mformat->rowtype), v, ROWTYPE_WIDTH);
231
232           for (col = 0; col < mformat->n_continuous_vars; ++col)
233             {
234               union value *dest_val =
235                 case_data_rw_idx (outcase,
236                                   1 + col + var_get_dict_index (mformat->varname));
237               dest_val->f = (matrices[n_splits - 1])[col + mformat->n_continuous_vars * row];
238               if (col == row && mformat->diagonal == NO_DIAGONAL)
239                 dest_val->f = 1.0;
240             }
241           row++;
242         }
243       else
244         {
245           blank_varname_column (outcase, mformat->varname);
246         }
247
248       /* Special case for SD and N_VECTOR: Rewrite as STDDEV and N respectively */
249       if (0 == strncasecmp (val, "sd      ", ROWTYPE_WIDTH))
250         {
251           value_copy_buf_rpad (case_data_rw (outcase, mformat->rowtype), ROWTYPE_WIDTH,
252                                (uint8_t *) "STDDEV", 6, ' ');
253         }
254       else if (0 == strncasecmp (val, "n_vector", ROWTYPE_WIDTH))
255         {
256           value_copy_buf_rpad (case_data_rw (outcase, mformat->rowtype), ROWTYPE_WIDTH,
257                                (uint8_t *) "N", 1, ' ');
258         }
259
260       casewriter_write (writer, outcase);
261     }
262
263   /* If NODIAGONAL is specified, then a final case must be written */
264   if (mformat->diagonal == NO_DIAGONAL)
265     {
266       int col;
267       struct ccase *outcase = case_create (proto);
268
269       if (prev_case)
270         case_copy (outcase, 0, prev_case, 0, caseproto_get_n_widths (proto));
271
272
273       const struct variable *var = dict_get_var (dict, idx + 1 + row);
274       set_varname_column (outcase, mformat->varname, var_get_name (var));
275
276       for (col = 0; col < mformat->n_continuous_vars; ++col)
277         {
278           union value *dest_val =
279             case_data_rw_idx (outcase, 1 + col +
280                               var_get_dict_index (mformat->varname));
281           dest_val->f = (matrices[n_splits - 1]) [col + mformat->n_continuous_vars * row];
282           if (col == row && mformat->diagonal == NO_DIAGONAL)
283             dest_val->f = 1.0;
284         }
285
286       casewriter_write (writer, outcase);
287     }
288
289   if (prev_case)
290     case_unref (prev_case);
291
292   int i;
293   for (i = 0 ; i < n_splits; ++i)
294     free (matrices[i]);
295   free (matrices);
296   struct casereader *reader1 = casewriter_make_reader (writer);
297   casereader_destroy (casereader0);
298   return reader1;
299 }
300
301 int
302 cmd_matrix (struct lexer *lexer, struct dataset *ds)
303 {
304   struct dictionary *dict;
305   struct data_parser *parser;
306   struct dfm_reader *reader;
307   struct file_handle *fh = NULL;
308   char *encoding = NULL;
309   struct matrix_format mformat;
310   int i;
311   size_t n_names;
312   char **names = NULL;
313
314   mformat.triangle = LOWER;
315   mformat.diagonal = DIAGONAL;
316   mformat.n_split_vars = 0;
317   mformat.split_vars = NULL;
318
319   dict = (in_input_program ()
320           ? dataset_dict (ds)
321           : dict_create (get_default_encoding ()));
322   parser = data_parser_create (dict);
323   reader = NULL;
324
325   data_parser_set_type (parser, DP_DELIMITED);
326   data_parser_set_warn_missing_fields (parser, false);
327   data_parser_set_span (parser, false);
328
329   mformat.rowtype = dict_create_var (dict, "ROWTYPE_", ROWTYPE_WIDTH);
330
331   mformat.n_continuous_vars = 0;
332   mformat.n_split_vars = 0;
333
334   if (! lex_force_match_id (lexer, "VARIABLES"))
335     goto error;
336
337   lex_match (lexer, T_EQUALS);
338
339   if (! parse_mixed_vars (lexer, dict, &names, &n_names, PV_NO_DUPLICATE))
340     {
341       int i;
342       for (i = 0; i < n_names; ++i)
343         free (names[i]);
344       free (names);
345       goto error;
346     }
347
348   int longest_name = 0;
349   for (i = 0; i < n_names; ++i)
350     {
351       maximize_int (&longest_name, strlen (names[i]));
352     }
353
354   mformat.varname = dict_create_var (dict, "VARNAME_",
355                                      8 * DIV_RND_UP (longest_name, 8));
356
357   for (i = 0; i < n_names; ++i)
358     {
359       if (0 == strcasecmp (names[i], "ROWTYPE_"))
360         {
361           const struct fmt_spec fmt = fmt_for_input (FMT_A, 8, 0);
362           data_parser_add_delimited_field (parser,
363                                            &fmt,
364                                            var_get_case_index (mformat.rowtype),
365                                            "ROWTYPE_");
366         }
367       else
368         {
369           const struct fmt_spec fmt = fmt_for_input (FMT_F, 10, 4);
370           struct variable *v = dict_create_var (dict, names[i], 0);
371           var_set_both_formats (v, &fmt);
372           data_parser_add_delimited_field (parser,
373                                            &fmt,
374                                            var_get_case_index (mformat.varname) +
375                                            ++mformat.n_continuous_vars,
376                                            names[i]);
377         }
378     }
379   for (i = 0; i < n_names; ++i)
380     free (names[i]);
381   free (names);
382
383   while (lex_token (lexer) != T_ENDCMD)
384     {
385       if (! lex_force_match (lexer, T_SLASH))
386         goto error;
387
388       if (lex_match_id (lexer, "FORMAT"))
389         {
390           lex_match (lexer, T_EQUALS);
391
392           while (lex_token (lexer) != T_SLASH && (lex_token (lexer) != T_ENDCMD))
393             {
394               if (lex_match_id (lexer, "LIST"))
395                 {
396                   data_parser_set_span (parser, false);
397                 }
398               else if (lex_match_id (lexer, "FREE"))
399                 {
400                   data_parser_set_span (parser, true);
401                 }
402               else if (lex_match_id (lexer, "UPPER"))
403                 {
404                   mformat.triangle = UPPER;
405                 }
406               else if (lex_match_id (lexer, "LOWER"))
407                 {
408                   mformat.triangle = LOWER;
409                 }
410               else if (lex_match_id (lexer, "FULL"))
411                 {
412                   mformat.triangle = FULL;
413                 }
414               else if (lex_match_id (lexer, "DIAGONAL"))
415                 {
416                   mformat.diagonal = DIAGONAL;
417                 }
418               else if (lex_match_id (lexer, "NODIAGONAL"))
419                 {
420                   mformat.diagonal = NO_DIAGONAL;
421                 }
422               else
423                 {
424                   lex_error (lexer, NULL);
425                   goto error;
426                 }
427             }
428         }
429       else if (lex_match_id (lexer, "FILE"))
430         {
431           lex_match (lexer, T_EQUALS);
432           fh_unref (fh);
433           fh = fh_parse (lexer, FH_REF_FILE | FH_REF_INLINE, NULL);
434           if (fh == NULL)
435             goto error;
436         }
437       else if (lex_match_id (lexer, "SPLIT"))
438         {
439           lex_match (lexer, T_EQUALS);
440           if (! parse_variables (lexer, dict, &mformat.split_vars, &mformat.n_split_vars, 0))
441             {
442               free (mformat.split_vars);
443               goto error;
444             }
445           int i;
446           for (i = 0; i < mformat.n_split_vars; ++i)
447             {
448               const struct fmt_spec fmt = fmt_for_input (FMT_F, 4, 0);
449               var_set_both_formats (mformat.split_vars[i], &fmt);
450             }
451           dict_reorder_vars (dict, mformat.split_vars, mformat.n_split_vars);
452           mformat.n_continuous_vars -= mformat.n_split_vars;
453         }
454       else
455         {
456           lex_error (lexer, NULL);
457           goto error;
458         }
459     }
460
461   if (mformat.diagonal == NO_DIAGONAL && mformat.triangle == FULL)
462     {
463       msg (SE, _("FORMAT = FULL and FORMAT = NODIAGONAL are mutually exclusive."));
464       goto error;
465     }
466
467   if (fh == NULL)
468     fh = fh_inline_file ();
469   fh_set_default_handle (fh);
470
471   if (!data_parser_any_fields (parser))
472     {
473       msg (SE, _("At least one variable must be specified."));
474       goto error;
475     }
476
477   if (lex_end_of_command (lexer) != CMD_SUCCESS)
478     goto error;
479
480   reader = dfm_open_reader (fh, lexer, encoding);
481   if (reader == NULL)
482     goto error;
483
484   if (in_input_program ())
485     {
486       struct data_list_trns *trns = xmalloc (sizeof *trns);
487       trns->parser = parser;
488       trns->reader = reader;
489       trns->end = NULL;
490       add_transformation (ds, data_list_trns_proc, data_list_trns_free, trns);
491     }
492   else
493     {
494       data_parser_make_active_file (parser, ds, reader, dict, preprocess, &mformat);
495     }
496
497   fh_unref (fh);
498   free (encoding);
499   free (mformat.split_vars);
500
501   return CMD_DATA_LIST;
502
503  error:
504   data_parser_destroy (parser);
505   if (!in_input_program ())
506     dict_destroy (dict);
507   fh_unref (fh);
508   free (encoding);
509   free (mformat.split_vars);
510   return CMD_CASCADING_FAILURE;
511 }
512
513 \f
514 /* Input procedure. */
515
516 /* Destroys DATA LIST transformation TRNS.
517    Returns true if successful, false if an I/O error occurred. */
518 static bool
519 data_list_trns_free (void *trns_)
520 {
521   struct data_list_trns *trns = trns_;
522   data_parser_destroy (trns->parser);
523   dfm_close_reader (trns->reader);
524   free (trns);
525   return true;
526 }
527
528 /* Handle DATA LIST transformation TRNS, parsing data into *C. */
529 static int
530 data_list_trns_proc (void *trns_, struct ccase **c, casenumber case_num UNUSED)
531 {
532   struct data_list_trns *trns = trns_;
533   int retval;
534
535   *c = case_unshare (*c);
536   if (data_parser_parse (trns->parser, trns->reader, *c))
537     retval = TRNS_CONTINUE;
538   else if (dfm_reader_error (trns->reader) || dfm_eof (trns->reader) > 1)
539     {
540       /* An I/O error, or encountering end of file for a second
541          time, should be escalated into a more serious error. */
542       retval = TRNS_ERROR;
543     }
544   else
545     retval = TRNS_END_FILE;
546
547   /* If there was an END subcommand handle it. */
548   if (trns->end != NULL)
549     {
550       double *end = &case_data_rw (*c, trns->end)->f;
551       if (retval == TRNS_END_FILE)
552         {
553           *end = 1.0;
554           retval = TRNS_CONTINUE;
555         }
556       else
557         *end = 0.0;
558     }
559
560   return retval;
561 }
562