31d6b710b0ba68a54402d33e50e559b9f581bf2e
[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 <gsl/gsl_matrix.h>
20 #include <gsl/gsl_vector.h>
21
22 #include "data/case.h"
23 #include "data/casereader.h"
24 #include "data/casewriter.h"
25 #include "data/data-in.h"
26 #include "data/dataset.h"
27 #include "data/dictionary.h"
28 #include "data/format.h"
29 #include "data/short-names.h"
30 #include "data/transformations.h"
31 #include "data/variable.h"
32 #include "language/command.h"
33 #include "language/data-io/data-parser.h"
34 #include "language/data-io/data-reader.h"
35 #include "language/data-io/file-handle.h"
36 #include "language/data-io/inpt-pgm.h"
37 #include "language/data-io/placement-parser.h"
38 #include "language/lexer/lexer.h"
39 #include "language/lexer/variable-parser.h"
40 #include "libpspp/assertion.h"
41 #include "libpspp/i18n.h"
42 #include "libpspp/intern.h"
43 #include "libpspp/message.h"
44 #include "libpspp/str.h"
45
46 #include "gl/c-ctype.h"
47 #include "gl/minmax.h"
48 #include "gl/xsize.h"
49 #include "gl/xalloc.h"
50
51 #include "gettext.h"
52 #define _(msgid) gettext (msgid)
53 \f
54 #define ROWTYPES                                \
55     /* Matrix row types. */                     \
56     RT(CORR,     2)                             \
57     RT(COV,      2)                             \
58     RT(MAT,      2)                             \
59     RT(N_MATRIX, 2)                             \
60     RT(PROX,     2)                             \
61                                                 \
62     /* Vector row types. */                     \
63     RT(COUNT,    1)                             \
64     RT(DFE,      1)                             \
65     RT(MEAN,     1)                             \
66     RT(MSE,      1)                             \
67     RT(STDDEV,   1)                             \
68     RT(N, 1)                                    \
69                                                 \
70     /* Scalar row types. */                     \
71     RT(N_SCALAR, 0)
72
73 enum rowtype
74   {
75 #define RT(NAME, DIMS) C_##NAME,
76     ROWTYPES
77 #undef RT
78   };
79
80 enum
81   {
82 #define RT(NAME, DIMS) +1
83     N_ROWTYPES = ROWTYPES
84 #undef RT
85   };
86 verify (N_ROWTYPES < 32);
87
88 /* Returns the number of dimensions in the indexes for row type RT.  A matrix
89    has 2 dimensions, a vector has 1, a scalar has 0. */
90 static int
91 rowtype_dimensions (enum rowtype rt)
92 {
93   static const int rowtype_dims[N_ROWTYPES] = {
94 #define RT(NAME, DIMS) [C_##NAME] = DIMS,
95     ROWTYPES
96 #undef RT
97   };
98   return rowtype_dims[rt];
99 }
100
101 static struct substring
102 rowtype_name (enum rowtype rt)
103 {
104   static const struct substring rowtype_names[N_ROWTYPES] = {
105 #define RT(NAME, DIMS) [C_##NAME] = SS_LITERAL_INITIALIZER (#NAME),
106     ROWTYPES
107 #undef RT
108   };
109
110   return rowtype_names[rt];
111 }
112
113 static bool
114 rowtype_from_string (struct substring token, enum rowtype *rt)
115 {
116   ss_trim (&token, ss_cstr (CC_SPACES));
117   for (size_t i = 0; i < N_ROWTYPES; i++)
118     if (lex_id_match (rowtype_name (i), token))
119       {
120         *rt = i;
121         return true;
122       }
123
124   if (lex_id_match (ss_cstr ("N_VECTOR"), token))
125     {
126       *rt = C_N;
127       return true;
128     }
129   else if (lex_id_match (ss_cstr ("SD"), token))
130     {
131       *rt = C_STDDEV;
132       return true;
133     }
134
135   return false;
136 }
137
138 static bool
139 rowtype_parse (struct lexer *lexer, enum rowtype *rt)
140 {
141   bool parsed = (lex_token (lexer) == T_ID
142                  && rowtype_from_string (lex_tokss (lexer), rt));
143   if (parsed)
144     lex_get (lexer);
145   return parsed;
146 }
147 \f
148 struct matrix_format
149   {
150     bool span;
151     enum triangle
152       {
153         LOWER,
154         UPPER,
155         FULL
156       }
157     triangle;
158     enum diagonal
159       {
160         DIAGONAL,
161         NO_DIAGONAL
162       }
163     diagonal;
164
165     bool input_rowtype;
166     struct variable **input_vars;
167     size_t n_input_vars;
168
169     /* How to read matrices with each possible number of dimensions (0=scalar,
170        1=vector, 2=matrix). */
171     struct matrix_sched
172       {
173         /* Number of rows and columns in the matrix: (1,1) for a scalar, (1,n) for
174            a vector, (n,n) for a matrix. */
175         int nr, nc;
176
177         /* Rows of data to read and the number of columns in each.  Because we
178            often read just a triangle and sometimes omit the diagonal, 'n_rp' can
179            be less than 'nr' and 'rp[i]->y' isn't always 'y'. */
180         struct row_sched
181           {
182             /* The y-value of the row inside the matrix. */
183             int y;
184
185             /* first and last (exclusive) columns to read in this row. */
186             int x0, x1;
187           }
188           *rp;
189         size_t n_rp;
190       }
191     ms[3];
192
193     struct variable *rowtype;
194     struct variable *varname;
195     struct variable **cvars;
196     int n_cvars;
197     struct variable **svars;
198     size_t *svar_indexes;
199     size_t n_svars;
200     struct variable **fvars;
201     size_t *fvar_indexes;
202     size_t n_fvars;
203     int cells;
204     int n;
205
206     unsigned int pooled_rowtype_mask;
207     unsigned int factor_rowtype_mask;
208
209     struct content
210       {
211         bool open;
212         enum rowtype rowtype;
213         bool close;
214       }
215     *contents;
216     size_t n_contents;
217   };
218
219 static void
220 matrix_format_uninit (struct matrix_format *mf)
221 {
222   free (mf->input_vars);
223   for (int i = 0; i < 3; i++)
224     free (mf->ms[i].rp);
225   free (mf->cvars);
226   free (mf->svars);
227   free (mf->svar_indexes);
228   free (mf->fvars);
229   free (mf->fvar_indexes);
230   free (mf->contents);
231 }
232
233 static void
234 set_string (struct ccase *outcase, const struct variable *var,
235             struct substring src)
236 {
237   struct substring dst = case_ss (outcase, var);
238   for (size_t i = 0; i < dst.length; i++)
239     dst.string[i] = i < src.length ? src.string[i] : ' ';
240 }
241
242 static void
243 parse_msg (struct dfm_reader *reader, const struct substring *token,
244            char *text, enum msg_severity severity)
245 {
246   int first_column = 0;
247   if (token)
248     {
249       struct substring line = dfm_get_record (reader);
250       if (token->string >= line.string && token->string < ss_end (line))
251         first_column = ss_pointer_to_position (line, token->string) + 1;
252     }
253
254   int line_number = dfm_get_line_number (reader);
255   struct msg_location *location = xmalloc (sizeof *location);
256   *location = (struct msg_location) {
257     .file_name = intern_new (dfm_get_file_name (reader)),
258     .first_line = line_number,
259     .last_line = line_number + 1,
260     .first_column = first_column,
261     .last_column = first_column ? first_column + token->length : 0,
262   };
263   struct msg *m = xmalloc (sizeof *m);
264   *m = (struct msg) {
265     .category = MSG_C_DATA,
266     .severity = severity,
267     .location = location,
268     .text = text,
269   };
270   msg_emit (m);
271 }
272
273 static void PRINTF_FORMAT (3, 4)
274 parse_warning (struct dfm_reader *reader, const struct substring *token,
275                const char *format, ...)
276 {
277   va_list args;
278   va_start (args, format);
279   parse_msg (reader, token, xvasprintf (format, args), MSG_S_WARNING);
280   va_end (args);
281 }
282
283 static void PRINTF_FORMAT (3, 4)
284 parse_error (struct dfm_reader *reader, const struct substring *token,
285              const char *format, ...)
286 {
287   va_list args;
288   va_start (args, format);
289   parse_msg (reader, token, xvasprintf (format, args), MSG_S_ERROR);
290   va_end (args);
291 }
292
293 /* Advance to beginning of next token. */
294 static bool
295 more_tokens (struct substring *p, struct dfm_reader *r)
296 {
297   for (;;)
298     {
299       ss_ltrim (p, ss_cstr (CC_SPACES ","));
300       if (p->length)
301         return true;
302
303       dfm_forward_record (r);
304       if (dfm_eof (r))
305         return false;
306       *p = dfm_get_record (r);
307     }
308 }
309
310 static bool
311 next_token (struct substring *p, struct dfm_reader *r, struct substring *token)
312 {
313   if (!more_tokens (p, r))
314     return false;
315
316   /* Collect token. */
317   int c = ss_first (*p);
318   if (c == '\'' || c == '"')
319     {
320       ss_advance (p, 1);
321       ss_get_until (p, c, token);
322     }
323   else
324     {
325       size_t n = 1;
326       for (;;)
327         {
328           c = ss_at (*p, n);
329           if (c == EOF
330               || ss_find_byte (ss_cstr (CC_SPACES ","), c) != SIZE_MAX
331               || ((c == '+' || c == '-')
332                   && ss_find_byte (ss_cstr ("dDeE"),
333                                    ss_at (*p, n - 1)) == SIZE_MAX))
334             break;
335           n++;
336         }
337       ss_get_bytes (p, n, token);
338     }
339   return true;
340 }
341
342 static bool
343 next_number (struct substring *p, struct dfm_reader *r, double *d)
344 {
345   struct substring token;
346   if (!next_token (p, r, &token))
347     return false;
348
349   union value v;
350   char *error = data_in (token, dfm_reader_get_encoding (r), FMT_F,
351                          settings_get_fmt_settings (), &v, 0, NULL);
352   if (error)
353     {
354       parse_error (r, &token, "%s", error);
355       free (error);
356     }
357   *d = v.f;
358   return true;
359 }
360
361 static bool
362 next_rowtype (struct substring *p, struct dfm_reader *r, enum rowtype *rt)
363 {
364   struct substring token;
365   if (!next_token (p, r, &token))
366     return false;
367
368   if (rowtype_from_string (token, rt))
369     return true;
370
371   parse_error (r, &token, _("Unknown row type \"%.*s\"."),
372                (int) token.length, token.string);
373   return false;
374 }
375
376 struct read_matrix_params
377   {
378     /* Adjustments to first and last row to read. */
379     int dy0, dy1;
380
381     /* Left and right columns to read in first row, inclusive.
382        For x1, INT_MAX is the rightmost column. */
383     int x0, x1;
384
385     /* Adjustment to x0 and x1 for each subsequent row we read.  Each of these
386        is 0 to keep it the same or -1 or +1 to adjust it by that much. */
387     int dx0, dx1;
388   };
389
390 static const struct read_matrix_params *
391 get_read_matrix_params (const struct matrix_format *mf)
392 {
393   if (mf->triangle == FULL)
394     {
395       /* 1 2 3 4
396          2 1 5 6
397          3 5 1 7
398          4 6 7 1 */
399       static const struct read_matrix_params rmp = { 0, 0, 0, INT_MAX, 0, 0 };
400       return &rmp;
401     }
402   else if (mf->triangle == LOWER)
403     {
404       if (mf->diagonal == DIAGONAL)
405         {
406           /* 1 . . .
407              2 1 . .
408              3 5 1 .
409              4 6 7 1 */
410           static const struct read_matrix_params rmp = { 0, 0, 0, 0, 0, 1 };
411           return &rmp;
412         }
413       else
414         {
415           /* . . . .
416              2 . . .
417              3 5 . .
418              4 6 7 . */
419           static const struct read_matrix_params rmp = { 1, 0, 0, 0, 0, 1 };
420           return &rmp;
421         }
422     }
423   else if (mf->triangle == UPPER)
424     {
425       if (mf->diagonal == DIAGONAL)
426         {
427           /* 1 2 3 4
428              . 1 5 6
429              . . 1 7
430              . . . 1 */
431           static const struct read_matrix_params rmp = { 0, 0, 0, INT_MAX, 1, 0 };
432           return &rmp;
433         }
434       else
435         {
436           /* . 2 3 4
437              . . 5 6
438              . . . 7
439              . . . . */
440           static const struct read_matrix_params rmp = { 0, -1, 1, INT_MAX, 1, 0 };
441           return &rmp;
442         }
443     }
444   else
445     NOT_REACHED ();
446 }
447
448 static void
449 schedule_matrices (struct matrix_format *mf)
450 {
451   struct matrix_sched *ms0 = &mf->ms[0];
452   ms0->nr = 1;
453   ms0->nc = 1;
454   ms0->rp = xmalloc (sizeof *ms0->rp);
455   ms0->rp[0] = (struct row_sched) { .y = 0, .x0 = 0, .x1 = 1 };
456   ms0->n_rp = 1;
457
458   struct matrix_sched *ms1 = &mf->ms[1];
459   ms1->nr = 1;
460   ms1->nc = mf->n_cvars;
461   ms1->rp = xmalloc (sizeof *ms1->rp);
462   ms1->rp[0] = (struct row_sched) { .y = 0, .x0 = 0, .x1 = mf->n_cvars };
463   ms1->n_rp = 1;
464
465   struct matrix_sched *ms2 = &mf->ms[2];
466   ms2->nr = mf->n_cvars;
467   ms2->nc = mf->n_cvars;
468   ms2->rp = xmalloc (mf->n_cvars * sizeof *ms2->rp);
469   ms2->n_rp = 0;
470
471   const struct read_matrix_params *rmp = get_read_matrix_params (mf);
472   int x0 = rmp->x0;
473   int x1 = rmp->x1 < mf->n_cvars ? rmp->x1 : mf->n_cvars - 1;
474   int y0 = rmp->dy0;
475   int y1 = (int) mf->n_cvars + rmp->dy1;
476   for (int y = y0; y < y1; y++)
477     {
478       assert (x0 >= 0 && x0 < mf->n_cvars);
479       assert (x1 >= 0 && x1 < mf->n_cvars);
480       assert (x1 >= x0);
481
482       ms2->rp[ms2->n_rp++] = (struct row_sched) {
483         .y = y, .x0 = x0, .x1 = x1 + 1
484       };
485
486       x0 += rmp->dx0;
487       x1 += rmp->dx1;
488     }
489 }
490
491 static bool
492 read_id_columns (const struct matrix_format *mf,
493                  struct substring *p, struct dfm_reader *r,
494                  double *d, enum rowtype *rt)
495 {
496   for (size_t i = 0; mf->input_vars[i] != mf->cvars[0]; i++)
497     if (!(mf->input_vars[i] == mf->rowtype
498           ? next_rowtype (p, r, rt)
499           : next_number (p, r, &d[i])))
500       return false;
501   return true;
502 }
503
504 static bool
505 equal_id_columns (const struct matrix_format *mf,
506                   const double *a, const double *b)
507 {
508   for (size_t i = 0; mf->input_vars[i] != mf->cvars[0]; i++)
509     if (mf->input_vars[i] != mf->rowtype && a[i] != b[i])
510       return false;
511   return true;
512 }
513
514 static bool
515 equal_split_columns (const struct matrix_format *mf,
516                      const double *a, const double *b)
517 {
518   for (size_t i = 0; i < mf->n_svars; i++)
519     {
520       size_t idx = mf->svar_indexes[i];
521       if (a[idx] != b[idx])
522         return false;
523     }
524   return true;
525 }
526
527 static bool
528 is_pooled (const struct matrix_format *mf, const double *d)
529 {
530   for (size_t i = 0; i < mf->n_fvars; i++)
531     if (d[mf->fvar_indexes[i]] != SYSMIS)
532       return false;
533   return true;
534 }
535
536 static void
537 matrix_sched_init (const struct matrix_format *mf, enum rowtype rt,
538                    gsl_matrix *m)
539 {
540   int n_dims = rowtype_dimensions (rt);
541   const struct matrix_sched *ms = &mf->ms[n_dims];
542   double diagonal = n_dims < 2 || rt != C_CORR ? SYSMIS : 1.0;
543   for (size_t y = 0; y < ms->nr; y++)
544     for (size_t x = 0; x < ms->nc; x++)
545       gsl_matrix_set (m, y, x, y == x ? diagonal : SYSMIS);
546 }
547
548 static void
549 matrix_sched_output (const struct matrix_format *mf, enum rowtype rt,
550                      gsl_matrix *m, const double *d, int split_num,
551                      struct casewriter *w)
552 {
553   int n_dims = rowtype_dimensions (rt);
554   const struct matrix_sched *ms = &mf->ms[n_dims];
555
556   if (rt == C_N_SCALAR)
557     {
558       for (size_t x = 1; x < mf->n_cvars; x++)
559         gsl_matrix_set (m, 0, x, gsl_matrix_get (m, 0, 0));
560       rt = C_N;
561     }
562
563   for (int y = 0; y < ms->nr; y++)
564     {
565       struct ccase *c = case_create (casewriter_get_proto (w));
566       for (size_t i = 0; mf->input_vars[i] != mf->cvars[0]; i++)
567         if (mf->input_vars[i] != mf->rowtype)
568           *case_num_rw (c, mf->input_vars[i]) = d[i];
569       if (mf->n_svars && !mf->svar_indexes)
570         *case_num_rw (c, mf->svars[0]) = split_num;
571       set_string (c, mf->rowtype, rowtype_name (rt));
572       const char *varname = n_dims == 2 ? var_get_name (mf->cvars[y]) : "";
573       set_string (c, mf->varname, ss_cstr (varname));
574       for (int x = 0; x < mf->n_cvars; x++)
575         *case_num_rw (c, mf->cvars[x]) = gsl_matrix_get (m, y, x);
576       casewriter_write (w, c);
577     }
578 }
579
580 static void
581 matrix_sched_output_n (const struct matrix_format *mf, double n,
582                        gsl_matrix *m, const double *d, int split_num,
583                        struct casewriter *w)
584 {
585   gsl_matrix_set (m, 0, 0, n);
586   matrix_sched_output (mf, C_N_SCALAR, m, d, split_num, w);
587 }
588
589 static void
590 check_eol (const struct matrix_format *mf, struct substring *p,
591            struct dfm_reader *r)
592 {
593   if (!mf->span)
594     {
595       ss_ltrim (p, ss_cstr (CC_SPACES ","));
596       if (p->length)
597         {
598           parse_error (r, p, _("Extraneous data expecting end of line."));
599           p->length = 0;
600         }
601     }
602 }
603
604 static void
605 parse_data_with_rowtype (const struct matrix_format *mf,
606                          struct dfm_reader *r, struct casewriter *w)
607 {
608   if (dfm_eof (r))
609     return;
610   struct substring p = dfm_get_record (r);
611
612   double *prev = NULL;
613   gsl_matrix *m = gsl_matrix_alloc (mf->n_cvars, mf->n_cvars);
614
615   double *d = xnmalloc (mf->n_input_vars, sizeof *d);
616   enum rowtype rt;
617
618   double *d_next = xnmalloc (mf->n_input_vars, sizeof *d_next);
619
620   if (!read_id_columns (mf, &p, r, d, &rt))
621     goto exit;
622   for (;;)
623     {
624       /* If this has rowtype N but there was an N subcommand, then the
625          subcommand takes precedence, so we will suppress outputting this
626          record.  We still need to parse it, though, so we can't skip other
627          work. */
628       bool suppress_output = mf->n >= 0 && (rt == C_N || rt == C_N_SCALAR);
629       if (suppress_output)
630         parse_error (r, NULL, _("N record is not allowed with N subcommand.  "
631                                 "Ignoring N record."));
632
633       /* If there's an N subcommand, and this is a new split, then output an N
634          record. */
635       if (mf->n >= 0 && (!prev || !equal_split_columns (mf, prev, d)))
636         {
637           matrix_sched_output_n (mf, mf->n, m, d, 0, w);
638
639           if (!prev)
640             prev = xnmalloc (mf->n_input_vars, sizeof *prev);
641           memcpy (prev, d, mf->n_input_vars * sizeof *prev);
642         }
643
644       /* Usually users don't provide the CONTENTS subcommand with ROWTYPE_, but
645          if they did then warn if ROWTYPE_ is an unexpected type. */
646       if (mf->factor_rowtype_mask || mf->pooled_rowtype_mask)
647         {
648           const char *name = rowtype_name (rt).string;
649           if (is_pooled (mf, d))
650             {
651               if (!((1u << rt) & mf->pooled_rowtype_mask))
652                 parse_warning (r, NULL, _("Data contains pooled row type %s not "
653                                           "included in CONTENTS."), name);
654             }
655           else
656             {
657               if (!((1u << rt) & mf->factor_rowtype_mask))
658                 parse_warning (r, NULL, _("Data contains with-factors row type "
659                                           "%s not included in CONTENTS."), name);
660             }
661         }
662
663       /* Initialize the matrix to be filled-in. */
664       int n_dims = rowtype_dimensions (rt);
665       const struct matrix_sched *ms = &mf->ms[n_dims];
666       matrix_sched_init (mf, rt, m);
667
668       enum rowtype rt_next;
669       bool eof;
670
671       size_t n_rows;
672       for (n_rows = 1; ; n_rows++)
673         {
674           if (n_rows <= ms->n_rp)
675             {
676               const struct row_sched *rs = &ms->rp[n_rows - 1];
677               size_t y = rs->y;
678               for (size_t x = rs->x0; x < rs->x1; x++)
679                 {
680                   double e;
681                   if (!next_number (&p, r, &e))
682                     goto exit;
683                   gsl_matrix_set (m, y, x, e);
684                   if (n_dims == 2 && mf->triangle != FULL)
685                     gsl_matrix_set (m, x, y, e);
686                 }
687               check_eol (mf, &p, r);
688             }
689           else
690             {
691               /* Suppress bad input data.  We'll issue an error later. */
692               p.length = 0;
693             }
694
695           eof = (!more_tokens (&p, r)
696                  || !read_id_columns (mf, &p, r, d_next, &rt_next));
697           if (eof)
698             break;
699
700           if (!equal_id_columns (mf, d, d_next) || rt_next != rt)
701             break;
702         }
703       if (!suppress_output)
704         matrix_sched_output (mf, rt, m, d, 0, w);
705
706       if (n_rows != ms->n_rp)
707         parse_error (r, NULL,
708                      _("Matrix %s had %zu rows but %zu rows were expected."),
709                      rowtype_name (rt).string, n_rows, ms->n_rp);
710       if (eof)
711         break;
712
713       double *d_tmp = d;
714       d = d_next;
715       d_next = d_tmp;
716
717       rt = rt_next;
718     }
719
720 exit:
721   free (prev);
722   gsl_matrix_free (m);
723   free (d);
724   free (d_next);
725 }
726
727 static void
728 parse_matrix_without_rowtype (const struct matrix_format *mf,
729                               struct substring *p, struct dfm_reader *r,
730                               gsl_matrix *m, enum rowtype rowtype, bool pooled,
731                               int split_num, struct casewriter *w)
732 {
733   int n_dims = rowtype_dimensions (rowtype);
734   const struct matrix_sched *ms = &mf->ms[n_dims];
735
736   double *d = xnmalloc (mf->n_input_vars, sizeof *d);
737   matrix_sched_init (mf, rowtype, m);
738   for (size_t i = 0; i < ms->n_rp; i++)
739     {
740       int y = ms->rp[i].y;
741       int k = 0;
742       int h = 0;
743       for (size_t j = 0; j < mf->n_input_vars; j++)
744         {
745           const struct variable *iv = mf->input_vars[j];
746           if (k < mf->n_cvars && iv == mf->cvars[k])
747             {
748               if (k < ms->rp[i].x1 - ms->rp[i].x0)
749                 {
750                   double e;
751                   if (!next_number (p, r, &e))
752                     goto exit;
753
754                   int x = k + ms->rp[i].x0;
755                   gsl_matrix_set (m, y, x, e);
756                   if (n_dims == 2 && mf->triangle != FULL)
757                     gsl_matrix_set (m, x, y, e);
758                 }
759               k++;
760               continue;
761             }
762           if (h < mf->n_fvars && iv == mf->fvars[h])
763             {
764               h++;
765               if (pooled)
766                 {
767                   d[j] = SYSMIS;
768                   continue;
769                 }
770             }
771
772           double e;
773           if (!next_number (p, r, &e))
774             goto exit;
775           d[j] = e;
776         }
777       check_eol (mf, p, r);
778     }
779
780   matrix_sched_output (mf, rowtype, m, d, split_num, w);
781 exit:
782   free (d);
783 }
784
785 static void
786 parse_data_without_rowtype (const struct matrix_format *mf,
787                             struct dfm_reader *r, struct casewriter *w)
788 {
789   if (dfm_eof (r))
790     return;
791   struct substring p = dfm_get_record (r);
792
793   gsl_matrix *m = gsl_matrix_alloc (mf->n_cvars, mf->n_cvars);
794
795   int split_num = 1;
796   do
797     {
798       for (size_t i = 0; i < mf->n_contents; )
799         {
800           size_t j = i;
801           if (mf->contents[i].open)
802             while (!mf->contents[j].close)
803               j++;
804
805           if (mf->contents[i].open)
806             {
807               for (size_t k = 0; k < mf->cells; k++)
808                 for (size_t h = i; h <= j; h++)
809                   parse_matrix_without_rowtype (mf, &p, r, m,
810                                                 mf->contents[h].rowtype, false,
811                                                 split_num, w);
812             }
813           else
814             parse_matrix_without_rowtype (mf, &p, r, m, mf->contents[i].rowtype,
815                                           true, split_num, w);
816           i = j + 1;
817         }
818
819       split_num++;
820     }
821   while (more_tokens (&p, r));
822
823   gsl_matrix_free (m);
824 }
825
826 /* Parses VARIABLES=varnames for MATRIX DATA and returns a dictionary with the
827    named variables in it. */
828 static struct dictionary *
829 parse_matrix_data_variables (struct lexer *lexer)
830 {
831   if (!lex_force_match_id (lexer, "VARIABLES"))
832     return NULL;
833   lex_match (lexer, T_EQUALS);
834
835   struct dictionary *dict = dict_create (get_default_encoding ());
836
837   size_t n_names = 0;
838   char **names = NULL;
839   if (!parse_DATA_LIST_vars (lexer, dict, &names, &n_names, PV_NO_DUPLICATE))
840     {
841       dict_unref (dict);
842       return NULL;
843     }
844
845   for (size_t i = 0; i < n_names; i++)
846     if (!strcasecmp (names[i], "ROWTYPE_"))
847       dict_create_var_assert (dict, "ROWTYPE_", 8);
848     else
849       dict_create_var_assert (dict, names[i], 0);
850
851   for (size_t i = 0; i < n_names; ++i)
852     free (names[i]);
853   free (names);
854
855   if (dict_lookup_var (dict, "VARNAME_"))
856     {
857       msg (SE, _("VARIABLES may not include VARNAME_."));
858       dict_unref (dict);
859       return NULL;
860     }
861   return dict;
862 }
863
864 static bool
865 parse_matrix_data_subvars (struct lexer *lexer, struct dictionary *dict,
866                            bool *taken_vars,
867                            struct variable ***vars, size_t **indexes,
868                            size_t *n_vars)
869 {
870   if (!parse_variables (lexer, dict, vars, n_vars, 0))
871     return false;
872
873   *indexes = xnmalloc (*n_vars, sizeof **indexes);
874   for (size_t i = 0; i < *n_vars; i++)
875     {
876       struct variable *v = (*vars)[i];
877       if (!strcasecmp (var_get_name (v), "ROWTYPE_"))
878         {
879           msg (SE, _("ROWTYPE_ is not allowed on SPLIT or FACTORS."));
880           goto error;
881         }
882       (*indexes)[i] = var_get_dict_index (v);
883
884       bool *tv = &taken_vars[var_get_dict_index (v)];
885       if (*tv)
886         {
887           msg (SE, _("%s may not appear on both SPLIT and FACTORS."),
888                var_get_name (v));
889           goto error;
890         }
891       *tv = true;
892
893       var_set_both_formats (v, &(struct fmt_spec) { .type = FMT_F, .w = 4 });
894     }
895   return true;
896
897 error:
898   free (*vars);
899   *vars = NULL;
900   *n_vars = 0;
901   free (*indexes);
902   *indexes = NULL;
903   return false;
904 }
905
906 int
907 cmd_matrix_data (struct lexer *lexer, struct dataset *ds)
908 {
909   struct dictionary *dict = parse_matrix_data_variables (lexer);
910   if (!dict)
911     return CMD_FAILURE;
912
913   size_t n_input_vars = dict_get_var_cnt (dict);
914   struct variable **input_vars = xnmalloc (n_input_vars, sizeof *input_vars);
915   for (size_t i = 0; i < n_input_vars; i++)
916     input_vars[i] = dict_get_var (dict, i);
917
918   int varname_width = 8;
919   for (size_t i = 0; i < n_input_vars; i++)
920     {
921       int w = strlen (var_get_name (input_vars[i]));
922       varname_width = MAX (w, varname_width);
923     }
924
925   struct variable *rowtype = dict_lookup_var (dict, "ROWTYPE_");
926   bool input_rowtype = rowtype != NULL;
927   if (!rowtype)
928     rowtype = dict_create_var_assert (dict, "ROWTYPE_", 8);
929
930   struct matrix_format mf = {
931     .input_rowtype = input_rowtype,
932     .input_vars = input_vars,
933     .n_input_vars = n_input_vars,
934
935     .rowtype = rowtype,
936     .varname = dict_create_var_assert (dict, "VARNAME_", varname_width),
937
938     .triangle = LOWER,
939     .diagonal = DIAGONAL,
940     .n = -1,
941     .cells = -1,
942   };
943
944   bool *taken_vars = XCALLOC (n_input_vars, bool);
945   if (input_rowtype)
946     taken_vars[var_get_dict_index (rowtype)] = true;
947
948   struct file_handle *fh = NULL;
949   while (lex_token (lexer) != T_ENDCMD)
950     {
951       if (!lex_force_match (lexer, T_SLASH))
952         goto error;
953
954       if (lex_match_id (lexer, "N"))
955         {
956           lex_match (lexer, T_EQUALS);
957
958           if (!lex_force_int_range (lexer, "N", 0, INT_MAX))
959             goto error;
960
961           mf.n = lex_integer (lexer);
962           lex_get (lexer);
963         }
964       else if (lex_match_id (lexer, "FORMAT"))
965         {
966           lex_match (lexer, T_EQUALS);
967
968           while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
969             {
970               if (lex_match_id (lexer, "LIST"))
971                 mf.span = false;
972               else if (lex_match_id (lexer, "FREE"))
973                 mf.span = true;
974               else if (lex_match_id (lexer, "UPPER"))
975                 mf.triangle = UPPER;
976               else if (lex_match_id (lexer, "LOWER"))
977                 mf.triangle = LOWER;
978               else if (lex_match_id (lexer, "FULL"))
979                 mf.triangle = FULL;
980               else if (lex_match_id (lexer, "DIAGONAL"))
981                 mf.diagonal = DIAGONAL;
982               else if (lex_match_id (lexer, "NODIAGONAL"))
983                 mf.diagonal = NO_DIAGONAL;
984               else
985                 {
986                   lex_error (lexer, NULL);
987                   goto error;
988                 }
989             }
990         }
991       else if (lex_match_id (lexer, "FILE"))
992         {
993           lex_match (lexer, T_EQUALS);
994           fh_unref (fh);
995           fh = fh_parse (lexer, FH_REF_FILE | FH_REF_INLINE, NULL);
996           if (!fh)
997             goto error;
998         }
999       else if (!mf.n_svars && lex_match_id (lexer, "SPLIT"))
1000         {
1001           lex_match (lexer, T_EQUALS);
1002           if (!mf.input_rowtype
1003               && lex_token (lexer) == T_ID
1004               && !dict_lookup_var (dict, lex_tokcstr (lexer)))
1005             {
1006               mf.svars = xmalloc (sizeof *mf.svars);
1007               mf.svars[0] = dict_create_var_assert (dict, lex_tokcstr (lexer),
1008                                                     0);
1009               var_set_both_formats (
1010                 mf.svars[0], &(struct fmt_spec) { .type = FMT_F, .w = 4 });
1011               mf.n_svars = 1;
1012               lex_get (lexer);
1013             }
1014           else if (!parse_matrix_data_subvars (lexer, dict, taken_vars,
1015                                                &mf.svars, &mf.svar_indexes,
1016                                                &mf.n_svars))
1017             goto error;
1018         }
1019       else if (!mf.n_fvars && lex_match_id (lexer, "FACTORS"))
1020         {
1021           lex_match (lexer, T_EQUALS);
1022           if (!parse_matrix_data_subvars (lexer, dict, taken_vars,
1023                                           &mf.fvars, &mf.fvar_indexes,
1024                                           &mf.n_fvars))
1025             goto error;
1026         }
1027       else if (lex_match_id (lexer, "CELLS"))
1028         {
1029           if (mf.input_rowtype)
1030             msg (SW, _("CELLS is ignored when VARIABLES includes ROWTYPE_"));
1031
1032           lex_match (lexer, T_EQUALS);
1033
1034           if (!lex_force_int_range (lexer, "CELLS", 0, INT_MAX))
1035             goto error;
1036
1037           mf.cells = lex_integer (lexer);
1038           lex_get (lexer);
1039         }
1040       else if (lex_match_id (lexer, "CONTENTS"))
1041         {
1042           lex_match (lexer, T_EQUALS);
1043
1044           size_t allocated_contents = mf.n_contents;
1045           bool in_parens = false;
1046           for (;;)
1047             {
1048               bool open = !in_parens && lex_match (lexer, T_LPAREN);
1049               enum rowtype rt;
1050               if (!rowtype_parse (lexer, &rt))
1051                 {
1052                   if (open || in_parens || (lex_token (lexer) != T_ENDCMD
1053                                             && lex_token (lexer) != T_SLASH))
1054                     {
1055                       lex_error (lexer, _("Row type keyword expected."));
1056                       goto error;
1057                     }
1058                   break;
1059                 }
1060
1061               if (open)
1062                 in_parens = true;
1063
1064               if (in_parens)
1065                 mf.factor_rowtype_mask |= 1u << rt;
1066               else
1067                 mf.pooled_rowtype_mask |= 1u << rt;
1068
1069               bool close = in_parens && lex_match (lexer, T_RPAREN);
1070               if (close)
1071                 in_parens = false;
1072
1073               if (mf.n_contents >= allocated_contents)
1074                 mf.contents = x2nrealloc (mf.contents, &allocated_contents,
1075                                           sizeof *mf.contents);
1076               mf.contents[mf.n_contents++] = (struct content) {
1077                 .open = open, .rowtype = rt, .close = close
1078               };
1079             }
1080         }
1081       else
1082         {
1083           lex_error (lexer, NULL);
1084           goto error;
1085         }
1086     }
1087   if (mf.diagonal == NO_DIAGONAL && mf.triangle == FULL)
1088     {
1089       msg (SE, _("FORMAT=FULL and FORMAT=NODIAGONAL are mutually exclusive."));
1090       goto error;
1091     }
1092   if (!mf.input_rowtype)
1093     {
1094       if (mf.cells < 0)
1095         {
1096           if (mf.n_fvars)
1097             {
1098               msg (SE, _("CELLS is required when factor variables are specified "
1099                          "and VARIABLES does not include ROWTYPE_."));
1100               goto error;
1101             }
1102           mf.cells = 1;
1103         }
1104
1105       if (!mf.n_contents)
1106         {
1107           msg (SW, _("CONTENTS was not specified and VARIABLES does not "
1108                      "include ROWTYPE_.  Assuming CONTENTS=CORR."));
1109
1110           mf.n_contents = 1;
1111           mf.contents = xmalloc (sizeof *mf.contents);
1112           *mf.contents = (struct content) { .rowtype = C_CORR };
1113         }
1114     }
1115   mf.cvars = xmalloc (mf.n_input_vars * sizeof *mf.cvars);
1116   for (size_t i = 0; i < mf.n_input_vars; i++)
1117     if (!taken_vars[i])
1118       {
1119         struct variable *v = input_vars[i];
1120         mf.cvars[mf.n_cvars++] = v;
1121         var_set_both_formats (v, &(struct fmt_spec) { .type = FMT_F, .w = 10,
1122                                                       .d = 4 });
1123       }
1124   if (!mf.n_cvars)
1125     {
1126       msg (SE, _("At least one continuous variable is required."));
1127       goto error;
1128     }
1129   if (mf.input_rowtype)
1130     {
1131       for (size_t i = 0; i < mf.n_cvars; i++)
1132         if (mf.cvars[i] != input_vars[n_input_vars - mf.n_cvars + i])
1133           {
1134             msg (SE, _("VARIABLES includes ROWTYPE_ but the continuous "
1135                        "variables are not the last ones on VARIABLES."));
1136             goto error;
1137           }
1138     }
1139   unsigned int rowtype_mask = mf.pooled_rowtype_mask | mf.factor_rowtype_mask;
1140   if (rowtype_mask & (1u << C_N) && mf.n >= 0)
1141     {
1142       msg (SE, _("Cannot specify N on CONTENTS along with the N subcommand."));
1143       goto error;
1144     }
1145
1146   struct variable **order = xnmalloc (dict_get_var_cnt (dict), sizeof *order);
1147   size_t n_order = 0;
1148   for (size_t i = 0; i < mf.n_svars; i++)
1149     order[n_order++] = mf.svars[i];
1150   order[n_order++] = mf.rowtype;
1151   for (size_t i = 0; i < mf.n_fvars; i++)
1152     order[n_order++] = mf.fvars[i];
1153   order[n_order++] = mf.varname;
1154   for (size_t i = 0; i < mf.n_cvars; i++)
1155     order[n_order++] = mf.cvars[i];
1156   assert (n_order == dict_get_var_cnt (dict));
1157   dict_reorder_vars (dict, order, n_order);
1158   free (order);
1159
1160   dict_set_split_vars (dict, mf.svars, mf.n_svars);
1161
1162   schedule_matrices (&mf);
1163
1164   if (fh == NULL)
1165     fh = fh_inline_file ();
1166
1167   if (lex_end_of_command (lexer) != CMD_SUCCESS)
1168     goto error;
1169
1170   struct dfm_reader *reader = dfm_open_reader (fh, lexer, NULL);
1171   if (reader == NULL)
1172     goto error;
1173
1174   struct casewriter *writer = autopaging_writer_create (dict_get_proto (dict));
1175   if (mf.input_rowtype)
1176     parse_data_with_rowtype (&mf, reader, writer);
1177   else
1178     parse_data_without_rowtype (&mf, reader, writer);
1179   dfm_close_reader (reader);
1180
1181   dataset_set_dict (ds, dict);
1182   dataset_set_source (ds, casewriter_make_reader (writer));
1183
1184   matrix_format_uninit (&mf);
1185   free (taken_vars);
1186   fh_unref (fh);
1187
1188   return CMD_SUCCESS;
1189
1190  error:
1191   matrix_format_uninit (&mf);
1192   free (taken_vars);
1193   dict_unref (dict);
1194   fh_unref (fh);
1195   return CMD_FAILURE;
1196 }