Add support for reading and writing SPV files.
[pspp] / perl-module / PSPP.xs
1 /* PSPP - computes sample statistics.
2    Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    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, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19
20 #undef VERSION
21 #include <config.h>
22
23 /* The Gnulib "strftime" module defines my_strftime in <config.h> for use by
24    gl/strftime.c.  Perl also defines my_strftime in embed.h for some other
25    purpose.  The former definition doesn't matter in this file, so suppress it
26    to avoid a compiler warning. */
27 #undef my_strftime
28
29 #include "EXTERN.h"
30 #include "perl.h"
31 #include "XSUB.h"
32
33 #include "ppport.h"
34
35 #include "minmax.h"
36 #include <libpspp/hmap.h>
37 #include <libpspp/hash-functions.h>
38 #include <libpspp/message.h>
39 #include <libpspp/version.h>
40 #include <libpspp/i18n.h>
41 #include <gl/xalloc.h>
42 #include <data/dictionary.h>
43 #include <data/case.h>
44 #include <data/casereader.h>
45 #include <data/casewriter.h>
46 #include <data/variable.h>
47 #include <data/attributes.h>
48 #include <data/file-handle-def.h>
49 #include <data/identifier.h>
50 #include <data/settings.h>
51 #include <data/sys-file-writer.h>
52 #include <data/value.h>
53 #include <data/vardict.h>
54 #include <data/value-labels.h>
55 #include <data/format.h>
56 #include <data/data-in.h>
57 #include <data/data-out.h>
58 #include <string.h>
59
60 typedef struct fmt_spec input_format ;
61 typedef struct fmt_spec output_format ;
62
63
64 /*  A thin wrapper around sfm_writer */
65 struct syswriter_info
66 {
67   bool opened;
68
69   /* A pointer to the writer. The writer is owned by the struct */
70   struct casewriter *writer;
71
72   /* A pointer to the dictionary. Owned externally */
73   const struct pspp_dict *dict;
74
75   /* The scalar containing the dictionary */
76   SV *dict_sv;
77 };
78
79
80 /*  A thin wrapper around sfm_reader */
81 struct sysreader_info
82 {
83   struct any_read_info opts;
84
85   /* A pointer to the reader. The reader is owned by the struct */
86   struct casereader *reader;
87
88   /* A pointer to the dictionary. */
89   struct pspp_dict *dict;
90 };
91
92
93 struct input_format {
94   struct hmap_node hmap_node;   /* In struct pspp_dict's input_formats map. */
95   const struct variable *var;
96   struct fmt_spec input_format;
97 };
98
99 /* A thin wrapper around struct dictionary.*/
100 struct pspp_dict {
101   struct dictionary *dict;
102   struct hmap input_formats;    /* Contains struct input_format. */
103 };
104
105
106 /*  A message handler which writes messages to PSPP::errstr */
107 static void
108 message_handler (const struct msg *m, void *aux)
109 {
110  SV *errstr = get_sv("PSPP::errstr", TRUE);
111  sv_setpv (errstr, m->text);
112 }
113
114 static int
115 sysfile_close (struct syswriter_info *swi)
116 {
117   int retval ;
118   if ( ! swi->opened )
119     return 0;
120
121   retval = casewriter_destroy (swi->writer);
122   if (retval > 0 )
123     swi->opened = false;
124
125   return retval;
126 }
127
128 static void
129 scalar_to_value (union value *val, SV *scalar, const struct variable *var)
130 {
131   if ( var_is_numeric (var))
132     {
133         if ( SvNOK (scalar) || SvIOK (scalar) )
134            val->f = SvNV (scalar);
135         else
136            val->f = SYSMIS;
137     }
138   else
139     {
140         STRLEN len;
141         const char *p = SvPV (scalar, len);
142         int width = var_get_width (var);
143         value_set_missing (val, width);
144         memcpy (value_str_rw (val, width), p, len);
145     }
146 }
147
148
149 static SV *
150 value_to_scalar (const union value *val, const struct variable *var)
151 {
152   if ( var_is_numeric (var))
153     {
154       if ( var_is_value_missing (var, val, MV_SYSTEM))
155         return newSVpvn ("", 0);
156
157       return newSVnv (val->f);
158     }
159   else
160     {
161       int width = var_get_width (var);
162       return newSVpvn (value_str (val, width), width);
163     }
164 }
165
166
167 static void
168 make_value_from_scalar (union value *uv, SV *val, const struct variable *var)
169 {
170  value_init (uv, var_get_width (var));
171  scalar_to_value (uv, val, var);
172 }
173
174 static struct pspp_dict *
175 create_pspp_dict (struct dictionary *dict)
176 {
177   struct pspp_dict *pspp_dict = xmalloc (sizeof *pspp_dict);
178   pspp_dict->dict = dict;
179   hmap_init (&pspp_dict->input_formats);
180   return pspp_dict;
181 }
182
183 static const struct fmt_spec *
184 find_input_format (const struct pspp_dict *dict, const struct variable *var)
185 {
186   struct input_format *input_format;
187
188   HMAP_FOR_EACH_IN_BUCKET (input_format, struct input_format, hmap_node,
189                            hash_pointer (var, 0), &dict->input_formats)
190     if (input_format->var == var)
191       return &input_format->input_format;
192
193   return NULL;
194 }
195
196
197 MODULE = PSPP
198
199 MODULE = PSPP           PACKAGE = PSPP
200
201 PROTOTYPES: ENABLE
202
203 void
204 onBoot (ver)
205  const char *ver
206 CODE:
207  /* Check that the version is correct up to the length of 'ver'.
208     This allows PSPP autobuilders to add a "-build#" suffix to the
209     PSPP version without causing failures here. */
210  assert (0 == strncmp (ver, bare_version, strlen (ver)));
211
212  i18n_init ();
213  msg_set_handler (message_handler, NULL);
214  settings_init ();
215  fh_init ();
216
217 SV *
218 format_value (val, var)
219  SV *val
220  struct variable *var
221 CODE:
222  SV *ret;
223  const struct fmt_spec *fmt = var_get_print_format (var);
224  union value uv;
225  char *s;
226  make_value_from_scalar (&uv, val, var);
227  s = data_out (&uv, var_get_encoding (var), fmt);
228  value_destroy (&uv, var_get_width (var));
229  ret = newSVpv (s, fmt->w);
230  free (s);
231  RETVAL = ret;
232  OUTPUT:
233 RETVAL
234
235
236 int
237 value_is_missing (val, var)
238  SV *val
239  struct variable *var
240 CODE:
241  union value uv;
242  int ret;
243  make_value_from_scalar (&uv, val, var);
244  ret = var_is_value_missing (var, &uv, MV_ANY);
245  value_destroy (&uv, var_get_width (var));
246  RETVAL = ret;
247  OUTPUT:
248 RETVAL
249
250
251
252 MODULE = PSPP           PACKAGE = PSPP::Dict
253
254 struct pspp_dict *
255 pxs_dict_new()
256 CODE:
257  RETVAL = create_pspp_dict (dict_create ("UTF-8"));
258 OUTPUT:
259  RETVAL
260
261
262 void
263 DESTROY (dict)
264  struct pspp_dict *dict
265 CODE:
266  if (dict != NULL)
267    {
268      struct input_format *input_format, *next_input_format;
269
270      HMAP_FOR_EACH_SAFE (input_format, next_input_format,
271                          struct input_format, hmap_node, &dict->input_formats)
272        {
273          hmap_delete (&dict->input_formats, &input_format->hmap_node);
274          free (input_format);
275        }
276      hmap_destroy (&dict->input_formats);
277      dict_unref (dict->dict);
278      free (dict);
279    }
280
281 int
282 get_var_cnt (dict)
283  struct pspp_dict *dict
284 CODE:
285  RETVAL = dict_get_var_cnt (dict->dict);
286 OUTPUT:
287 RETVAL
288
289 void
290 set_label (dict, label)
291  struct pspp_dict *dict
292  char *label
293 CODE:
294  dict_set_label (dict->dict, label);
295
296 void
297 set_documents (dict, docs)
298  struct pspp_dict *dict
299  char *docs
300 CODE:
301  dict_set_documents_string (dict->dict, docs);
302
303
304 void
305 add_document (dict, doc)
306  struct pspp_dict *dict
307  char *doc
308 CODE:
309  dict_add_document_line (dict->dict, doc, false);
310
311
312 void
313 clear_documents (dict)
314  struct pspp_dict *dict
315 CODE:
316  dict_clear_documents (dict->dict);
317
318
319 void
320 set_weight (dict, var)
321  struct pspp_dict *dict
322  struct variable *var
323 CODE:
324  dict_set_weight (dict->dict, var);
325
326
327 struct variable *
328 pxs_get_variable (dict, idx)
329  struct pspp_dict *dict
330  SV *idx
331 INIT:
332  SV *errstr = get_sv("PSPP::errstr", TRUE);
333  sv_setpv (errstr, "");
334  if ( SvIV (idx) >= dict_get_var_cnt (dict->dict))
335   {
336     sv_setpv (errstr, "The dictionary doesn't have that many variables.");
337     XSRETURN_UNDEF;
338   }
339 CODE:
340  RETVAL = dict_get_var (dict->dict, SvIV (idx));
341  OUTPUT:
342 RETVAL
343
344
345 struct variable *
346 pxs_get_var_by_name (dict, name)
347  struct pspp_dict *dict
348  const char *name
349 INIT:
350  SV *errstr = get_sv("PSPP::errstr", TRUE);
351  sv_setpv (errstr, "");
352 CODE:
353  struct variable *var = dict_lookup_var (dict->dict, name);
354  if ( ! var )
355       sv_setpv (errstr, "No such variable.");
356  RETVAL = var;
357  OUTPUT:
358 RETVAL
359
360
361 MODULE = PSPP           PACKAGE = PSPP::Var
362
363
364 struct variable *
365 pxs_dict_create_var (dict, name, ip_fmt)
366  struct pspp_dict * dict
367  char *name
368  input_format ip_fmt
369 INIT:
370  SV *errstr = get_sv("PSPP::errstr", TRUE);
371  sv_setpv (errstr, "");
372  if ( ! id_is_plausible (name, false))
373   {
374     sv_setpv (errstr, "The variable name is not valid.");
375     XSRETURN_UNDEF;
376   }
377 CODE:
378  struct fmt_spec op_fmt;
379  struct input_format *input_format;
380
381  struct variable *v;
382  op_fmt = fmt_for_output_from_input (&ip_fmt);
383  v = dict_create_var (dict->dict, name,
384         fmt_is_string (op_fmt.type) ? op_fmt.w : 0);
385  if ( NULL == v )
386   {
387     sv_setpv (errstr, "The variable could not be created (probably already exists).");
388     XSRETURN_UNDEF;
389   }
390  var_set_both_formats (v, &op_fmt);
391
392  input_format = xmalloc (sizeof *input_format);
393  input_format->var = v;
394  input_format->input_format = ip_fmt;
395  hmap_insert (&dict->input_formats, &input_format->hmap_node,
396               hash_pointer (v, 0));
397
398  RETVAL = v;
399 OUTPUT:
400  RETVAL
401
402
403 int
404 set_missing_values (var, v1, ...)
405  struct variable *var;
406  SV *v1;
407 INIT:
408  int i;
409  union value val[3];
410
411  if ( items > 4 )
412   croak ("No more than 3 missing values are permitted");
413
414  for (i = 0; i < items - 1; ++i)
415    scalar_to_value (&val[i], ST(i+1), var);
416 CODE:
417  struct missing_values mv;
418  mv_init (&mv, var_get_width (var));
419  for (i = 0 ; i < items - 1; ++i )
420    mv_add_value (&mv, &val[i]);
421  var_set_missing_values (var, &mv);
422
423
424 void
425 set_label (var, label)
426  struct variable *var;
427  char *label
428 CODE:
429   var_set_label (var, label);
430
431
432 void
433 clear_value_labels (var)
434  struct variable *var;
435 CODE:
436  var_clear_value_labels (var);
437
438 SV *
439 get_write_format (var)
440  struct variable *var
441 CODE:
442  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
443  const struct fmt_spec *fmt = var_get_write_format (var);
444
445  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
446  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
447  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
448
449  RETVAL = newRV ((SV *) fmthash);
450  OUTPUT:
451 RETVAL
452
453 SV *
454 get_print_format (var)
455  struct variable *var
456 CODE:
457  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
458  const struct fmt_spec *fmt = var_get_print_format (var);
459
460  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
461  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
462  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
463
464  RETVAL = newRV ((SV *) fmthash);
465  OUTPUT:
466 RETVAL
467
468
469 void
470 pxs_set_write_format (var, fmt)
471  struct variable *var
472  output_format fmt
473 CODE:
474  var_set_write_format (var, &fmt);
475
476
477 void
478 pxs_set_print_format (var, fmt)
479  struct variable *var
480  output_format fmt
481 CODE:
482  var_set_print_format (var, &fmt);
483
484 void
485 pxs_set_output_format (var, fmt)
486  struct variable *var
487  output_format fmt
488 CODE:
489  var_set_both_formats (var, &fmt);
490
491
492 int
493 add_value_label (var, key, label)
494  struct variable *var
495  SV *key
496  char *label
497 INIT:
498  SV *errstr = get_sv("PSPP::errstr", TRUE);
499  sv_setpv (errstr, "");
500 CODE:
501  union value the_value;
502  int width = var_get_width (var);
503  int ok;
504
505  value_init (&the_value, width);
506  if ( var_is_numeric (var))
507  {
508   if ( ! looks_like_number (key))
509     {
510       sv_setpv (errstr, "Cannot add label with string key to a numeric variable");
511       value_destroy (&the_value, width);
512       XSRETURN_IV (0);
513     }
514   the_value.f = SvNV (key);
515  }
516  else
517  {
518   value_copy_str_rpad (&the_value, width, SvPV_nolen(key), ' ');
519  }
520  ok = var_add_value_label (var, &the_value, label);
521  value_destroy (&the_value, width);
522  if (!ok)
523  {
524    sv_setpv (errstr, "Something went wrong");
525    XSRETURN_IV (0);
526  }
527  XSRETURN_IV (1);
528
529
530 SV *
531 get_attributes (var)
532  struct variable *var
533 CODE:
534  HV *attrhash = (HV *) sv_2mortal ((SV *) newHV());
535
536  struct attrset *as = var_get_attributes (var);
537
538  if ( as )
539    {
540      struct attrset_iterator iter;
541      struct attribute *attr;
542
543      for (attr = attrset_first (as, &iter);
544           attr;
545           attr = attrset_next (as, &iter))
546        {
547          int i;
548          const char *name = attribute_get_name (attr);
549
550          AV *values = newAV ();
551
552          for (i = 0 ; i < attribute_get_n_values (attr); ++i )
553            {
554              const char *value = attribute_get_value (attr, i);
555              av_push (values, newSVpv (value, 0));
556            }
557
558          hv_store (attrhash, name, strlen (name),
559                    newRV_noinc ((SV*) values), 0);
560        }
561    }
562
563  RETVAL = newRV ((SV *) attrhash);
564  OUTPUT:
565 RETVAL
566
567
568 const char *
569 get_name (var)
570  struct variable * var
571 CODE:
572  RETVAL = var_get_name (var);
573  OUTPUT:
574 RETVAL
575
576
577 const char *
578 get_label (var)
579  struct variable * var
580 CODE:
581  RETVAL = var_get_label (var);
582  OUTPUT:
583 RETVAL
584
585
586 SV *
587 get_value_labels (var)
588  struct variable *var
589 CODE:
590  HV *labelhash = (HV *) sv_2mortal ((SV *) newHV());
591  const struct val_lab *vl;
592  struct val_labs_iterator *viter = NULL;
593  const struct val_labs *labels = var_get_value_labels (var);
594
595  if ( labels )
596    {
597      for (vl = val_labs_first (labels);
598           vl;
599           vl = val_labs_next (labels, vl))
600        {
601          SV *sv = value_to_scalar (&vl->value, var);
602          STRLEN len;
603          const char *s = SvPV (sv, len);
604          hv_store (labelhash, s, len, newSVpv (val_lab_get_label (vl), 0), 0);
605        }
606    }
607
608  RETVAL = newRV ((SV *) labelhash);
609  OUTPUT:
610 RETVAL
611
612
613
614 MODULE = PSPP           PACKAGE = PSPP::Sysfile
615
616
617 struct syswriter_info *
618 pxs_create_sysfile (name, dict, opts_hr)
619  char *name
620  struct pspp_dict *dict;
621  SV *opts_hr
622 INIT:
623  SV *dict_sv = ST(1);
624  struct sfm_write_options opts;
625  if (!SvROK (opts_hr))
626   {
627     opts = sfm_writer_default_options ();
628   }
629  else
630   {
631     HV *opt_h = (HV *) SvRV (opts_hr);
632     SV** readonly = hv_fetch(opt_h, "readonly", 8, 0);
633     SV** compress = hv_fetch(opt_h, "compress", 8, 0);
634     SV** version = hv_fetch(opt_h, "version", 7, 0);
635
636     opts.create_writeable = readonly ? ! SvIV (*readonly) : true;
637     opts.compression = (compress && SvIV (*compress)
638                         ? ANY_COMP_SIMPLE
639                         : ANY_COMP_NONE);
640     opts.version = version ? SvIV (*version) : 3 ;
641   }
642 CODE:
643  struct file_handle *fh =
644    fh_create_file (NULL, name, "UTF-8", fh_default_properties () );
645  struct syswriter_info *swi = xmalloc (sizeof (*swi));
646  swi->writer = sfm_open_writer (fh, dict->dict, opts);
647  swi->dict = dict;
648  swi->opened = true;
649  swi->dict_sv = dict_sv;
650  SvREFCNT_inc (swi->dict_sv);
651  
652  RETVAL = swi;
653  OUTPUT:
654 RETVAL
655
656 int
657 close (swi)
658  struct syswriter_info *swi
659 CODE:
660  RETVAL = sysfile_close (swi);
661 OUTPUT:
662  RETVAL
663
664 void
665 DESTROY (swi)
666  struct syswriter_info *swi
667 CODE:
668  sysfile_close (swi);
669  SvREFCNT_dec (swi->dict_sv);
670  free (swi);
671
672 int
673 append_case (swi, ccase)
674  struct syswriter_info *swi
675  SV *ccase
676 INIT:
677  SV *errstr = get_sv("PSPP::errstr", TRUE);
678  sv_setpv (errstr, "");
679  if ( (!SvROK(ccase)))
680   {
681     XSRETURN_UNDEF;
682   }
683 CODE:
684  int i = 0;
685  AV *av_case = (AV*) SvRV (ccase);
686
687  const struct variable **vv;
688  size_t nv;
689  struct ccase *c;
690  SV *sv;
691
692  if ( av_len (av_case) >= dict_get_var_cnt (swi->dict->dict))
693    XSRETURN_UNDEF;
694
695  c =  case_create (dict_get_proto (swi->dict->dict));
696
697  dict_get_vars (swi->dict->dict, &vv, &nv,
698                 1u << DC_ORDINARY | 1u << DC_SYSTEM);
699
700  for (sv = av_shift (av_case); SvOK (sv);  sv = av_shift (av_case))
701  {
702     const struct variable *v = vv[i++];
703     const struct fmt_spec *ifmt = find_input_format (swi->dict, v);
704
705     /* If an input format has been set, then use it.
706        Otherwise just convert the raw value.
707     */
708     if ( ifmt )
709       {
710         struct substring ss = ss_cstr (SvPV_nolen (sv));
711         char *error;
712         bool ok;
713
714         error = data_in (ss, SvUTF8(sv) ? UTF8: "iso-8859-1", ifmt->type,
715                          case_data_rw (c, v), var_get_width (v),
716                          dict_get_encoding (swi->dict->dict));
717         ok = error == NULL;
718         free (error);
719
720         if ( !ok )
721           {
722             RETVAL = 0;
723             goto finish;
724           }
725       }
726     else
727       {
728         scalar_to_value (case_data_rw (c, v), sv, v);
729       }
730  }
731
732  /* The remaining variables must be sysmis or blank string */
733  while (i < dict_get_var_cnt (swi->dict->dict))
734  {
735    const struct variable *v = vv[i++];
736    union value *val = case_data_rw (c, v);
737    value_set_missing (val, var_get_width (v));
738  }
739  casewriter_write (swi->writer, c);
740  RETVAL = 1;
741  finish:
742  free (vv);
743 OUTPUT:
744  RETVAL
745
746
747 \f
748
749 MODULE = PSPP           PACKAGE = PSPP::Reader
750
751 struct sysreader_info *
752 pxs_open_sysfile (name)
753  char * name
754 CODE:
755  struct casereader *reader;
756  struct sysreader_info *sri = NULL;
757  struct file_handle *fh =
758    fh_create_file (NULL, name, "UTF-8", fh_default_properties () );
759  struct dictionary *dict;
760
761  sri = xmalloc (sizeof (*sri));
762  sri->reader = any_reader_open_and_decode (fh, NULL, &dict, &sri->opts);
763  if (sri->reader)
764    sri->dict = create_pspp_dict (dict);
765  else
766    {
767      free (sri);
768      sri = NULL;
769    }
770
771  RETVAL = sri;
772  OUTPUT:
773 RETVAL
774
775
776 struct pspp_dict *
777 pxs_get_dict (reader)
778  struct sysreader_info *reader;
779 CODE:
780  RETVAL = reader->dict;
781  OUTPUT:
782 RETVAL
783
784 SV *
785 get_case_cnt (sfr)
786  struct sysreader_info *sfr;
787 CODE:
788  SV *ret;
789  casenumber n = casereader_get_case_cnt (sfr->reader);
790  if (n == CASENUMBER_MAX)
791   ret = &PL_sv_undef;
792  else 
793   ret = newSViv (n);
794  RETVAL = ret;
795  OUTPUT:
796 RETVAL
797
798
799
800 void
801 get_next_case (sfr)
802  struct sysreader_info *sfr;
803 PPCODE:
804  struct ccase *c;
805
806  if ((c = casereader_read (sfr->reader)) != NULL)
807  {
808   int v;
809
810   EXTEND (SP, dict_get_var_cnt (sfr->dict->dict));
811   for (v = 0; v < dict_get_var_cnt (sfr->dict->dict); ++v )
812     {
813       const struct variable *var = dict_get_var (sfr->dict->dict, v);
814       const union value *val = case_data (c, var);
815
816       PUSHs (sv_2mortal (value_to_scalar (val, var)));
817     }
818
819   case_unref (c);
820  }