perl-module: Add copyright and licence notices
[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 (val->s, 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 (val->s, 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    make_value_from_scalar (&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    {
421      mv_add_value (&mv, &val[i]);
422      value_destroy (&val[i], var_get_width (var));
423    }
424  var_set_missing_values (var, &mv);
425
426
427 void
428 set_label (var, label)
429  struct variable *var;
430  char *label
431 CODE:
432   var_set_label (var, label);
433
434
435 void
436 clear_value_labels (var)
437  struct variable *var;
438 CODE:
439  var_clear_value_labels (var);
440
441 SV *
442 get_write_format (var)
443  struct variable *var
444 CODE:
445  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
446  const struct fmt_spec *fmt = var_get_write_format (var);
447
448  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
449  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
450  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
451
452  RETVAL = newRV ((SV *) fmthash);
453  OUTPUT:
454 RETVAL
455
456 SV *
457 get_print_format (var)
458  struct variable *var
459 CODE:
460  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
461  const struct fmt_spec *fmt = var_get_print_format (var);
462
463  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
464  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
465  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
466
467  RETVAL = newRV ((SV *) fmthash);
468  OUTPUT:
469 RETVAL
470
471
472 void
473 pxs_set_write_format (var, fmt)
474  struct variable *var
475  output_format fmt
476 CODE:
477  var_set_write_format (var, &fmt);
478
479
480 void
481 pxs_set_print_format (var, fmt)
482  struct variable *var
483  output_format fmt
484 CODE:
485  var_set_print_format (var, &fmt);
486
487 void
488 pxs_set_output_format (var, fmt)
489  struct variable *var
490  output_format fmt
491 CODE:
492  var_set_both_formats (var, &fmt);
493
494
495 int
496 add_value_label (var, key, label)
497  struct variable *var
498  SV *key
499  char *label
500 INIT:
501  SV *errstr = get_sv("PSPP::errstr", TRUE);
502  sv_setpv (errstr, "");
503 CODE:
504  union value the_value;
505  int width = var_get_width (var);
506  int ok;
507
508  value_init (&the_value, width);
509  if ( var_is_numeric (var))
510  {
511   if ( ! looks_like_number (key))
512     {
513       sv_setpv (errstr, "Cannot add label with string key to a numeric variable");
514       value_destroy (&the_value, width);
515       XSRETURN_IV (0);
516     }
517   the_value.f = SvNV (key);
518  }
519  else
520  {
521   value_copy_str_rpad (&the_value, width, SvPV_nolen(key), ' ');
522  }
523  ok = var_add_value_label (var, &the_value, label);
524  value_destroy (&the_value, width);
525  if (!ok)
526  {
527    sv_setpv (errstr, "Something went wrong");
528    XSRETURN_IV (0);
529  }
530  XSRETURN_IV (1);
531
532
533 SV *
534 get_attributes (var)
535  struct variable *var
536 CODE:
537  HV *attrhash = (HV *) sv_2mortal ((SV *) newHV());
538
539  struct attrset *as = var_get_attributes (var);
540
541  if ( as )
542    {
543      struct attrset_iterator iter;
544      struct attribute *attr;
545
546      for (attr = attrset_first (as, &iter);
547           attr;
548           attr = attrset_next (as, &iter))
549        {
550          int i;
551          const char *name = attribute_get_name (attr);
552
553          AV *values = newAV ();
554
555          for (i = 0 ; i < attribute_get_n_values (attr); ++i )
556            {
557              const char *value = attribute_get_value (attr, i);
558              av_push (values, newSVpv (value, 0));
559            }
560
561          hv_store (attrhash, name, strlen (name),
562                    newRV_noinc ((SV*) values), 0);
563        }
564    }
565
566  RETVAL = newRV ((SV *) attrhash);
567  OUTPUT:
568 RETVAL
569
570
571 const char *
572 get_name (var)
573  struct variable * var
574 CODE:
575  RETVAL = var_get_name (var);
576  OUTPUT:
577 RETVAL
578
579
580 const char *
581 get_label (var)
582  struct variable * var
583 CODE:
584  RETVAL = var_get_label (var);
585  OUTPUT:
586 RETVAL
587
588
589 SV *
590 get_value_labels (var)
591  struct variable *var
592 CODE:
593  HV *labelhash = (HV *) sv_2mortal ((SV *) newHV());
594  const struct val_lab *vl;
595  const struct val_labs *labels = var_get_value_labels (var);
596
597  if ( labels )
598    {
599      for (vl = val_labs_first (labels);
600           vl;
601           vl = val_labs_next (labels, vl))
602        {
603          SV *sv = value_to_scalar (&vl->value, var);
604          STRLEN len;
605          const char *s = SvPV (sv, len);
606          hv_store (labelhash, s, len, newSVpv (val_lab_get_label (vl), 0), 0);
607        }
608    }
609
610  RETVAL = newRV ((SV *) labelhash);
611  OUTPUT:
612 RETVAL
613
614
615
616 MODULE = PSPP           PACKAGE = PSPP::Sysfile
617
618
619 struct syswriter_info *
620 pxs_create_sysfile (name, dict, opts_hr)
621  char *name
622  struct pspp_dict *dict;
623  SV *opts_hr
624 INIT:
625  SV *dict_sv = ST(1);
626  struct sfm_write_options opts;
627  if (!SvROK (opts_hr))
628   {
629     opts = sfm_writer_default_options ();
630   }
631  else
632   {
633     HV *opt_h = (HV *) SvRV (opts_hr);
634     SV** readonly = hv_fetch(opt_h, "readonly", 8, 0);
635     SV** compress = hv_fetch(opt_h, "compress", 8, 0);
636     SV** version = hv_fetch(opt_h, "version", 7, 0);
637
638     opts.create_writeable = readonly ? ! SvIV (*readonly) : true;
639     opts.compression = (compress && SvIV (*compress)
640                         ? ANY_COMP_SIMPLE
641                         : ANY_COMP_NONE);
642     opts.version = version ? SvIV (*version) : 3 ;
643   }
644 CODE:
645  struct file_handle *fh =
646    fh_create_file (NULL, name, "UTF-8", fh_default_properties () );
647  struct syswriter_info *swi = xmalloc (sizeof (*swi));
648  swi->writer = sfm_open_writer (fh, dict->dict, opts);
649  swi->dict = dict;
650  swi->opened = true;
651  swi->dict_sv = dict_sv;
652  SvREFCNT_inc (swi->dict_sv);
653  
654  RETVAL = swi;
655  OUTPUT:
656 RETVAL
657
658 int
659 close (swi)
660  struct syswriter_info *swi
661 CODE:
662  RETVAL = sysfile_close (swi);
663 OUTPUT:
664  RETVAL
665
666 void
667 DESTROY (swi)
668  struct syswriter_info *swi
669 CODE:
670  sysfile_close (swi);
671  SvREFCNT_dec (swi->dict_sv);
672  free (swi);
673
674 int
675 append_case (swi, ccase)
676  struct syswriter_info *swi
677  SV *ccase
678 INIT:
679  SV *errstr = get_sv("PSPP::errstr", TRUE);
680  sv_setpv (errstr, "");
681  if ( (!SvROK(ccase)))
682   {
683     XSRETURN_UNDEF;
684   }
685 CODE:
686  int i = 0;
687  AV *av_case = (AV*) SvRV (ccase);
688
689  const struct variable **vv;
690  size_t nv;
691  struct ccase *c;
692  SV *sv;
693
694  if ( av_len (av_case) >= dict_get_var_cnt (swi->dict->dict))
695    XSRETURN_UNDEF;
696
697  c =  case_create (dict_get_proto (swi->dict->dict));
698
699  dict_get_vars (swi->dict->dict, &vv, &nv,
700                 1u << DC_ORDINARY | 1u << DC_SYSTEM);
701
702  for (sv = av_shift (av_case); SvOK (sv);  sv = av_shift (av_case))
703  {
704     const struct variable *v = vv[i++];
705     const struct fmt_spec *ifmt = find_input_format (swi->dict, v);
706
707     /* If an input format has been set, then use it.
708        Otherwise just convert the raw value.
709     */
710     if ( ifmt )
711       {
712         struct substring ss = ss_cstr (SvPV_nolen (sv));
713         char *error;
714         bool ok;
715
716         error = data_in (ss, SvUTF8(sv) ? UTF8: "iso-8859-1", ifmt->type,
717                          case_data_rw (c, v), var_get_width (v),
718                          dict_get_encoding (swi->dict->dict));
719         ok = error == NULL;
720         free (error);
721
722         if ( !ok )
723           {
724             RETVAL = 0;
725             goto finish;
726           }
727       }
728     else
729       {
730         scalar_to_value (case_data_rw (c, v), sv, v);
731       }
732  }
733
734  /* The remaining variables must be sysmis or blank string */
735  while (i < dict_get_var_cnt (swi->dict->dict))
736  {
737    const struct variable *v = vv[i++];
738    union value *val = case_data_rw (c, v);
739    value_set_missing (val, var_get_width (v));
740  }
741  casewriter_write (swi->writer, c);
742  RETVAL = 1;
743  finish:
744  free (vv);
745 OUTPUT:
746  RETVAL
747
748
749 \f
750
751 MODULE = PSPP           PACKAGE = PSPP::Reader
752
753 struct sysreader_info *
754 pxs_open_sysfile (name)
755  char * name
756 CODE:
757  struct sysreader_info *sri = NULL;
758  struct file_handle *fh =
759    fh_create_file (NULL, name, "UTF-8", fh_default_properties () );
760  struct dictionary *dict;
761
762  sri = xmalloc (sizeof (*sri));
763  sri->reader = any_reader_open_and_decode (fh, NULL, &dict, &sri->opts);
764  if (sri->reader)
765    sri->dict = create_pspp_dict (dict);
766  else
767    {
768      free (sri);
769      sri = NULL;
770    }
771
772  RETVAL = sri;
773  OUTPUT:
774 RETVAL
775
776
777 struct pspp_dict *
778 pxs_get_dict (reader)
779  struct sysreader_info *reader;
780 CODE:
781  RETVAL = reader->dict;
782  OUTPUT:
783 RETVAL
784
785 SV *
786 get_case_cnt (sfr)
787  struct sysreader_info *sfr;
788 CODE:
789  SV *ret;
790  casenumber n = casereader_get_case_cnt (sfr->reader);
791  if (n == CASENUMBER_MAX)
792   ret = &PL_sv_undef;
793  else 
794   ret = newSViv (n);
795  RETVAL = ret;
796  OUTPUT:
797 RETVAL
798
799
800
801 void
802 get_next_case (sfr)
803  struct sysreader_info *sfr;
804 PPCODE:
805  struct ccase *c;
806
807  if ((c = casereader_read (sfr->reader)) != NULL)
808  {
809   int v;
810
811   EXTEND (SP, dict_get_var_cnt (sfr->dict->dict));
812   for (v = 0; v < dict_get_var_cnt (sfr->dict->dict); ++v )
813     {
814       const struct variable *var = dict_get_var (sfr->dict->dict, v);
815       const union value *val = case_data (c, var);
816
817       PUSHs (sv_2mortal (value_to_scalar (val, var)));
818     }
819
820   case_unref (c);
821  }