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