value: Get rid of value_str(), value_str_rw(), value_num().
[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   long n;
81 };
82
83 /*
84 valid rowtype_ values:
85   CORR,
86   COV,
87   MAT,
88
89
90   MSE,
91   DFE,
92   MEAN,
93   STDDEV (or SD),
94   N_VECTOR (or N),
95   N_SCALAR,
96   N_MATRIX,
97   COUNT,
98   PROX.
99 */
100
101 /* Sets the value of OUTCASE which corresponds to VNAME
102    to the value STR.  VNAME must be of type string.
103  */
104 static void
105 set_varname_column (struct ccase *outcase, const struct variable *vname,
106      const char *str)
107 {
108   int len = var_get_width (vname);
109   uint8_t *s = case_str_rw (outcase, vname);
110
111   strncpy (CHAR_CAST (char *, s), str, len);
112 }
113
114 static void
115 blank_varname_column (struct ccase *outcase, const struct variable *vname)
116 {
117   int len = var_get_width (vname);
118   uint8_t *s = case_str_rw (outcase, vname);
119
120   memset (s, ' ', len);
121 }
122
123 static struct casereader *
124 preprocess (struct casereader *casereader0, const struct dictionary *dict, void *aux)
125 {
126   struct matrix_format *mformat = aux;
127   const struct caseproto *proto = casereader_get_proto (casereader0);
128   struct casewriter *writer = autopaging_writer_create (proto);
129   struct ccase *prev_case = NULL;
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   union value *prev_values = xcalloc (mformat->n_split_vars, sizeof *prev_values);
141   int row = (mformat->triangle == LOWER && mformat->diagonal == NO_DIAGONAL) ? 1 : 0;
142   bool first_case = true;
143   for (; (c = casereader_read (pass0)) != NULL; case_unref (c))
144     {
145       int s;
146       bool match = false;
147       if (!first_case)
148         {
149           match = true;
150           for (s = 0; s < mformat->n_split_vars; ++s)
151             {
152               const struct variable *svar = mformat->split_vars[s];
153               const union value *sv = case_data (c, svar);
154               if (! value_equal (prev_values + s, sv, var_get_width (svar)))
155                 {
156                   match = false;
157                   break;
158                 }
159             }
160         }
161       first_case = false;
162
163       if (matrices == NULL || ! match)
164         {
165           row = (mformat->triangle == LOWER && mformat->diagonal == NO_DIAGONAL) ?
166             1 : 0;
167
168           n_splits++;
169           matrices = xrealloc (matrices, sizeof (double*)  * n_splits);
170           matrices[n_splits - 1] = xmalloc (sizeof_matrix);
171         }
172
173       for (s = 0; s < mformat->n_split_vars; ++s)
174         {
175           const struct variable *svar = mformat->split_vars[s];
176           const union value *sv = case_data (c, svar);
177           value_clone (prev_values + s, sv, var_get_width (svar));
178         }
179
180       int c_offset = (mformat->triangle == UPPER) ? row : 0;
181       if (mformat->triangle == UPPER && mformat->diagonal == NO_DIAGONAL)
182         c_offset++;
183       const union value *v = case_data (c, mformat->rowtype);
184       const char *val = CHAR_CAST (const char *, v->s);
185       if (0 == strncasecmp (val, "corr    ", ROWTYPE_WIDTH) ||
186           0 == strncasecmp (val, "cov     ", ROWTYPE_WIDTH))
187         {
188           if (row >= mformat->n_continuous_vars)
189             {
190               msg (SE,
191                    _("There are %d variable declared but the data has at least %d matrix rows."),
192                    mformat->n_continuous_vars, row + 1);
193               case_unref (c);
194               casereader_destroy (pass0);
195               free (prev_values);
196               goto error;
197             }
198           int col;
199           for (col = c_offset; col < mformat->n_continuous_vars; ++col)
200             {
201               const struct variable *var =
202                 dict_get_var (dict,
203                               1 + col - c_offset +
204                               var_get_dict_index (mformat->varname));
205
206               double e = case_data (c, var)->f;
207               if (e == SYSMIS)
208                 continue;
209
210               /* Fill in the lower triangle */
211               (matrices[n_splits-1])[col + mformat->n_continuous_vars * row] = e;
212
213               if (mformat->triangle != FULL)
214                 /* Fill in the upper triangle */
215                 (matrices[n_splits-1]) [row + mformat->n_continuous_vars * col] = e;
216             }
217           row++;
218         }
219     }
220   casereader_destroy (pass0);
221   free (prev_values);
222
223   /* Now make a second pass to fill in the other triangle from our
224      temporary matrix */
225   const int idx = var_get_dict_index (mformat->varname);
226   row = 0;
227
228   if (mformat->n >= 0)
229     {
230       int col;
231       struct ccase *outcase = case_create (proto);
232       union value *v = case_data_rw (outcase, mformat->rowtype);
233       memcpy (v->s, "N       ", ROWTYPE_WIDTH);
234       blank_varname_column (outcase, mformat->varname);
235       for (col = 0; col < mformat->n_continuous_vars; ++col)
236         {
237           union value *dest_val =
238             case_data_rw_idx (outcase,
239                               1 + col + var_get_dict_index (mformat->varname));
240           dest_val->f = mformat->n;
241         }
242       casewriter_write (writer, outcase);
243     }
244
245   n_splits = 0;
246   prev_values = xcalloc (mformat->n_split_vars, sizeof *prev_values);
247   first_case = true;
248   for (; (c = casereader_read (casereader0)) != NULL; prev_case = c)
249     {
250       int s;
251       bool match = false;
252       if (!first_case)
253         {
254           match = true;
255           for (s = 0; s < mformat->n_split_vars; ++s)
256             {
257               const struct variable *svar = mformat->split_vars[s];
258               const union value *sv = case_data (c, svar);
259               if (! value_equal (prev_values + s, sv, var_get_width (svar)))
260                 {
261                   match = false;
262                   break;
263                 }
264             }
265         }
266       first_case = false;
267       if (! match)
268         {
269           n_splits++;
270           row = 0;
271         }
272
273       for (s = 0; s < mformat->n_split_vars; ++s)
274         {
275           const struct variable *svar = mformat->split_vars[s];
276           const union value *sv = case_data (c, svar);
277           value_clone (prev_values + s, sv, var_get_width (svar));
278         }
279
280       case_unref (prev_case);
281       const union value *v = case_data (c, mformat->rowtype);
282       const char *val = CHAR_CAST (const char *, v->s);
283       if (mformat->n >= 0)
284         {
285           if (0 == strncasecmp (val, "n       ", ROWTYPE_WIDTH) ||
286               0 == strncasecmp (val, "n_vector", ROWTYPE_WIDTH))
287             {
288               msg (SW,
289                    _("The N subcommand was specified, but a N record was also found in the data.  The N record will be ignored."));
290               continue;
291             }
292         }
293
294       struct ccase *outcase = case_create (proto);
295       case_copy (outcase, 0, c, 0, caseproto_get_n_widths (proto));
296
297       if (0 == strncasecmp (val, "corr    ", ROWTYPE_WIDTH) ||
298           0 == strncasecmp (val, "cov     ", ROWTYPE_WIDTH))
299         {
300           int col;
301           const struct variable *var = dict_get_var (dict, idx + 1 + row);
302           set_varname_column (outcase, mformat->varname, var_get_name (var));
303           value_copy (case_data_rw (outcase, mformat->rowtype), v, ROWTYPE_WIDTH);
304
305           for (col = 0; col < mformat->n_continuous_vars; ++col)
306             {
307               union value *dest_val =
308                 case_data_rw_idx (outcase,
309                                   1 + col + var_get_dict_index (mformat->varname));
310               dest_val->f = (matrices[n_splits - 1])[col + mformat->n_continuous_vars * row];
311               if (col == row && mformat->diagonal == NO_DIAGONAL)
312                 dest_val->f = 1.0;
313             }
314           row++;
315         }
316       else
317         {
318           blank_varname_column (outcase, mformat->varname);
319         }
320
321       /* Special case for SD and N_VECTOR: Rewrite as STDDEV and N respectively */
322       if (0 == strncasecmp (val, "sd      ", ROWTYPE_WIDTH))
323         {
324           value_copy_buf_rpad (case_data_rw (outcase, mformat->rowtype), ROWTYPE_WIDTH,
325                                (uint8_t *) "STDDEV", 6, ' ');
326         }
327       else if (0 == strncasecmp (val, "n_vector", ROWTYPE_WIDTH))
328         {
329           value_copy_buf_rpad (case_data_rw (outcase, mformat->rowtype), ROWTYPE_WIDTH,
330                                (uint8_t *) "N", 1, ' ');
331         }
332
333       casewriter_write (writer, outcase);
334     }
335
336   /* If NODIAGONAL is specified, then a final case must be written */
337   if (mformat->diagonal == NO_DIAGONAL)
338     {
339       int col;
340       struct ccase *outcase = case_create (proto);
341
342       if (prev_case)
343         case_copy (outcase, 0, prev_case, 0, caseproto_get_n_widths (proto));
344
345       const struct variable *var = dict_get_var (dict, idx + 1 + row);
346       set_varname_column (outcase, mformat->varname, var_get_name (var));
347
348       for (col = 0; col < mformat->n_continuous_vars; ++col)
349         {
350           union value *dest_val =
351             case_data_rw_idx (outcase, 1 + col +
352                               var_get_dict_index (mformat->varname));
353           dest_val->f = (matrices[n_splits - 1]) [col + mformat->n_continuous_vars * row];
354           if (col == row && mformat->diagonal == NO_DIAGONAL)
355             dest_val->f = 1.0;
356         }
357
358       casewriter_write (writer, outcase);
359     }
360   free (prev_values);
361
362   if (prev_case)
363     case_unref (prev_case);
364
365   int i;
366   for (i = 0 ; i < n_splits; ++i)
367     free (matrices[i]);
368   free (matrices);
369   struct casereader *reader1 = casewriter_make_reader (writer);
370   casereader_destroy (casereader0);
371   return reader1;
372
373
374 error:
375   if (prev_case)
376     case_unref (prev_case);
377
378   for (i = 0 ; i < n_splits; ++i)
379     free (matrices[i]);
380   free (matrices);
381   casereader_destroy (casereader0);
382   casewriter_destroy (writer);
383   return NULL;
384 }
385
386 int
387 cmd_matrix (struct lexer *lexer, struct dataset *ds)
388 {
389   struct dictionary *dict;
390   struct data_parser *parser;
391   struct dfm_reader *reader;
392   struct file_handle *fh = NULL;
393   char *encoding = NULL;
394   struct matrix_format mformat;
395   int i;
396   size_t n_names;
397   char **names = NULL;
398
399   mformat.triangle = LOWER;
400   mformat.diagonal = DIAGONAL;
401   mformat.n_split_vars = 0;
402   mformat.split_vars = NULL;
403   mformat.n = -1;
404
405   dict = (in_input_program ()
406           ? dataset_dict (ds)
407           : dict_create (get_default_encoding ()));
408   parser = data_parser_create (dict);
409   reader = NULL;
410
411   data_parser_set_type (parser, DP_DELIMITED);
412   data_parser_set_warn_missing_fields (parser, false);
413   data_parser_set_span (parser, false);
414
415   mformat.rowtype = dict_create_var (dict, "ROWTYPE_", ROWTYPE_WIDTH);
416
417   mformat.n_continuous_vars = 0;
418   mformat.n_split_vars = 0;
419
420   if (! lex_force_match_id (lexer, "VARIABLES"))
421     goto error;
422
423   lex_match (lexer, T_EQUALS);
424
425   if (! parse_mixed_vars (lexer, dict, &names, &n_names, PV_NO_DUPLICATE))
426     {
427       int i;
428       for (i = 0; i < n_names; ++i)
429         free (names[i]);
430       free (names);
431       goto error;
432     }
433
434   int longest_name = 0;
435   for (i = 0; i < n_names; ++i)
436     {
437       maximize_int (&longest_name, strlen (names[i]));
438     }
439
440   mformat.varname = dict_create_var (dict, "VARNAME_",
441                                      8 * DIV_RND_UP (longest_name, 8));
442
443   for (i = 0; i < n_names; ++i)
444     {
445       if (0 == strcasecmp (names[i], "ROWTYPE_"))
446         {
447           const struct fmt_spec fmt = fmt_for_input (FMT_A, 8, 0);
448           data_parser_add_delimited_field (parser,
449                                            &fmt,
450                                            var_get_case_index (mformat.rowtype),
451                                            "ROWTYPE_");
452         }
453       else
454         {
455           const struct fmt_spec fmt = fmt_for_input (FMT_F, 10, 4);
456           struct variable *v = dict_create_var (dict, names[i], 0);
457           var_set_both_formats (v, &fmt);
458           data_parser_add_delimited_field (parser,
459                                            &fmt,
460                                            var_get_case_index (mformat.varname) +
461                                            ++mformat.n_continuous_vars,
462                                            names[i]);
463         }
464     }
465   for (i = 0; i < n_names; ++i)
466     free (names[i]);
467   free (names);
468
469   while (lex_token (lexer) != T_ENDCMD)
470     {
471       if (! lex_force_match (lexer, T_SLASH))
472         goto error;
473
474       if (lex_match_id (lexer, "N"))
475         {
476           lex_match (lexer, T_EQUALS);
477
478           if (! lex_force_int (lexer))
479             goto error;
480
481           mformat.n = lex_integer (lexer);
482           if (mformat.n < 0)
483             {
484               msg (SE, _("%s must not be negative."), "N");
485               goto error;
486             }
487           lex_get (lexer);
488         }
489       else if (lex_match_id (lexer, "FORMAT"))
490         {
491           lex_match (lexer, T_EQUALS);
492
493           while (lex_token (lexer) != T_SLASH && (lex_token (lexer) != T_ENDCMD))
494             {
495               if (lex_match_id (lexer, "LIST"))
496                 {
497                   data_parser_set_span (parser, false);
498                 }
499               else if (lex_match_id (lexer, "FREE"))
500                 {
501                   data_parser_set_span (parser, true);
502                 }
503               else if (lex_match_id (lexer, "UPPER"))
504                 {
505                   mformat.triangle = UPPER;
506                 }
507               else if (lex_match_id (lexer, "LOWER"))
508                 {
509                   mformat.triangle = LOWER;
510                 }
511               else if (lex_match_id (lexer, "FULL"))
512                 {
513                   mformat.triangle = FULL;
514                 }
515               else if (lex_match_id (lexer, "DIAGONAL"))
516                 {
517                   mformat.diagonal = DIAGONAL;
518                 }
519               else if (lex_match_id (lexer, "NODIAGONAL"))
520                 {
521                   mformat.diagonal = NO_DIAGONAL;
522                 }
523               else
524                 {
525                   lex_error (lexer, NULL);
526                   goto error;
527                 }
528             }
529         }
530       else if (lex_match_id (lexer, "FILE"))
531         {
532           lex_match (lexer, T_EQUALS);
533           fh_unref (fh);
534           fh = fh_parse (lexer, FH_REF_FILE | FH_REF_INLINE, NULL);
535           if (fh == NULL)
536             goto error;
537         }
538       else if (lex_match_id (lexer, "SPLIT"))
539         {
540           lex_match (lexer, T_EQUALS);
541           if (! parse_variables (lexer, dict, &mformat.split_vars, &mformat.n_split_vars, 0))
542             {
543               free (mformat.split_vars);
544               goto error;
545             }
546           int i;
547           for (i = 0; i < mformat.n_split_vars; ++i)
548             {
549               const struct fmt_spec fmt = fmt_for_input (FMT_F, 4, 0);
550               var_set_both_formats (mformat.split_vars[i], &fmt);
551             }
552           dict_reorder_vars (dict, mformat.split_vars, mformat.n_split_vars);
553           mformat.n_continuous_vars -= mformat.n_split_vars;
554         }
555       else
556         {
557           lex_error (lexer, NULL);
558           goto error;
559         }
560     }
561
562   if (mformat.diagonal == NO_DIAGONAL && mformat.triangle == FULL)
563     {
564       msg (SE, _("FORMAT = FULL and FORMAT = NODIAGONAL are mutually exclusive."));
565       goto error;
566     }
567
568   if (fh == NULL)
569     fh = fh_inline_file ();
570   fh_set_default_handle (fh);
571
572   if (!data_parser_any_fields (parser))
573     {
574       msg (SE, _("At least one variable must be specified."));
575       goto error;
576     }
577
578   if (lex_end_of_command (lexer) != CMD_SUCCESS)
579     goto error;
580
581   reader = dfm_open_reader (fh, lexer, encoding);
582   if (reader == NULL)
583     goto error;
584
585   if (in_input_program ())
586     {
587       struct data_list_trns *trns = xmalloc (sizeof *trns);
588       trns->parser = parser;
589       trns->reader = reader;
590       trns->end = NULL;
591       add_transformation (ds, data_list_trns_proc, data_list_trns_free, trns);
592     }
593   else
594     {
595       data_parser_make_active_file (parser, ds, reader, dict, preprocess,
596                                     &mformat);
597     }
598
599   fh_unref (fh);
600   free (encoding);
601   free (mformat.split_vars);
602
603   return CMD_DATA_LIST;
604
605  error:
606   data_parser_destroy (parser);
607   if (!in_input_program ())
608     dict_unref (dict);
609   fh_unref (fh);
610   free (encoding);
611   free (mformat.split_vars);
612   return CMD_CASCADING_FAILURE;
613 }
614
615 \f
616 /* Input procedure. */
617
618 /* Destroys DATA LIST transformation TRNS.
619    Returns true if successful, false if an I/O error occurred. */
620 static bool
621 data_list_trns_free (void *trns_)
622 {
623   struct data_list_trns *trns = trns_;
624   data_parser_destroy (trns->parser);
625   dfm_close_reader (trns->reader);
626   free (trns);
627   return true;
628 }
629
630 /* Handle DATA LIST transformation TRNS, parsing data into *C. */
631 static int
632 data_list_trns_proc (void *trns_, struct ccase **c, casenumber case_num UNUSED)
633 {
634   struct data_list_trns *trns = trns_;
635   int retval;
636
637   *c = case_unshare (*c);
638   if (data_parser_parse (trns->parser, trns->reader, *c))
639     retval = TRNS_CONTINUE;
640   else if (dfm_reader_error (trns->reader) || dfm_eof (trns->reader) > 1)
641     {
642       /* An I/O error, or encountering end of file for a second
643          time, should be escalated into a more serious error. */
644       retval = TRNS_ERROR;
645     }
646   else
647     retval = TRNS_END_FILE;
648
649   /* If there was an END subcommand handle it. */
650   if (trns->end != NULL)
651     {
652       double *end = &case_data_rw (*c, trns->end)->f;
653       if (retval == TRNS_END_FILE)
654         {
655           *end = 1.0;
656           retval = TRNS_CONTINUE;
657         }
658       else
659         *end = 0.0;
660     }
661
662   return retval;
663 }