d10cc34921ecb1bcfa8e64883657d2c999b0588e
[pspp-builds.git] / perl-module / PSPP.xs
1 /* PSPP - computes sample statistics.
2    Copyright (C) 2007, 2008, 2009 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 #include "EXTERN.h"
21 #include "perl.h"
22 #include "XSUB.h"
23
24 #include <config.h>
25
26 #include "ppport.h"
27
28 #include "minmax.h"
29 #include <libpspp/message.h>
30 #include <libpspp/version.h>
31 #include <gl/xalloc.h>
32 #include <data/dictionary.h>
33 #include <data/case.h>
34 #include <data/casereader.h>
35 #include <data/variable.h>
36 #include <data/attributes.h>
37 #include <data/file-handle-def.h>
38 #include <data/sys-file-writer.h>
39 #include <data/sys-file-reader.h>
40 #include <data/value.h>
41 #include <data/vardict.h>
42 #include <data/value-labels.h>
43 #include <data/format.h>
44 #include <data/data-in.h>
45 #include <data/data-out.h>
46 #include <string.h>
47
48 typedef struct fmt_spec input_format ;
49 typedef struct fmt_spec output_format ;
50
51
52 /*  A thin wrapper around sfm_writer */
53 struct sysfile_info
54 {
55   bool opened;
56
57   /* A pointer to the writer. The writer is owned by the struct */
58   struct casewriter *writer;
59
60   /* A pointer to the dictionary. Owned externally */
61   const struct dictionary *dict;
62
63   /* The scalar containing the dictionary */
64   SV *dict_sv;
65 };
66
67
68 /*  A thin wrapper around sfm_reader */
69 struct sysreader_info
70 {
71   struct sfm_read_info opts;
72
73   /* A pointer to the reader. The reader is owned by the struct */
74   struct casereader *reader;
75
76   /* A pointer to the dictionary. */
77   struct dictionary *dict;
78 };
79
80
81
82 /*  A message handler which writes messages to PSPP::errstr */
83 static void
84 message_handler (const struct msg *m)
85 {
86  SV *errstr = get_sv("PSPP::errstr", TRUE);
87  sv_setpv (errstr, m->text);
88 }
89
90 static int
91 sysfile_close (struct sysfile_info *sfi)
92 {
93   int retval ;
94   if ( ! sfi->opened )
95     return 0;
96
97   retval = casewriter_destroy (sfi->writer);
98   if (retval > 0 )
99     sfi->opened = false;
100
101   return retval;
102 }
103
104 static void
105 scalar_to_value (union value *val, SV *scalar, const struct variable *var)
106 {
107   if ( var_is_numeric (var))
108     {
109         if ( SvNOK (scalar) || SvIOK (scalar) )
110            val->f = SvNV (scalar);
111         else
112            val->f = SYSMIS;
113     }
114   else
115     {
116         STRLEN len;
117         const char *p = SvPV (scalar, len);
118         int width = var_get_width (var);
119         value_set_missing (val, width);
120         memcpy (value_str_rw (val, width), p, len);
121     }
122 }
123
124
125 static SV *
126 value_to_scalar (const union value *val, const struct variable *var)
127 {
128   if ( var_is_numeric (var))
129     {
130       if ( var_is_value_missing (var, val, MV_SYSTEM))
131         return newSVpvn ("", 0);
132
133       return newSVnv (val->f);
134     }
135   else
136     {
137       int width = var_get_width (var);
138       return newSVpvn (value_str (val, width), width);
139     }
140 }
141
142
143 static void
144 var_set_input_format (struct variable *v, input_format ip_fmt)
145 {
146   struct fmt_spec *if_copy = malloc (sizeof (*if_copy));
147   memcpy (if_copy, &ip_fmt, sizeof (ip_fmt));
148   var_attach_aux (v, if_copy, var_dtor_free);
149 }
150
151 static void
152 make_value_from_scalar (union value *uv, SV *val, const struct variable *var)
153 {
154  value_init (uv, var_get_width (var));
155  scalar_to_value (uv, val, var);
156 }
157
158
159 MODULE = PSPP
160
161 MODULE = PSPP           PACKAGE = PSPP
162
163 void
164 onBoot (ver)
165  const char *ver
166 CODE:
167  assert (0 == strcmp (ver, bare_version));
168  i18n_init ();
169  msg_init (NULL, message_handler);
170  settings_init (0, 0);
171  fh_init ();
172
173 SV *
174 format_value (val, var)
175  SV *val
176  struct variable *var
177 CODE:
178  SV *ret;
179  const struct fmt_spec *fmt = var_get_print_format (var);
180  const struct dictionary *dict = var_get_vardict (var)->dict;
181  union value uv;
182  char *s;
183  make_value_from_scalar (&uv, val, var);
184  fprintf (stderr, "Encoding is %s\n", dict_get_encoding (dict));
185  s = data_out (&uv, dict_get_encoding (dict), fmt);
186  value_destroy (&uv, var_get_width (var));
187  ret = newSVpv (s, fmt->w);
188  free (s);
189  RETVAL = ret;
190  OUTPUT:
191 RETVAL
192
193
194 int
195 value_is_missing (val, var)
196  SV *val
197  struct variable *var
198 CODE:
199  union value uv;
200  int ret;
201  make_value_from_scalar (&uv, val, var);
202  ret = var_is_value_missing (var, &uv, MV_ANY);
203  value_destroy (&uv, var_get_width (var));
204  RETVAL = ret;
205  OUTPUT:
206 RETVAL
207
208
209
210 MODULE = PSPP           PACKAGE = PSPP::Dict
211
212 struct dictionary *
213 pxs_dict_new()
214 CODE:
215  RETVAL = dict_create ();
216 OUTPUT:
217  RETVAL
218
219
220 void
221 DESTROY (dict)
222  struct dictionary *dict
223 CODE:
224  dict_destroy (dict);
225
226
227 int
228 get_var_cnt (dict)
229  struct dictionary *dict
230 CODE:
231  RETVAL = dict_get_var_cnt (dict);
232 OUTPUT:
233 RETVAL
234
235 void
236 set_label (dict, label)
237  struct dictionary *dict
238  char *label
239 CODE:
240  dict_set_label (dict, label);
241
242 void
243 set_documents (dict, docs)
244  struct dictionary *dict
245  char *docs
246 CODE:
247  dict_set_documents (dict, docs);
248
249
250 void
251 add_document (dict, doc)
252  struct dictionary *dict
253  char *doc
254 CODE:
255  dict_add_document_line (dict, doc);
256
257
258 void
259 clear_documents (dict)
260  struct dictionary *dict
261 CODE:
262  dict_clear_documents (dict);
263
264
265 void
266 set_weight (dict, var)
267  struct dictionary *dict
268  struct variable *var
269 CODE:
270  dict_set_weight (dict, var);
271
272
273 struct variable *
274 pxs_get_variable (dict, idx)
275  struct dictionary *dict
276  SV *idx
277 INIT:
278  SV *errstr = get_sv("PSPP::errstr", TRUE);
279  sv_setpv (errstr, "");
280  if ( SvIV (idx) >= dict_get_var_cnt (dict))
281   {
282     sv_setpv (errstr, "The dictionary doesn't have that many variables.");
283     XSRETURN_UNDEF;
284   }
285 CODE:
286  RETVAL = dict_get_var (dict, SvIV (idx));
287  OUTPUT:
288 RETVAL
289
290
291 struct variable *
292 pxs_get_var_by_name (dict, name)
293  struct dictionary *dict
294  const char *name
295 INIT:
296  SV *errstr = get_sv("PSPP::errstr", TRUE);
297  sv_setpv (errstr, "");
298 CODE:
299  struct variable *var = dict_lookup_var (dict, name);
300  if ( ! var )
301       sv_setpv (errstr, "No such variable.");
302  RETVAL = var;
303  OUTPUT:
304 RETVAL
305
306
307 MODULE = PSPP           PACKAGE = PSPP::Var
308
309
310 struct variable *
311 pxs_dict_create_var (dict, name, ip_fmt)
312  struct dictionary * dict
313  char *name
314  input_format ip_fmt
315 INIT:
316  SV *errstr = get_sv("PSPP::errstr", TRUE);
317  sv_setpv (errstr, "");
318  if ( ! var_is_plausible_name (name, false))
319   {
320     sv_setpv (errstr, "The variable name is not valid.");
321     XSRETURN_UNDEF;
322   }
323 CODE:
324  struct fmt_spec op_fmt;
325
326  struct variable *v;
327  op_fmt = fmt_for_output_from_input (&ip_fmt);
328  v = dict_create_var (dict, name,
329         fmt_is_string (op_fmt.type) ? op_fmt.w : 0);
330  if ( NULL == v )
331   {
332     sv_setpv (errstr, "The variable could not be created (probably already exists).");
333     XSRETURN_UNDEF;
334   }
335  var_set_both_formats (v, &op_fmt);
336  var_set_input_format (v, ip_fmt);
337  RETVAL = v;
338 OUTPUT:
339  RETVAL
340
341
342 int
343 set_missing_values (var, v1, ...)
344  struct variable *var;
345  SV *v1;
346 INIT:
347  int i;
348  union value val[3];
349
350  if ( items > 4 )
351   croak ("No more than 3 missing values are permitted");
352
353  for (i = 0; i < items - 1; ++i)
354    scalar_to_value (&val[i], ST(i+1), var);
355 CODE:
356  struct missing_values mv;
357  mv_init (&mv, var_get_width (var));
358  for (i = 0 ; i < items - 1; ++i )
359    mv_add_value (&mv, &val[i]);
360  var_set_missing_values (var, &mv);
361
362
363 void
364 set_label (var, label)
365  struct variable *var;
366  char *label
367 CODE:
368   var_set_label (var, label);
369
370
371 void
372 clear_value_labels (var)
373  struct variable *var;
374 CODE:
375  var_clear_value_labels (var);
376
377 void
378 pxs_set_write_format (var, fmt)
379  struct variable *var
380  output_format fmt
381 CODE:
382  var_set_write_format (var, &fmt);
383
384
385 void
386 pxs_set_print_format (var, fmt)
387  struct variable *var
388  output_format fmt
389 CODE:
390  var_set_print_format (var, &fmt);
391
392 void
393 pxs_set_output_format (var, fmt)
394  struct variable *var
395  output_format fmt
396 CODE:
397  var_set_both_formats (var, &fmt);
398
399
400 int
401 add_value_label (var, key, label)
402  struct variable *var
403  SV *key
404  char *label
405 INIT:
406  SV *errstr = get_sv("PSPP::errstr", TRUE);
407  sv_setpv (errstr, "");
408 CODE:
409  union value the_value;
410  int width = var_get_width (var);
411  int ok;
412
413  value_init (&the_value, width);
414  if ( var_is_numeric (var))
415  {
416   if ( ! looks_like_number (key))
417     {
418       sv_setpv (errstr, "Cannot add label with string key to a numeric variable");
419       value_destroy (&the_value, width);
420       XSRETURN_IV (0);
421     }
422   the_value.f = SvNV (key);
423  }
424  else
425  {
426   value_copy_str_rpad (&the_value, width, SvPV_nolen(key), ' ');
427  }
428  ok = var_add_value_label (var, &the_value, label);
429  value_destroy (&the_value, width);
430  if (!ok)
431  {
432    sv_setpv (errstr, "Something went wrong");
433    XSRETURN_IV (0);
434  }
435  XSRETURN_IV (1);
436
437
438 SV *
439 get_attributes (var)
440  struct variable *var
441 CODE:
442  HV *attrhash = (HV *) sv_2mortal ((SV *) newHV());
443
444  struct attrset *as = var_get_attributes (var);
445
446  if ( as )
447    {
448      struct attrset_iterator iter;
449      struct attribute *attr;
450
451      for (attr = attrset_first (as, &iter);
452           attr;
453           attr = attrset_next (as, &iter))
454        {
455          int i;
456          const char *name = attribute_get_name (attr);
457
458          AV *values = newAV ();
459
460          for (i = 0 ; i < attribute_get_n_values (attr); ++i )
461            {
462              const char *value = attribute_get_value (attr, i);
463              av_push (values, newSVpv (value, 0));
464            }
465
466          hv_store (attrhash, name, strlen (name),
467                    newRV_noinc ((SV*) values), 0);
468        }
469    }
470
471  RETVAL = newRV ((SV *) attrhash);
472  OUTPUT:
473 RETVAL
474
475
476 const char *
477 get_name (var)
478  struct variable * var
479 CODE:
480  RETVAL = var_get_name (var);
481  OUTPUT:
482 RETVAL
483
484
485 const char *
486 get_label (var)
487  struct variable * var
488 CODE:
489  RETVAL = var_get_label (var);
490  OUTPUT:
491 RETVAL
492
493
494 SV *
495 get_value_labels (var)
496  struct variable *var
497 CODE:
498  HV *labelhash = (HV *) sv_2mortal ((SV *) newHV());
499  const struct val_lab *vl;
500  struct val_labs_iterator *viter = NULL;
501  const struct val_labs *labels = var_get_value_labels (var);
502
503  if ( labels )
504    {
505      for (vl = val_labs_first (labels);
506           vl;
507           vl = val_labs_next (labels, vl))
508        {
509          SV *sv = value_to_scalar (&vl->value, var);
510          STRLEN len;
511          const char *s = SvPV (sv, len);
512          hv_store (labelhash, s, len, newSVpv (val_lab_get_label (vl), 0), 0);
513        }
514    }
515
516  RETVAL = newRV ((SV *) labelhash);
517  OUTPUT:
518 RETVAL
519
520
521
522 MODULE = PSPP           PACKAGE = PSPP::Sysfile
523
524
525 struct sysfile_info *
526 pxs_create_sysfile (name, dict_ref, opts_hr)
527  char *name
528  SV *dict_ref
529  SV *opts_hr
530 INIT:
531  SV *dict_sv = SvRV (dict_ref);
532  struct dictionary *dict = (void *) SvIV (dict_sv);
533  struct sfm_write_options opts;
534  if (!SvROK (opts_hr))
535   {
536     opts = sfm_writer_default_options ();
537   }
538  else
539   {
540     HV *opt_h = (HV *) SvRV (opts_hr);
541     SV** readonly = hv_fetch(opt_h, "readonly", 8, 0);
542     SV** compress = hv_fetch(opt_h, "compress", 8, 0);
543     SV** version = hv_fetch(opt_h, "version", 7, 0);
544
545     opts.create_writeable = readonly ? ! SvIV (*readonly) : true;
546     opts.compress = compress ? SvIV (*compress) : false;
547     opts.version = version ? SvIV (*version) : 3 ;
548   }
549 CODE:
550  struct file_handle *fh =
551   fh_create_file (NULL, name, fh_default_properties () );
552  struct sysfile_info *sfi = xmalloc (sizeof (*sfi));
553  sfi->writer = sfm_open_writer (fh, dict, opts);
554  sfi->dict = dict;
555  sfi->opened = true;
556  sfi->dict_sv = dict_sv;
557  SvREFCNT_inc (sfi->dict_sv);
558  
559  RETVAL = sfi;
560  OUTPUT:
561 RETVAL
562
563 int
564 close (sfi)
565  struct sysfile_info *sfi
566 CODE:
567  RETVAL = sysfile_close (sfi);
568 OUTPUT:
569  RETVAL
570
571 void
572 DESTROY (sfi)
573  struct sysfile_info *sfi
574 CODE:
575  sysfile_close (sfi);
576  SvREFCNT_dec (sfi->dict_sv);
577  free (sfi);
578
579 int
580 append_case (sfi, ccase)
581  struct sysfile_info *sfi
582  SV *ccase
583 INIT:
584  SV *errstr = get_sv("PSPP::errstr", TRUE);
585  sv_setpv (errstr, "");
586  if ( (!SvROK(ccase)))
587   {
588     XSRETURN_UNDEF;
589   }
590 CODE:
591  int i = 0;
592  AV *av_case = (AV*) SvRV (ccase);
593
594  const struct variable **vv;
595  size_t nv;
596  struct ccase *c;
597  SV *sv;
598
599  if ( av_len (av_case) >= dict_get_var_cnt (sfi->dict))
600    XSRETURN_UNDEF;
601
602  c =  case_create (dict_get_proto (sfi->dict));
603
604  dict_get_vars (sfi->dict, &vv, &nv, 1u << DC_ORDINARY | 1u << DC_SYSTEM);
605
606  for (sv = av_shift (av_case); SvOK (sv);  sv = av_shift (av_case))
607  {
608     const struct variable *v = vv[i++];
609     const struct fmt_spec *ifmt = var_get_aux (v);
610
611     /* If an input format has been set, then use it.
612        Otherwise just convert the raw value.
613     */
614     if ( ifmt )
615       {
616         struct substring ss = ss_cstr (SvPV_nolen (sv));
617         if ( ! data_in (ss, LEGACY_NATIVE, ifmt->type, 0, 0, 0,
618                         case_data_rw (c, v),
619                         var_get_width (v)) )
620           {
621             RETVAL = 0;
622             goto finish;
623           }
624       }
625     else
626       {
627         scalar_to_value (case_data_rw (c, v), sv, v);
628       }
629  }
630
631  /* The remaining variables must be sysmis or blank string */
632  while (i < dict_get_var_cnt (sfi->dict))
633  {
634    const struct variable *v = vv[i++];
635    union value *val = case_data_rw (c, v);
636    value_set_missing (val, var_get_width (v));
637  }
638  RETVAL = casewriter_write (sfi->writer, c);
639  finish:
640  free (vv);
641 OUTPUT:
642  RETVAL
643
644
645 \f
646
647 MODULE = PSPP           PACKAGE = PSPP::Reader
648
649 struct sysreader_info *
650 pxs_open_sysfile (name)
651  char * name
652 CODE:
653  struct casereader *reader;
654  struct sysreader_info *sri = NULL;
655  struct file_handle *fh =
656          fh_create_file (NULL, name, fh_default_properties () );
657
658  sri = xmalloc (sizeof (*sri));
659  sri->reader = sfm_open_reader (fh, &sri->dict, &sri->opts);
660
661  if ( NULL == sri->reader)
662  {
663    free (sri);
664    sri = NULL;
665  }
666
667  RETVAL = sri;
668  OUTPUT:
669 RETVAL
670
671
672 struct dictionary *
673 pxs_get_dict (reader)
674  struct sysreader_info *reader;
675 CODE:
676  RETVAL = reader->dict;
677  OUTPUT:
678 RETVAL
679
680
681 void
682 get_next_case (sfr)
683  struct sysreader_info *sfr;
684 PPCODE:
685  struct ccase *c;
686
687  if (c = casereader_read (sfr->reader))
688  {
689   int v;
690
691   EXTEND (SP, dict_get_var_cnt (sfr->dict));
692   for (v = 0; v < dict_get_var_cnt (sfr->dict); ++v )
693     {
694       const struct variable *var = dict_get_var (sfr->dict, v);
695       const union value *val = case_data (c, var);
696
697       PUSHs (sv_2mortal (value_to_scalar (val, var)));
698     }
699
700   case_unref (c);
701  }