Added a n_missing parameter to casereader_create_filter_missing.
[pspp-builds.git] / src / language / stats / t-test.q
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000 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_cdf.h>
20 #include <math.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include <data/case.h>
26 #include <data/casegrouper.h>
27 #include <data/casereader.h>
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/value-labels.h>
31 #include <data/variable.h>
32 #include <language/command.h>
33 #include <language/dictionary/split-file.h>
34 #include <language/lexer/lexer.h>
35 #include <libpspp/assertion.h>
36 #include <libpspp/compiler.h>
37 #include <libpspp/hash.h>
38 #include <libpspp/message.h>
39 #include <libpspp/misc.h>
40 #include <libpspp/str.h>
41 #include <libpspp/taint.h>
42 #include <math/group-proc.h>
43 #include <math/levene.h>
44 #include <output/manager.h>
45 #include <output/table.h>
46
47 #include "xalloc.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51
52 /* (headers) */
53
54 /* (specification)
55    "T-TEST" (tts_):
56      +groups=custom;
57      testval=double;
58      +variables=varlist("PV_NO_SCRATCH | PV_NUMERIC");
59      +pairs=custom;
60      missing=miss:!analysis/listwise,
61             incl:include/!exclude;
62      +format=fmt:!labels/nolabels;
63      criteria=:cin(d:criteria,"%s > 0. && %s < 1.").
64 */
65 /* (declarations) */
66 /* (functions) */
67
68
69 /* Variable for the GROUPS subcommand, if given. */
70 static struct variable *indep_var;
71
72 enum comparison
73   {
74     CMP_LE = -2,
75     CMP_EQ = 0,
76   };
77
78 struct group_properties
79 {
80   /* The comparison criterion */
81   enum comparison criterion;
82
83   /* The width of the independent variable */
84   int indep_width ;
85
86   union {
87     /* The value of the independent variable at which groups are determined to
88        belong to one group or the other */
89     double critical_value;
90
91
92     /* The values of the independent variable for each group */
93     union value g_value[2];
94   } v ;
95
96 };
97
98
99 static struct group_properties gp ;
100
101
102
103 /* PAIRS: Number of pairs to be compared ; each pair. */
104 static int n_pairs = 0 ;
105 struct pair
106 {
107   /* The variables comprising the pair */
108   const struct variable *v[2];
109
110   /* The number of valid variable pairs */
111   double n;
112
113   /* The sum of the members */
114   double sum[2];
115
116   /* sum of squares of the members */
117   double ssq[2];
118
119   /* Std deviation of the members */
120   double std_dev[2];
121
122
123   /* Sample Std deviation of the members */
124   double s_std_dev[2];
125
126   /* The means of the members */
127   double mean[2];
128
129   /* The correlation coefficient between the variables */
130   double correlation;
131
132   /* The sum of the differences */
133   double sum_of_diffs;
134
135   /* The sum of the products */
136   double sum_of_prod;
137
138   /* The mean of the differences */
139   double mean_diff;
140
141   /* The sum of the squares of the differences */
142   double ssq_diffs;
143
144   /* The std deviation of the differences */
145   double std_dev_diff;
146 };
147
148 static struct pair *pairs=0;
149
150 static int parse_value (struct lexer *lexer, union value * v, enum val_type);
151
152 /* Structures and Functions for the Statistics Summary Box */
153 struct ssbox;
154 typedef void populate_ssbox_func (struct ssbox *ssb,
155                                             struct cmd_t_test *cmd);
156 typedef void finalize_ssbox_func (struct ssbox *ssb);
157
158 struct ssbox
159 {
160   struct tab_table *t;
161
162   populate_ssbox_func *populate;
163   finalize_ssbox_func *finalize;
164
165 };
166
167 /* Create a ssbox */
168 void ssbox_create (struct ssbox *ssb,   struct cmd_t_test *cmd, int mode);
169
170 /* Populate a ssbox according to cmd */
171 void ssbox_populate (struct ssbox *ssb, struct cmd_t_test *cmd);
172
173 /* Submit and destroy a ssbox */
174 void ssbox_finalize (struct ssbox *ssb);
175
176 /* A function to create, populate and submit the Paired Samples Correlation
177    box */
178 void pscbox (void);
179
180
181 /* Structures and Functions for the Test Results Box */
182 struct trbox;
183
184 typedef void populate_trbox_func (struct trbox *trb,
185                                  struct cmd_t_test *cmd);
186 typedef void finalize_trbox_func (struct trbox *trb);
187
188 struct trbox {
189   struct tab_table *t;
190   populate_trbox_func *populate;
191   finalize_trbox_func *finalize;
192 };
193
194 /* Create a trbox */
195 void trbox_create (struct trbox *trb,   struct cmd_t_test *cmd, int mode);
196
197 /* Populate a ssbox according to cmd */
198 void trbox_populate (struct trbox *trb, struct cmd_t_test *cmd);
199
200 /* Submit and destroy a ssbox */
201 void trbox_finalize (struct trbox *trb);
202
203 /* Which mode was T-TEST invoked */
204 enum {
205   T_1_SAMPLE = 0 ,
206   T_IND_SAMPLES,
207   T_PAIRED
208 };
209
210
211 static int common_calc (const struct dictionary *dict,
212                         const struct ccase *, void *,
213                         enum mv_class);
214 static void common_precalc (struct cmd_t_test *);
215 static void common_postcalc (struct cmd_t_test *);
216
217 static int one_sample_calc (const struct dictionary *dict, const struct ccase *, void *, enum mv_class);
218 static void one_sample_precalc (struct cmd_t_test *);
219 static void one_sample_postcalc (struct cmd_t_test *);
220
221 static int  paired_calc (const struct dictionary *dict, const struct ccase *,
222                          struct cmd_t_test*, enum mv_class);
223 static void paired_precalc (struct cmd_t_test *);
224 static void paired_postcalc (struct cmd_t_test *);
225
226 static void group_precalc (struct cmd_t_test *);
227 static int  group_calc (const struct dictionary *dict, const struct ccase *,
228                         struct cmd_t_test *, enum mv_class);
229 static void group_postcalc (struct cmd_t_test *);
230
231
232 static void calculate (struct cmd_t_test *,
233                       struct casereader *,
234                       const struct dataset *);
235
236 static  int mode;
237
238 static struct cmd_t_test cmd;
239
240 static bool bad_weight_warn = false;
241
242
243 static int compare_group_binary (const struct group_statistics *a,
244                                 const struct group_statistics *b,
245                                 const struct group_properties *p);
246
247
248 static unsigned  hash_group_binary (const struct group_statistics *g,
249                                    const struct group_properties *p);
250
251
252
253 int
254 cmd_t_test (struct lexer *lexer, struct dataset *ds)
255 {
256   struct casegrouper *grouper;
257   struct casereader *group;
258   bool ok;
259
260   if ( !parse_t_test (lexer, ds, &cmd, NULL) )
261     return CMD_FAILURE;
262
263   if (! cmd.sbc_criteria)
264     cmd.criteria=0.95;
265
266   {
267     int m=0;
268     if (cmd.sbc_testval) ++m;
269     if (cmd.sbc_groups) ++m;
270     if (cmd.sbc_pairs) ++m;
271
272     if ( m != 1)
273       {
274         msg (SE,
275             _ ("TESTVAL, GROUPS and PAIRS subcommands are mutually exclusive.")
276             );
277         free_t_test (&cmd);
278         return CMD_FAILURE;
279       }
280   }
281
282   if (cmd.sbc_testval)
283     mode=T_1_SAMPLE;
284   else if (cmd.sbc_groups)
285     mode=T_IND_SAMPLES;
286   else
287     mode=T_PAIRED;
288
289   if ( mode == T_PAIRED)
290     {
291       if (cmd.sbc_variables)
292         {
293           msg (SE, _ ("VARIABLES subcommand is not appropriate with PAIRS"));
294           free_t_test (&cmd);
295           return CMD_FAILURE;
296         }
297       else
298         {
299           /* Iterate through the pairs and put each variable that is a
300              member of a pair into cmd.v_variables */
301
302           int i;
303           struct hsh_iterator hi;
304           struct const_hsh_table *hash;
305           const struct variable *v;
306
307           hash = const_hsh_create (n_pairs, compare_vars_by_name, hash_var_by_name,
308           0, 0);
309
310           for (i=0; i < n_pairs; ++i)
311             {
312               const_hsh_insert (hash, pairs[i].v[0]);
313               const_hsh_insert (hash, pairs[i].v[1]);
314             }
315
316           assert (cmd.n_variables == 0);
317           cmd.n_variables = const_hsh_count (hash);
318
319           cmd.v_variables = xnrealloc (cmd.v_variables, cmd.n_variables,
320                                        sizeof *cmd.v_variables);
321           /* Iterate through the hash */
322           for (i=0,v = const_hsh_first (hash, &hi);
323                v != 0;
324                v = const_hsh_next (hash, &hi) )
325             cmd.v_variables[i++]=v;
326           const_hsh_destroy (hash);
327         }
328     }
329   else if ( !cmd.sbc_variables)
330     {
331       msg (SE, _ ("One or more VARIABLES must be specified."));
332       free_t_test (&cmd);
333       return CMD_FAILURE;
334     }
335
336   bad_weight_warn = true;
337
338   /* Data pass. */
339   grouper = casegrouper_create_splits (proc_open (ds), dataset_dict (ds));
340   while (casegrouper_get_next_group (grouper, &group))
341     calculate (&cmd, group, ds);
342   ok = casegrouper_destroy (grouper);
343   ok = proc_commit (ds) && ok;
344
345   n_pairs=0;
346   free (pairs);
347   pairs=0;
348
349   if ( mode == T_IND_SAMPLES)
350     {
351       int v;
352       /* Destroy any group statistics we created */
353       for (v = 0 ; v < cmd.n_variables ; ++v )
354         {
355           struct group_proc *grpp = group_proc_get (cmd.v_variables[v]);
356           hsh_destroy (grpp->group_hash);
357         }
358     }
359
360   free_t_test (&cmd);
361   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
362 }
363
364 static int
365 tts_custom_groups (struct lexer *lexer, struct dataset *ds, struct cmd_t_test *cmd UNUSED, 
366         void *aux UNUSED)
367 {
368   int n_group_values=0;
369
370   lex_match (lexer, '=');
371
372   indep_var = parse_variable (lexer, dataset_dict (ds));
373   if (!indep_var)
374     {
375       lex_error (lexer, "expecting variable name in GROUPS subcommand");
376       return 0;
377     }
378
379   if (var_is_long_string (indep_var))
380     {
381       msg (SE, _ ("Long string variable %s is not valid here."),
382            var_get_name (indep_var));
383       return 0;
384     }
385
386   if (!lex_match (lexer, '('))
387     {
388       if (var_is_numeric (indep_var))
389         {
390           gp.v.g_value[0].f = 1;
391           gp.v.g_value[1].f = 2;
392
393           gp.criterion = CMP_EQ;
394
395           n_group_values = 2;
396
397           return 1;
398         }
399       else
400         {
401           msg (SE, _ ("When applying GROUPS to a string variable, two "
402                      "values must be specified."));
403           return 0;
404         }
405     }
406
407   if (!parse_value (lexer, &gp.v.g_value[0], var_get_type (indep_var)))
408       return 0;
409
410   lex_match (lexer, ',');
411   if (lex_match (lexer, ')'))
412     {
413       if (var_is_alpha (indep_var))
414         {
415           msg (SE, _ ("When applying GROUPS to a string variable, two "
416                      "values must be specified."));
417           return 0;
418         }
419       gp.criterion = CMP_LE;
420       gp.v.critical_value = gp.v.g_value[0].f;
421
422       n_group_values = 1;
423       return 1;
424     }
425
426   if (!parse_value (lexer, &gp.v.g_value[1], var_get_type (indep_var)))
427     return 0;
428
429   n_group_values = 2;
430   if (!lex_force_match (lexer, ')'))
431     return 0;
432
433   if ( n_group_values == 2 )
434     gp.criterion = CMP_EQ ;
435   else
436     gp.criterion = CMP_LE ;
437
438
439   if ( var_is_alpha (indep_var))
440     {
441       buf_copy_rpad (gp.v.g_value [0].s, var_get_width (indep_var),
442                      gp.v.g_value [0].s, strlen (gp.v.g_value[0].s));
443
444       buf_copy_rpad (gp.v.g_value [1].s, var_get_width (indep_var),
445                      gp.v.g_value [1].s, strlen (gp.v.g_value[1].s));
446     }
447
448   return 1;
449 }
450
451
452 static int
453 tts_custom_pairs (struct lexer *lexer, struct dataset *ds, struct cmd_t_test *cmd UNUSED, void *aux UNUSED)
454 {
455   const struct variable **vars;
456   size_t n_vars;
457   size_t n_pairs_local;
458
459   size_t n_before_WITH;
460   size_t n_after_WITH = SIZE_MAX;
461   int paired ; /* Was the PAIRED keyword given ? */
462
463   lex_match (lexer, '=');
464
465   n_vars=0;
466   if (!parse_variables_const (lexer, dataset_dict (ds), &vars, &n_vars,
467                         PV_DUPLICATE | PV_NUMERIC | PV_NO_SCRATCH))
468     {
469       free (vars);
470       return 0;
471     }
472   assert (n_vars);
473
474   n_before_WITH = 0;
475   if (lex_match (lexer, T_WITH))
476     {
477       n_before_WITH = n_vars;
478       if (!parse_variables_const (lexer, dataset_dict (ds), &vars, &n_vars,
479                             PV_DUPLICATE | PV_APPEND
480                             | PV_NUMERIC | PV_NO_SCRATCH))
481         {
482           free (vars);
483           return 0;
484         }
485       n_after_WITH = n_vars - n_before_WITH;
486     }
487
488   paired = (lex_match (lexer, '(') && lex_match_id (lexer, "PAIRED") && lex_match (lexer, ')'));
489
490   /* Determine the number of pairs needed */
491   if (paired)
492     {
493       if (n_before_WITH != n_after_WITH)
494         {
495           free (vars);
496           msg (SE, _ ("PAIRED was specified but the number of variables "
497                      "preceding WITH (%zu) did not match the number "
498                      "following (%zu)."),
499                n_before_WITH, n_after_WITH);
500           return 0;
501         }
502       n_pairs_local = n_before_WITH;
503     }
504   else if (n_before_WITH > 0) /* WITH keyword given, but not PAIRED keyword */
505     {
506       n_pairs_local = n_before_WITH * n_after_WITH ;
507     }
508   else /* Neither WITH nor PAIRED keyword given */
509     {
510       if (n_vars < 2)
511         {
512           free (vars);
513           msg (SE, _ ("At least two variables must be specified "
514                      "on PAIRS."));
515           return 0;
516         }
517
518       /* how many ways can you pick 2 from n_vars ? */
519       n_pairs_local = n_vars * (n_vars - 1) / 2;
520     }
521
522
523   /* Allocate storage for the pairs */
524   pairs = xnrealloc (pairs, n_pairs + n_pairs_local, sizeof *pairs);
525
526   /* Populate the pairs with the appropriate variables */
527   if ( paired )
528     {
529       int i;
530
531       assert (n_pairs_local == n_vars / 2);
532       for (i = 0; i < n_pairs_local; ++i)
533         {
534           pairs[i].v[n_pairs] = vars[i];
535           pairs[i].v[n_pairs + 1] = vars[i + n_pairs_local];
536         }
537     }
538   else if (n_before_WITH > 0) /* WITH keyword given, but not PAIRED keyword */
539     {
540       int i,j;
541       size_t p = n_pairs;
542
543       for (i=0 ; i < n_before_WITH ; ++i )
544         {
545           for (j=0 ; j < n_after_WITH ; ++j)
546             {
547               pairs[p].v[0] = vars[i];
548               pairs[p].v[1] = vars[j+n_before_WITH];
549               ++p;
550             }
551         }
552     }
553   else /* Neither WITH nor PAIRED given */
554     {
555       size_t i,j;
556       size_t p=n_pairs;
557
558       for (i=0 ; i < n_vars ; ++i )
559         {
560           for (j=i+1 ; j < n_vars ; ++j)
561             {
562               pairs[p].v[0] = vars[i];
563               pairs[p].v[1] = vars[j];
564               ++p;
565             }
566         }
567     }
568
569   n_pairs+=n_pairs_local;
570
571   free (vars);
572   return 1;
573 }
574
575 /* Parses the current token (numeric or string, depending on type)
576     value v and returns success. */
577 static int
578 parse_value (struct lexer *lexer, union value * v, enum val_type type)
579 {
580   if (type == VAL_NUMERIC)
581     {
582       if (!lex_force_num (lexer))
583         return 0;
584       v->f = lex_tokval (lexer);
585     }
586   else
587     {
588       if (!lex_force_string (lexer))
589         return 0;
590       memset  (v->s, ' ', MAX_SHORT_STRING);
591       strncpy (v->s, ds_cstr (lex_tokstr (lexer)), ds_length (lex_tokstr (lexer)));
592     }
593
594   lex_get (lexer);
595
596   return 1;
597 }
598
599
600 /* Implementation of the SSBOX object */
601
602 void ssbox_base_init (struct ssbox *this, int cols,int rows);
603
604 void ssbox_base_finalize (struct ssbox *ssb);
605
606 void ssbox_one_sample_init (struct ssbox *this,
607                            struct cmd_t_test *cmd );
608
609 void ssbox_independent_samples_init (struct ssbox *this,
610                                     struct cmd_t_test *cmd);
611
612 void ssbox_paired_init (struct ssbox *this,
613                            struct cmd_t_test *cmd);
614
615
616 /* Factory to create an ssbox */
617 void
618 ssbox_create (struct ssbox *ssb, struct cmd_t_test *cmd, int mode)
619 {
620     switch (mode)
621       {
622       case T_1_SAMPLE:
623         ssbox_one_sample_init (ssb,cmd);
624         break;
625       case T_IND_SAMPLES:
626         ssbox_independent_samples_init (ssb,cmd);
627         break;
628       case T_PAIRED:
629         ssbox_paired_init (ssb,cmd);
630         break;
631       default:
632         NOT_REACHED ();
633       }
634 }
635
636
637
638 /* Despatcher for the populate method */
639 void
640 ssbox_populate (struct ssbox *ssb,struct cmd_t_test *cmd)
641 {
642   ssb->populate (ssb,cmd);
643 }
644
645
646 /* Despatcher for finalize */
647 void
648 ssbox_finalize (struct ssbox *ssb)
649 {
650   ssb->finalize (ssb);
651 }
652
653
654 /* Submit the box and clear up */
655 void
656 ssbox_base_finalize (struct ssbox *ssb)
657 {
658   tab_submit (ssb->t);
659 }
660
661
662
663 /* Initialize a ssbox struct */
664 void
665 ssbox_base_init (struct ssbox *this, int cols,int rows)
666 {
667   this->finalize = ssbox_base_finalize;
668   this->t = tab_create (cols, rows, 0);
669
670   tab_columns (this->t, SOM_COL_DOWN, 1);
671   tab_headers (this->t,0,0,1,0);
672   tab_box (this->t, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, cols -1, rows -1 );
673   tab_hline (this->t, TAL_2,0,cols-1,1);
674   tab_dim (this->t, tab_natural_dimensions);
675 }
676
677 void  ssbox_one_sample_populate (struct ssbox *ssb,
678                               struct cmd_t_test *cmd);
679
680 /* Initialize the one_sample ssbox */
681 void
682 ssbox_one_sample_init (struct ssbox *this,
683                            struct cmd_t_test *cmd )
684 {
685   const int hsize=5;
686   const int vsize=cmd->n_variables+1;
687
688   this->populate = ssbox_one_sample_populate;
689
690   ssbox_base_init (this, hsize,vsize);
691   tab_title (this->t, _ ("One-Sample Statistics"));
692   tab_vline (this->t, TAL_2, 1,0,vsize - 1);
693   tab_text (this->t, 1, 0, TAB_CENTER | TAT_TITLE, _ ("N"));
694   tab_text (this->t, 2, 0, TAB_CENTER | TAT_TITLE, _ ("Mean"));
695   tab_text (this->t, 3, 0, TAB_CENTER | TAT_TITLE, _ ("Std. Deviation"));
696   tab_text (this->t, 4, 0, TAB_CENTER | TAT_TITLE, _ ("SE. Mean"));
697 }
698
699 void ssbox_independent_samples_populate (struct ssbox *ssb,
700                                         struct cmd_t_test *cmd);
701
702 /* Initialize the independent samples ssbox */
703 void
704 ssbox_independent_samples_init (struct ssbox *this,
705         struct cmd_t_test *cmd)
706 {
707   int hsize=6;
708   int vsize = cmd->n_variables*2 +1;
709
710   this->populate = ssbox_independent_samples_populate;
711
712   ssbox_base_init (this, hsize,vsize);
713   tab_vline (this->t, TAL_GAP, 1, 0,vsize - 1);
714   tab_title (this->t, _ ("Group Statistics"));
715   tab_text (this->t, 1, 0, TAB_CENTER | TAT_TITLE, var_get_name (indep_var));
716   tab_text (this->t, 2, 0, TAB_CENTER | TAT_TITLE, _ ("N"));
717   tab_text (this->t, 3, 0, TAB_CENTER | TAT_TITLE, _ ("Mean"));
718   tab_text (this->t, 4, 0, TAB_CENTER | TAT_TITLE, _ ("Std. Deviation"));
719   tab_text (this->t, 5, 0, TAB_CENTER | TAT_TITLE, _ ("SE. Mean"));
720 }
721
722
723 /* Populate the ssbox for independent samples */
724 void
725 ssbox_independent_samples_populate (struct ssbox *ssb,
726                               struct cmd_t_test *cmd)
727 {
728   int i;
729
730   char *val_lab[2] = {NULL, NULL};
731   double indep_value[2];
732
733   char prefix[2][3]={"",""};
734
735   if ( var_is_numeric (indep_var) )
736     {
737       const char *s;
738
739       s = var_lookup_value_label (indep_var, &gp.v.g_value[0]);
740       val_lab[0] = s ? strdup (s) : NULL;
741
742       s = var_lookup_value_label (indep_var, &gp.v.g_value[1]);
743       val_lab[1] = s ? strdup (s) : NULL;
744     }
745   else
746     {
747       val_lab[0] = calloc (sizeof (char), MAX_SHORT_STRING + 1);
748       val_lab[1] = calloc (sizeof (char), MAX_SHORT_STRING + 1);
749       memcpy (val_lab[0], gp.v.g_value[0].s, MAX_SHORT_STRING);
750       memcpy (val_lab[1], gp.v.g_value[1].s, MAX_SHORT_STRING);
751     }
752
753   if (gp.criterion == CMP_LE )
754     {
755       strcpy (prefix[0],">=");
756       strcpy (prefix[1],"<");
757       indep_value[0] = gp.v.critical_value;
758       indep_value[1] = gp.v.critical_value;
759     }
760   else
761     {
762       indep_value[0] = gp.v.g_value[0].f;
763       indep_value[1] = gp.v.g_value[1].f;
764     }
765
766   assert (ssb->t);
767
768   for (i=0; i < cmd->n_variables; ++i)
769     {
770       const struct variable *var = cmd->v_variables[i];
771       struct hsh_table *grp_hash = group_proc_get (var)->group_hash;
772       int count=0;
773
774       tab_text (ssb->t, 0, i*2+1, TAB_LEFT,
775                 var_get_name (cmd->v_variables[i]));
776
777       if (val_lab[0])
778         tab_text (ssb->t, 1, i*2+1, TAB_LEFT | TAT_PRINTF,
779                   "%s%s", prefix[0], val_lab[0]);
780       else
781           tab_text (ssb->t, 1, i*2+1, TAB_LEFT | TAT_PRINTF,
782                     "%s%g", prefix[0], indep_value[0]);
783
784
785       if (val_lab[1])
786         tab_text (ssb->t, 1, i*2+1+1, TAB_LEFT | TAT_PRINTF,
787                   "%s%s", prefix[1], val_lab[1]);
788       else
789           tab_text (ssb->t, 1, i*2+1+1, TAB_LEFT | TAT_PRINTF,
790                     "%s%g", prefix[1], indep_value[1]);
791
792
793       /* Fill in the group statistics */
794       for ( count = 0 ; count < 2 ; ++count )
795         {
796           union value search_val;
797
798           struct group_statistics *gs;
799
800           if ( gp.criterion == CMP_LE )
801             {
802               if ( count == 0 )
803                 {
804                   /* >= case  */
805                   search_val.f = gp.v.critical_value + 1.0;
806                 }
807               else
808                 {
809                   /*  less than ( < )  case */
810                   search_val.f = gp.v.critical_value - 1.0;
811                 }
812             }
813           else
814             {
815               search_val = gp.v.g_value[count];
816             }
817
818           gs = hsh_find (grp_hash, (void *) &search_val);
819           assert (gs);
820
821           tab_float (ssb->t, 2 ,i*2+count+1, TAB_RIGHT, gs->n, 10, 0);
822           tab_float (ssb->t, 3 ,i*2+count+1, TAB_RIGHT, gs->mean, 8, 2);
823           tab_float (ssb->t, 4 ,i*2+count+1, TAB_RIGHT, gs->std_dev, 8, 3);
824           tab_float (ssb->t, 5 ,i*2+count+1, TAB_RIGHT, gs->se_mean, 8, 3);
825         }
826     }
827   free (val_lab[0]);
828   free (val_lab[1]);
829 }
830
831
832 void ssbox_paired_populate (struct ssbox *ssb,
833                            struct cmd_t_test *cmd);
834
835 /* Initialize the paired values ssbox */
836 void
837 ssbox_paired_init (struct ssbox *this, struct cmd_t_test *cmd UNUSED)
838 {
839   int hsize=6;
840
841   int vsize = n_pairs*2+1;
842
843   this->populate = ssbox_paired_populate;
844
845   ssbox_base_init (this, hsize,vsize);
846   tab_title (this->t, _ ("Paired Sample Statistics"));
847   tab_vline (this->t,TAL_GAP,1,0,vsize-1);
848   tab_vline (this->t,TAL_2,2,0,vsize-1);
849   tab_text (this->t, 2, 0, TAB_CENTER | TAT_TITLE, _ ("Mean"));
850   tab_text (this->t, 3, 0, TAB_CENTER | TAT_TITLE, _ ("N"));
851   tab_text (this->t, 4, 0, TAB_CENTER | TAT_TITLE, _ ("Std. Deviation"));
852   tab_text (this->t, 5, 0, TAB_CENTER | TAT_TITLE, _ ("SE. Mean"));
853 }
854
855
856 /* Populate the ssbox for paired values */
857 void
858 ssbox_paired_populate (struct ssbox *ssb,struct cmd_t_test *cmd UNUSED)
859 {
860   int i;
861
862   assert (ssb->t);
863
864   for (i=0; i < n_pairs; ++i)
865     {
866       int j;
867
868       tab_text (ssb->t, 0, i*2+1, TAB_LEFT | TAT_PRINTF , _ ("Pair %d"),i);
869
870       for (j=0 ; j < 2 ; ++j)
871         {
872           struct group_statistics *gs;
873
874           gs = &group_proc_get (pairs[i].v[j])->ugs;
875
876           /* Titles */
877
878           tab_text (ssb->t, 1, i*2+j+1, TAB_LEFT,
879                     var_get_name (pairs[i].v[j]));
880
881           /* Values */
882           tab_float (ssb->t,2, i*2+j+1, TAB_RIGHT, pairs[i].mean[j], 8, 2);
883           tab_float (ssb->t,3, i*2+j+1, TAB_RIGHT, pairs[i].n, 10, 0);
884           tab_float (ssb->t,4, i*2+j+1, TAB_RIGHT, pairs[i].std_dev[j], 8, 3);
885           tab_float (ssb->t,5, i*2+j+1, TAB_RIGHT, pairs[i].std_dev[j]/sqrt (pairs[i].n), 8, 3);
886
887         }
888     }
889 }
890
891 /* Populate the one sample ssbox */
892 void
893 ssbox_one_sample_populate (struct ssbox *ssb, struct cmd_t_test *cmd)
894 {
895   int i;
896
897   assert (ssb->t);
898
899   for (i=0; i < cmd->n_variables; ++i)
900     {
901       struct group_statistics *gs = &group_proc_get (cmd->v_variables[i])->ugs;
902
903       tab_text (ssb->t, 0, i+1, TAB_LEFT, var_get_name (cmd->v_variables[i]));
904       tab_float (ssb->t,1, i+1, TAB_RIGHT, gs->n, 10, 0);
905       tab_float (ssb->t,2, i+1, TAB_RIGHT, gs->mean, 8, 2);
906       tab_float (ssb->t,3, i+1, TAB_RIGHT, gs->std_dev, 8, 2);
907       tab_float (ssb->t,4, i+1, TAB_RIGHT, gs->se_mean, 8, 3);
908     }
909
910 }
911
912
913
914 /* Implementation of the Test Results box struct */
915
916 void trbox_base_init (struct trbox *self,size_t n_vars, int cols);
917 void trbox_base_finalize (struct trbox *trb);
918
919 void trbox_independent_samples_init (struct trbox *trb,
920                                     struct cmd_t_test *cmd );
921
922 void trbox_independent_samples_populate (struct trbox *trb,
923                                         struct cmd_t_test *cmd);
924
925 void trbox_one_sample_init (struct trbox *self,
926                       struct cmd_t_test *cmd );
927
928 void trbox_one_sample_populate (struct trbox *trb,
929                                struct cmd_t_test *cmd);
930
931 void trbox_paired_init (struct trbox *self,
932                        struct cmd_t_test *cmd );
933
934 void trbox_paired_populate (struct trbox *trb,
935                       struct cmd_t_test *cmd);
936
937
938
939 /* Create a trbox according to mode*/
940 void
941 trbox_create (struct trbox *trb,
942              struct cmd_t_test *cmd, int mode)
943 {
944     switch (mode)
945       {
946       case T_1_SAMPLE:
947         trbox_one_sample_init (trb,cmd);
948         break;
949       case T_IND_SAMPLES:
950         trbox_independent_samples_init (trb,cmd);
951         break;
952       case T_PAIRED:
953         trbox_paired_init (trb,cmd);
954         break;
955       default:
956         NOT_REACHED ();
957       }
958 }
959
960 /* Populate a trbox according to cmd */
961 void
962 trbox_populate (struct trbox *trb, struct cmd_t_test *cmd)
963 {
964   trb->populate (trb,cmd);
965 }
966
967 /* Submit and destroy a trbox */
968 void
969 trbox_finalize (struct trbox *trb)
970 {
971   trb->finalize (trb);
972 }
973
974 /* Initialize the independent samples trbox */
975 void
976 trbox_independent_samples_init (struct trbox *self,
977                            struct cmd_t_test *cmd UNUSED)
978 {
979   const int hsize=11;
980   const int vsize=cmd->n_variables*2+3;
981
982   assert (self);
983   self->populate = trbox_independent_samples_populate;
984
985   trbox_base_init (self,cmd->n_variables*2,hsize);
986   tab_title (self->t,_ ("Independent Samples Test"));
987   tab_hline (self->t,TAL_1,2,hsize-1,1);
988   tab_vline (self->t,TAL_2,2,0,vsize-1);
989   tab_vline (self->t,TAL_1,4,0,vsize-1);
990   tab_box (self->t,-1,-1,-1,TAL_1, 2,1,hsize-2,vsize-1);
991   tab_hline (self->t,TAL_1, hsize-2,hsize-1,2);
992   tab_box (self->t,-1,-1,-1,TAL_1, hsize-2,2,hsize-1,vsize-1);
993   tab_joint_text (self->t, 2, 0, 3, 0,
994                  TAB_CENTER,_ ("Levene's Test for Equality of Variances"));
995   tab_joint_text (self->t, 4,0,hsize-1,0,
996                  TAB_CENTER,_ ("t-test for Equality of Means"));
997
998   tab_text (self->t,2,2, TAB_CENTER | TAT_TITLE,_ ("F"));
999   tab_text (self->t,3,2, TAB_CENTER | TAT_TITLE,_ ("Sig."));
1000   tab_text (self->t,4,2, TAB_CENTER | TAT_TITLE,_ ("t"));
1001   tab_text (self->t,5,2, TAB_CENTER | TAT_TITLE,_ ("df"));
1002   tab_text (self->t,6,2, TAB_CENTER | TAT_TITLE,_ ("Sig. (2-tailed)"));
1003   tab_text (self->t,7,2, TAB_CENTER | TAT_TITLE,_ ("Mean Difference"));
1004   tab_text (self->t,8,2, TAB_CENTER | TAT_TITLE,_ ("Std. Error Difference"));
1005   tab_text (self->t,9,2, TAB_CENTER | TAT_TITLE,_ ("Lower"));
1006   tab_text (self->t,10,2, TAB_CENTER | TAT_TITLE,_ ("Upper"));
1007
1008   tab_joint_text (self->t, 9, 1, 10, 1, TAB_CENTER | TAT_PRINTF,
1009                  _ ("%g%% Confidence Interval of the Difference"),
1010                  cmd->criteria*100.0);
1011
1012 }
1013
1014 /* Populate the independent samples trbox */
1015 void
1016 trbox_independent_samples_populate (struct trbox *self,
1017                                    struct cmd_t_test *cmd )
1018 {
1019   int i;
1020
1021   assert (self);
1022   for (i=0; i < cmd->n_variables; ++i)
1023     {
1024       double p,q;
1025
1026       double t;
1027       double df;
1028
1029       double df1, df2;
1030
1031       double pooled_variance;
1032       double std_err_diff;
1033       double mean_diff;
1034
1035       const struct variable *var = cmd->v_variables[i];
1036       struct group_proc *grp_data = group_proc_get (var);
1037
1038       struct hsh_table *grp_hash = grp_data->group_hash;
1039
1040       struct group_statistics *gs0 ;
1041       struct group_statistics *gs1 ;
1042
1043       union value search_val;
1044
1045       if ( gp.criterion == CMP_LE )
1046         search_val.f = gp.v.critical_value - 1.0;
1047       else
1048         search_val = gp.v.g_value[0];
1049
1050       gs0 = hsh_find (grp_hash, (void *) &search_val);
1051       assert (gs0);
1052
1053       if ( gp.criterion == CMP_LE )
1054         search_val.f = gp.v.critical_value + 1.0;
1055       else
1056         search_val = gp.v.g_value[1];
1057
1058       gs1 = hsh_find (grp_hash, (void *) &search_val);
1059       assert (gs1);
1060
1061
1062       tab_text (self->t, 0, i*2+3, TAB_LEFT, var_get_name (cmd->v_variables[i]));
1063
1064       tab_text (self->t, 1, i*2+3, TAB_LEFT, _ ("Equal variances assumed"));
1065
1066
1067       tab_float (self->t, 2, i*2+3, TAB_CENTER, grp_data->levene, 8,3);
1068
1069       /* Now work out the significance of the Levene test */
1070       df1 = 1; df2 = grp_data->ugs.n - 2;
1071       q = gsl_cdf_fdist_Q (grp_data->levene, df1, df2);
1072
1073       tab_float (self->t, 3, i*2+3, TAB_CENTER, q, 8,3 );
1074
1075       df = gs0->n + gs1->n - 2.0 ;
1076       tab_float (self->t, 5, i*2+3, TAB_RIGHT, df, 10, 0);
1077
1078       pooled_variance = ( (gs0->n )*pow2 (gs0->s_std_dev)
1079                           +
1080                           (gs1->n )*pow2 (gs1->s_std_dev)
1081                         ) / df  ;
1082
1083       t = (gs0->mean - gs1->mean) / sqrt (pooled_variance) ;
1084       t /= sqrt ((gs0->n + gs1->n)/ (gs0->n*gs1->n));
1085
1086       tab_float (self->t, 4, i*2+3, TAB_RIGHT, t, 8, 3);
1087
1088       p = gsl_cdf_tdist_P (t, df);
1089       q = gsl_cdf_tdist_Q (t, df);
1090
1091       tab_float (self->t, 6, i*2+3, TAB_RIGHT, 2.0* (t>0?q:p) , 8, 3);
1092
1093       mean_diff = gs0->mean - gs1->mean;
1094       tab_float (self->t, 7, i*2+3, TAB_RIGHT, mean_diff, 8, 3);
1095
1096
1097       std_err_diff = sqrt ( pow2 (gs0->se_mean) + pow2 (gs1->se_mean));
1098       tab_float (self->t, 8, i*2+3, TAB_RIGHT, std_err_diff, 8, 3);
1099
1100
1101       /* Now work out the confidence interval */
1102       q = (1 - cmd->criteria)/2.0;  /* 2-tailed test */
1103
1104       t = gsl_cdf_tdist_Qinv (q,df);
1105       tab_float (self->t, 9, i*2+3, TAB_RIGHT,
1106                 mean_diff - t * std_err_diff, 8, 3);
1107
1108       tab_float (self->t, 10, i*2+3, TAB_RIGHT,
1109                 mean_diff + t * std_err_diff, 8, 3);
1110
1111
1112       {
1113         double se2;
1114       /* Now for the \sigma_1 != \sigma_2 case */
1115       tab_text (self->t, 1, i*2+3+1,
1116                 TAB_LEFT, _ ("Equal variances not assumed"));
1117
1118
1119       se2 = (pow2 (gs0->s_std_dev)/ (gs0->n -1) ) +
1120          (pow2 (gs1->s_std_dev)/ (gs1->n -1) );
1121
1122       t = mean_diff / sqrt (se2) ;
1123       tab_float (self->t, 4, i*2+3+1, TAB_RIGHT, t, 8, 3);
1124
1125       df = pow2 (se2) / (
1126                        (pow2 (pow2 (gs0->s_std_dev)/ (gs0->n - 1 ))
1127                         / (gs0->n -1 )
1128                         )
1129                        +
1130                        (pow2 (pow2 (gs1->s_std_dev)/ (gs1->n - 1 ))
1131                         / (gs1->n -1 )
1132                         )
1133                        ) ;
1134       tab_float (self->t, 5, i*2+3+1, TAB_RIGHT, df, 8, 3);
1135
1136       p = gsl_cdf_tdist_P (t, df);
1137       q = gsl_cdf_tdist_Q (t, df);
1138
1139       tab_float (self->t, 6, i*2+3+1, TAB_RIGHT, 2.0* (t>0?q:p) , 8, 3);
1140
1141       /* Now work out the confidence interval */
1142       q = (1 - cmd->criteria)/2.0;  /* 2-tailed test */
1143
1144       t = gsl_cdf_tdist_Qinv (q, df);
1145
1146       tab_float (self->t, 7, i*2+3+1, TAB_RIGHT, mean_diff, 8, 3);
1147
1148
1149       tab_float (self->t, 8, i*2+3+1, TAB_RIGHT, std_err_diff, 8, 3);
1150
1151
1152       tab_float (self->t, 9, i*2+3+1, TAB_RIGHT,
1153                 mean_diff - t * std_err_diff, 8, 3);
1154
1155       tab_float (self->t, 10, i*2+3+1, TAB_RIGHT,
1156                 mean_diff + t * std_err_diff, 8, 3);
1157
1158       }
1159     }
1160 }
1161
1162 /* Initialize the paired samples trbox */
1163 void
1164 trbox_paired_init (struct trbox *self,
1165                            struct cmd_t_test *cmd UNUSED)
1166 {
1167
1168   const int hsize=10;
1169   const int vsize=n_pairs+3;
1170
1171   self->populate = trbox_paired_populate;
1172
1173   trbox_base_init (self,n_pairs,hsize);
1174   tab_title (self->t, _ ("Paired Samples Test"));
1175   tab_hline (self->t,TAL_1,2,6,1);
1176   tab_vline (self->t,TAL_2,2,0,vsize - 1);
1177   tab_joint_text (self->t,2,0,6,0,TAB_CENTER,_ ("Paired Differences"));
1178   tab_box (self->t,-1,-1,-1,TAL_1, 2,1,6,vsize-1);
1179   tab_box (self->t,-1,-1,-1,TAL_1, 6,0,hsize-1,vsize-1);
1180   tab_hline (self->t,TAL_1,5,6, 2);
1181   tab_vline (self->t,TAL_GAP,6,0,1);
1182
1183   tab_joint_text (self->t, 5, 1, 6, 1, TAB_CENTER | TAT_PRINTF,
1184                  _ ("%g%% Confidence Interval of the Difference"),
1185                  cmd->criteria*100.0);
1186
1187   tab_text (self->t, 2, 2, TAB_CENTER | TAT_TITLE, _ ("Mean"));
1188   tab_text (self->t, 3, 2, TAB_CENTER | TAT_TITLE, _ ("Std. Deviation"));
1189   tab_text (self->t, 4, 2, TAB_CENTER | TAT_TITLE, _ ("Std. Error Mean"));
1190   tab_text (self->t, 5, 2, TAB_CENTER | TAT_TITLE, _ ("Lower"));
1191   tab_text (self->t, 6, 2, TAB_CENTER | TAT_TITLE, _ ("Upper"));
1192   tab_text (self->t, 7, 2, TAB_CENTER | TAT_TITLE, _ ("t"));
1193   tab_text (self->t, 8, 2, TAB_CENTER | TAT_TITLE, _ ("df"));
1194   tab_text (self->t, 9, 2, TAB_CENTER | TAT_TITLE, _ ("Sig. (2-tailed)"));
1195 }
1196
1197 /* Populate the paired samples trbox */
1198 void
1199 trbox_paired_populate (struct trbox *trb,
1200                               struct cmd_t_test *cmd UNUSED)
1201 {
1202   int i;
1203
1204   for (i=0; i < n_pairs; ++i)
1205     {
1206       double p,q;
1207       double se_mean;
1208
1209       double n = pairs[i].n;
1210       double t;
1211       double df = n - 1;
1212
1213       tab_text (trb->t, 0, i+3, TAB_LEFT | TAT_PRINTF, _ ("Pair %d"),i);
1214
1215       tab_text (trb->t, 1, i+3, TAB_LEFT | TAT_PRINTF, "%s - %s",
1216                 var_get_name (pairs[i].v[0]),
1217                 var_get_name (pairs[i].v[1]));
1218
1219       tab_float (trb->t, 2, i+3, TAB_RIGHT, pairs[i].mean_diff, 8, 4);
1220
1221       tab_float (trb->t, 3, i+3, TAB_RIGHT, pairs[i].std_dev_diff, 8, 5);
1222
1223       /* SE Mean */
1224       se_mean = pairs[i].std_dev_diff / sqrt (n) ;
1225       tab_float (trb->t, 4, i+3, TAB_RIGHT, se_mean, 8,5 );
1226
1227       /* Now work out the confidence interval */
1228       q = (1 - cmd->criteria)/2.0;  /* 2-tailed test */
1229
1230       t = gsl_cdf_tdist_Qinv (q, df);
1231
1232       tab_float (trb->t, 5, i+3, TAB_RIGHT,
1233                 pairs[i].mean_diff - t * se_mean , 8, 4);
1234
1235       tab_float (trb->t, 6, i+3, TAB_RIGHT,
1236                 pairs[i].mean_diff + t * se_mean , 8, 4);
1237
1238       t = (pairs[i].mean[0] - pairs[i].mean[1])
1239         / sqrt (
1240                  ( pow2 (pairs[i].s_std_dev[0]) + pow2 (pairs[i].s_std_dev[1]) -
1241                   2 * pairs[i].correlation *
1242                   pairs[i].s_std_dev[0] * pairs[i].s_std_dev[1] )
1243                 / (n - 1)
1244                 );
1245
1246       tab_float (trb->t, 7, i+3, TAB_RIGHT, t , 8,3 );
1247
1248       /* Degrees of freedom */
1249       tab_float (trb->t, 8, i+3, TAB_RIGHT, df , 10, 0 );
1250
1251       p = gsl_cdf_tdist_P (t,df);
1252       q = gsl_cdf_tdist_P (t,df);
1253
1254       tab_float (trb->t, 9, i+3, TAB_RIGHT, 2.0* (t>0?q:p) , 8, 3);
1255
1256     }
1257 }
1258
1259 /* Initialize the one sample trbox */
1260 void
1261 trbox_one_sample_init (struct trbox *self, struct cmd_t_test *cmd )
1262 {
1263   const int hsize=7;
1264   const int vsize=cmd->n_variables+3;
1265
1266   self->populate = trbox_one_sample_populate;
1267
1268   trbox_base_init (self, cmd->n_variables,hsize);
1269   tab_title (self->t, _ ("One-Sample Test"));
1270   tab_hline (self->t, TAL_1, 1, hsize - 1, 1);
1271   tab_vline (self->t, TAL_2, 1, 0, vsize - 1);
1272
1273   tab_joint_text (self->t, 1, 0, hsize-1,0, TAB_CENTER | TAT_PRINTF,
1274                  _ ("Test Value = %f"), cmd->n_testval[0]);
1275
1276   tab_box (self->t, -1, -1, -1, TAL_1, 1,1,hsize-1,vsize-1);
1277
1278
1279   tab_joint_text (self->t,5,1,6,1,TAB_CENTER  | TAT_PRINTF,
1280                  _ ("%g%% Confidence Interval of the Difference"),
1281                  cmd->criteria*100.0);
1282
1283   tab_vline (self->t,TAL_GAP,6,1,1);
1284   tab_hline (self->t,TAL_1,5,6,2);
1285   tab_text (self->t, 1, 2, TAB_CENTER | TAT_TITLE, _ ("t"));
1286   tab_text (self->t, 2, 2, TAB_CENTER | TAT_TITLE, _ ("df"));
1287   tab_text (self->t, 3, 2, TAB_CENTER | TAT_TITLE, _ ("Sig. (2-tailed)"));
1288   tab_text (self->t, 4, 2, TAB_CENTER | TAT_TITLE, _ ("Mean Difference"));
1289   tab_text (self->t, 5, 2, TAB_CENTER | TAT_TITLE, _ ("Lower"));
1290   tab_text (self->t, 6, 2, TAB_CENTER | TAT_TITLE, _ ("Upper"));
1291
1292 }
1293
1294
1295 /* Populate the one sample trbox */
1296 void
1297 trbox_one_sample_populate (struct trbox *trb, struct cmd_t_test *cmd)
1298 {
1299   int i;
1300
1301   assert (trb->t);
1302
1303   for (i=0; i < cmd->n_variables; ++i)
1304     {
1305       double t;
1306       double p,q;
1307       double df;
1308       struct group_statistics *gs = &group_proc_get (cmd->v_variables[i])->ugs;
1309
1310
1311       tab_text (trb->t, 0, i+3, TAB_LEFT, var_get_name (cmd->v_variables[i]));
1312
1313       t = (gs->mean - cmd->n_testval[0] ) * sqrt (gs->n) / gs->std_dev ;
1314
1315       tab_float (trb->t, 1, i+3, TAB_RIGHT, t, 8,3);
1316
1317       /* degrees of freedom */
1318       df = gs->n - 1;
1319
1320       tab_float (trb->t, 2, i+3, TAB_RIGHT, df, 8,0);
1321
1322       p = gsl_cdf_tdist_P (t, df);
1323       q = gsl_cdf_tdist_Q (t, df);
1324
1325       /* Multiply by 2 to get 2-tailed significance, makeing sure we've got
1326          the correct tail*/
1327       tab_float (trb->t, 3, i+3, TAB_RIGHT, 2.0* (t>0?q:p), 8,3);
1328
1329       tab_float (trb->t, 4, i+3, TAB_RIGHT, gs->mean_diff, 8,3);
1330
1331
1332       q = (1 - cmd->criteria)/2.0;  /* 2-tailed test */
1333       t = gsl_cdf_tdist_Qinv (q, df);
1334
1335       tab_float (trb->t, 5, i+3, TAB_RIGHT,
1336                  gs->mean_diff - t * gs->se_mean, 8,4);
1337
1338       tab_float (trb->t, 6, i+3, TAB_RIGHT,
1339                  gs->mean_diff + t * gs->se_mean, 8,4);
1340     }
1341 }
1342
1343 /* Base initializer for the generalized trbox */
1344 void
1345 trbox_base_init (struct trbox *self, size_t data_rows, int cols)
1346 {
1347   const size_t rows = 3 + data_rows;
1348
1349   self->finalize = trbox_base_finalize;
1350   self->t = tab_create (cols, rows, 0);
1351   tab_headers (self->t,0,0,3,0);
1352   tab_box (self->t, TAL_2, TAL_2, TAL_0, TAL_0, 0, 0, cols -1, rows -1);
1353   tab_hline (self->t, TAL_2,0,cols-1,3);
1354   tab_dim (self->t, tab_natural_dimensions);
1355 }
1356
1357
1358 /* Base finalizer for the trbox */
1359 void
1360 trbox_base_finalize (struct trbox *trb)
1361 {
1362   tab_submit (trb->t);
1363 }
1364
1365
1366 /* Create , populate and submit the Paired Samples Correlation box */
1367 void
1368 pscbox (void)
1369 {
1370   const int rows=1+n_pairs;
1371   const int cols=5;
1372   int i;
1373
1374   struct tab_table *table;
1375
1376   table = tab_create (cols,rows,0);
1377
1378   tab_columns (table, SOM_COL_DOWN, 1);
1379   tab_headers (table,0,0,1,0);
1380   tab_box (table, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, cols -1, rows -1 );
1381   tab_hline (table, TAL_2, 0, cols - 1, 1);
1382   tab_vline (table, TAL_2, 2, 0, rows - 1);
1383   tab_dim (table, tab_natural_dimensions);
1384   tab_title (table, _ ("Paired Samples Correlations"));
1385
1386   /* column headings */
1387   tab_text (table, 2,0, TAB_CENTER | TAT_TITLE, _ ("N"));
1388   tab_text (table, 3,0, TAB_CENTER | TAT_TITLE, _ ("Correlation"));
1389   tab_text (table, 4,0, TAB_CENTER | TAT_TITLE, _ ("Sig."));
1390
1391   for (i=0; i < n_pairs; ++i)
1392     {
1393       double p,q;
1394
1395       double df = pairs[i].n -2;
1396
1397       double correlation_t =
1398         pairs[i].correlation * sqrt (df) /
1399         sqrt (1 - pow2 (pairs[i].correlation));
1400
1401
1402       /* row headings */
1403       tab_text (table, 0,i+1, TAB_LEFT | TAT_TITLE | TAT_PRINTF,
1404                _ ("Pair %d"), i);
1405
1406       tab_text (table, 1,i+1, TAB_LEFT | TAT_TITLE | TAT_PRINTF,
1407                _ ("%s & %s"),
1408                var_get_name (pairs[i].v[0]),
1409                var_get_name (pairs[i].v[1]));
1410
1411
1412       /* row data */
1413       tab_float (table, 2, i+1, TAB_RIGHT, pairs[i].n, 4, 0);
1414       tab_float (table, 3, i+1, TAB_RIGHT, pairs[i].correlation, 8, 3);
1415
1416       p = gsl_cdf_tdist_P (correlation_t, df);
1417       q = gsl_cdf_tdist_Q (correlation_t, df);
1418
1419       tab_float (table, 4, i+1, TAB_RIGHT, 2.0* (correlation_t>0?q:p), 8, 3);
1420     }
1421
1422   tab_submit (table);
1423 }
1424
1425
1426
1427
1428 /* Calculation Implementation */
1429
1430 /* Per case calculations common to all variants of the T test */
1431 static int
1432 common_calc (const struct dictionary *dict,
1433              const struct ccase *c,
1434              void *_cmd,
1435              enum mv_class exclude)
1436 {
1437   int i;
1438   struct cmd_t_test *cmd = (struct cmd_t_test *)_cmd;
1439
1440   double weight = dict_get_case_weight (dict, c, NULL);
1441
1442
1443   /* Listwise has to be implicit if the independent variable is missing ?? */
1444   if ( cmd->sbc_groups )
1445     {
1446       if (var_is_value_missing (indep_var, case_data (c, indep_var), exclude))
1447         return 0;
1448     }
1449
1450   for (i = 0; i < cmd->n_variables ; ++i)
1451     {
1452       const struct variable *v = cmd->v_variables[i];
1453       const union value *val = case_data (c, v);
1454
1455       if (!var_is_value_missing (v, val, exclude))
1456         {
1457           struct group_statistics *gs;
1458           gs = &group_proc_get (v)->ugs;
1459
1460           gs->n += weight;
1461           gs->sum += weight * val->f;
1462           gs->ssq += weight * val->f * val->f;
1463         }
1464     }
1465   return 0;
1466 }
1467
1468 /* Pre calculations common to all variants of the T test */
1469 static void
1470 common_precalc ( struct cmd_t_test *cmd )
1471 {
1472   int i=0;
1473
1474   for (i=0; i< cmd->n_variables ; ++i)
1475     {
1476       struct group_statistics *gs;
1477       gs= &group_proc_get (cmd->v_variables[i])->ugs;
1478
1479       gs->sum=0;
1480       gs->n=0;
1481       gs->ssq=0;
1482       gs->sum_diff=0;
1483     }
1484 }
1485
1486 /* Post calculations common to all variants of the T test */
1487 void
1488 common_postcalc (struct cmd_t_test *cmd)
1489 {
1490   int i=0;
1491
1492   for (i=0; i< cmd->n_variables ; ++i)
1493     {
1494       struct group_statistics *gs;
1495       gs= &group_proc_get (cmd->v_variables[i])->ugs;
1496
1497       gs->mean=gs->sum / gs->n;
1498       gs->s_std_dev= sqrt (
1499                          ( (gs->ssq / gs->n ) - gs->mean * gs->mean )
1500                          ) ;
1501
1502       gs->std_dev= sqrt (
1503                          gs->n/ (gs->n-1) *
1504                          ( (gs->ssq / gs->n ) - gs->mean * gs->mean )
1505                          ) ;
1506
1507       gs->se_mean = gs->std_dev / sqrt (gs->n);
1508       gs->mean_diff= gs->sum_diff / gs->n;
1509     }
1510 }
1511
1512 /* Per case calculations for one sample t test  */
1513 static int
1514 one_sample_calc (const struct dictionary *dict,
1515                  const struct ccase *c, void *cmd_,
1516                  enum mv_class exclude)
1517 {
1518   int i;
1519
1520   struct cmd_t_test *cmd = (struct cmd_t_test *)cmd_;
1521
1522   double weight = dict_get_case_weight (dict, c, NULL);
1523
1524
1525   for (i=0; i< cmd->n_variables ; ++i)
1526     {
1527       struct group_statistics *gs;
1528       const struct variable *v = cmd->v_variables[i];
1529       const union value *val = case_data (c, v);
1530
1531       gs= &group_proc_get (cmd->v_variables[i])->ugs;
1532
1533       if (!var_is_value_missing (v, val, exclude))
1534         gs->sum_diff += weight * (val->f - cmd->n_testval[0]);
1535     }
1536
1537   return 0;
1538 }
1539
1540 /* Pre calculations for one sample t test */
1541 static void
1542 one_sample_precalc ( struct cmd_t_test *cmd )
1543 {
1544   int i=0;
1545
1546   for (i=0; i< cmd->n_variables ; ++i)
1547     {
1548       struct group_statistics *gs;
1549       gs= &group_proc_get (cmd->v_variables[i])->ugs;
1550
1551       gs->sum_diff=0;
1552     }
1553 }
1554
1555 /* Post calculations for one sample t test */
1556 static void
1557 one_sample_postcalc (struct cmd_t_test *cmd)
1558 {
1559   int i=0;
1560
1561   for (i=0; i< cmd->n_variables ; ++i)
1562     {
1563       struct group_statistics *gs;
1564       gs= &group_proc_get (cmd->v_variables[i])->ugs;
1565
1566       gs->mean_diff = gs->sum_diff / gs->n ;
1567     }
1568 }
1569
1570
1571
1572 static void
1573 paired_precalc (struct cmd_t_test *cmd UNUSED)
1574 {
1575   int i;
1576
1577   for (i=0; i < n_pairs ; ++i )
1578     {
1579       pairs[i].n = 0;
1580       pairs[i].sum[0] = 0;      pairs[i].sum[1] = 0;
1581       pairs[i].ssq[0] = 0;      pairs[i].ssq[1] = 0;
1582       pairs[i].sum_of_prod = 0;
1583       pairs[i].correlation = 0;
1584       pairs[i].sum_of_diffs = 0;
1585       pairs[i].ssq_diffs = 0;
1586     }
1587
1588 }
1589
1590
1591 static int
1592 paired_calc (const struct dictionary *dict, const struct ccase *c,
1593              struct cmd_t_test *cmd UNUSED, enum mv_class exclude)
1594 {
1595   int i;
1596
1597   double weight = dict_get_case_weight (dict, c, NULL);
1598
1599   for (i=0; i < n_pairs ; ++i )
1600     {
1601       const struct variable *v0 = pairs[i].v[0];
1602       const struct variable *v1 = pairs[i].v[1];
1603
1604       const union value *val0 = case_data (c, v0);
1605       const union value *val1 = case_data (c, v1);
1606
1607       if (!var_is_value_missing (v0, val0, exclude) &&
1608           !var_is_value_missing (v1, val1, exclude))
1609         {
1610           pairs[i].n += weight;
1611           pairs[i].sum[0] += weight * val0->f;
1612           pairs[i].sum[1] += weight * val1->f;
1613
1614           pairs[i].ssq[0] += weight * pow2 (val0->f);
1615           pairs[i].ssq[1] += weight * pow2 (val1->f);
1616
1617           pairs[i].sum_of_prod += weight * val0->f * val1->f ;
1618
1619           pairs[i].sum_of_diffs += weight * ( val0->f - val1->f ) ;
1620           pairs[i].ssq_diffs += weight * pow2 (val0->f - val1->f);
1621         }
1622     }
1623
1624   return 0;
1625 }
1626
1627 static void
1628 paired_postcalc (struct cmd_t_test *cmd UNUSED)
1629 {
1630   int i;
1631
1632   for (i=0; i < n_pairs ; ++i )
1633     {
1634       int j;
1635       const double n = pairs[i].n;
1636
1637       for (j=0; j < 2 ; ++j)
1638         {
1639           pairs[i].mean[j] = pairs[i].sum[j] / n ;
1640           pairs[i].s_std_dev[j] = sqrt ((pairs[i].ssq[j] / n -
1641                                               pow2 (pairs[i].mean[j]))
1642                                      );
1643
1644           pairs[i].std_dev[j] = sqrt (n/ (n-1)* (pairs[i].ssq[j] / n -
1645                                               pow2 (pairs[i].mean[j]))
1646                                      );
1647         }
1648
1649       pairs[i].correlation = pairs[i].sum_of_prod / pairs[i].n -
1650         pairs[i].mean[0] * pairs[i].mean[1] ;
1651       /* correlation now actually contains the covariance */
1652
1653       pairs[i].correlation /= pairs[i].std_dev[0] * pairs[i].std_dev[1];
1654       pairs[i].correlation *= pairs[i].n / ( pairs[i].n - 1 );
1655
1656       pairs[i].mean_diff = pairs[i].sum_of_diffs / n ;
1657
1658       pairs[i].std_dev_diff = sqrt (  n / (n - 1) * (
1659                                     ( pairs[i].ssq_diffs / n )
1660                                     -
1661                                     pow2 (pairs[i].mean_diff )
1662                                     ) );
1663     }
1664 }
1665
1666 static void
1667 group_precalc (struct cmd_t_test *cmd )
1668 {
1669   int i;
1670   int j;
1671
1672   for (i=0; i< cmd->n_variables ; ++i)
1673     {
1674       struct group_proc *ttpr = group_proc_get (cmd->v_variables[i]);
1675
1676       /* There's always 2 groups for a T - TEST */
1677       ttpr->n_groups = 2;
1678
1679       gp.indep_width = var_get_width (indep_var);
1680
1681       ttpr->group_hash = hsh_create (2,
1682                                     (hsh_compare_func *) compare_group_binary,
1683                                     (hsh_hash_func *) hash_group_binary,
1684                                     (hsh_free_func *) free_group,
1685                                     (void *) &gp );
1686
1687       for (j=0 ; j < 2 ; ++j)
1688         {
1689           struct group_statistics *gs = xmalloc (sizeof *gs);
1690
1691           gs->sum = 0;
1692           gs->n = 0;
1693           gs->ssq = 0;
1694
1695           if ( gp.criterion == CMP_EQ )
1696             {
1697               gs->id = gp.v.g_value[j];
1698             }
1699           else
1700             {
1701               if ( j == 0 )
1702                 gs->id.f = gp.v.critical_value - 1.0 ;
1703               else
1704                 gs->id.f = gp.v.critical_value + 1.0 ;
1705             }
1706
1707           hsh_insert ( ttpr->group_hash, (void *) gs );
1708         }
1709     }
1710
1711 }
1712
1713 static int
1714 group_calc (const struct dictionary *dict,
1715             const struct ccase *c, struct cmd_t_test *cmd,
1716             enum mv_class exclude)
1717 {
1718   int i;
1719
1720   const double weight = dict_get_case_weight (dict, c, NULL);
1721
1722   const union value *gv;
1723
1724   if (var_is_value_missing (indep_var, case_data (c, indep_var), exclude))
1725     return 0;
1726
1727   gv = case_data (c, indep_var);
1728
1729   for (i=0; i< cmd->n_variables ; ++i)
1730     {
1731       const struct variable *var = cmd->v_variables[i];
1732       const union value *val = case_data (c, var);
1733       struct hsh_table *grp_hash = group_proc_get (var)->group_hash;
1734       struct group_statistics *gs;
1735
1736       gs = hsh_find (grp_hash, (void *) gv);
1737
1738       /* If the independent variable doesn't match either of the values
1739          for this case then move on to the next case */
1740       if ( ! gs )
1741         return 0;
1742
1743       if (!var_is_value_missing (var, val, exclude))
1744         {
1745           gs->n += weight;
1746           gs->sum += weight * val->f;
1747           gs->ssq += weight * pow2 (val->f);
1748         }
1749     }
1750
1751   return 0;
1752 }
1753
1754
1755 static void
1756 group_postcalc ( struct cmd_t_test *cmd )
1757 {
1758   int i;
1759
1760   for (i = 0; i < cmd->n_variables ; ++i)
1761     {
1762       const struct variable *var = cmd->v_variables[i];
1763       struct hsh_table *grp_hash = group_proc_get (var)->group_hash;
1764       struct hsh_iterator g;
1765       struct group_statistics *gs;
1766       int count=0;
1767
1768       for (gs =  hsh_first (grp_hash,&g);
1769            gs != 0;
1770            gs = hsh_next (grp_hash,&g))
1771         {
1772           gs->mean = gs->sum / gs->n;
1773
1774           gs->s_std_dev= sqrt (
1775                               ( (gs->ssq / gs->n ) - gs->mean * gs->mean )
1776                               ) ;
1777
1778           gs->std_dev= sqrt (
1779                             gs->n/ (gs->n-1) *
1780                             ( (gs->ssq / gs->n ) - gs->mean * gs->mean )
1781                             ) ;
1782
1783           gs->se_mean = gs->std_dev / sqrt (gs->n);
1784           count ++;
1785         }
1786       assert (count == 2);
1787     }
1788 }
1789
1790
1791
1792 static void
1793 calculate (struct cmd_t_test *cmd,
1794           struct casereader *input, const struct dataset *ds)
1795 {
1796   const struct dictionary *dict = dataset_dict (ds);
1797   struct ssbox stat_summary_box;
1798   struct trbox test_results_box;
1799
1800   struct casereader *pass1, *pass2, *pass3;
1801   struct taint *taint;
1802   struct ccase c;
1803
1804   enum mv_class exclude = cmd->miss != TTS_INCLUDE ? MV_ANY : MV_SYSTEM;
1805
1806   if (!casereader_peek (input, 0, &c))
1807     {
1808       casereader_destroy (input);
1809       return;
1810     }
1811   output_split_file_values (ds, &c);
1812   case_destroy (&c);
1813
1814   if ( cmd->miss == TTS_LISTWISE )
1815     input = casereader_create_filter_missing (input,
1816                                               cmd->v_variables,
1817                                               cmd->n_variables,
1818                                               exclude, NULL, NULL);
1819
1820   input = casereader_create_filter_weight (input, dict, NULL, NULL);
1821
1822   taint = taint_clone (casereader_get_taint (input));
1823   casereader_split (input, &pass1, &pass2);
1824
1825   common_precalc (cmd);
1826   for (; casereader_read (pass1, &c); case_destroy (&c))
1827     common_calc (dict, &c, cmd, exclude);
1828   casereader_destroy (pass1);
1829   common_postcalc (cmd);
1830
1831   switch (mode)
1832     {
1833     case T_1_SAMPLE:
1834       one_sample_precalc (cmd);
1835       for (; casereader_read (pass2, &c); case_destroy (&c))
1836         one_sample_calc (dict, &c, cmd, exclude);
1837       one_sample_postcalc (cmd);
1838       break;
1839     case T_PAIRED:
1840       paired_precalc (cmd);
1841       for (; casereader_read (pass2, &c); case_destroy (&c))
1842         paired_calc (dict, &c, cmd, exclude);
1843       paired_postcalc (cmd);
1844       break;
1845     case T_IND_SAMPLES:
1846       pass3 = casereader_clone (pass2);
1847
1848       group_precalc (cmd);
1849       for (; casereader_read (pass2, &c); case_destroy (&c))
1850         group_calc (dict, &c, cmd, exclude);
1851       group_postcalc (cmd);
1852
1853       levene (dict, pass3, indep_var, cmd->n_variables, cmd->v_variables,
1854               exclude);
1855       break;
1856     }
1857   casereader_destroy (pass2);
1858
1859   if (!taint_has_tainted_successor (taint))
1860     {
1861       ssbox_create (&stat_summary_box,cmd,mode);
1862       ssbox_populate (&stat_summary_box,cmd);
1863       ssbox_finalize (&stat_summary_box);
1864
1865       if ( mode == T_PAIRED )
1866         pscbox ();
1867
1868       trbox_create (&test_results_box,cmd,mode);
1869       trbox_populate (&test_results_box,cmd);
1870       trbox_finalize (&test_results_box);
1871     }
1872
1873   taint_destroy (taint);
1874 }
1875
1876 short which_group (const struct group_statistics *g,
1877                   const struct group_properties *p);
1878
1879 /* Return -1 if the id of a is less than b; +1 if greater than and
1880    0 if equal */
1881 static int
1882 compare_group_binary (const struct group_statistics *a,
1883                      const struct group_statistics *b,
1884                      const struct group_properties *p)
1885 {
1886   short flag_a;
1887   short flag_b;
1888
1889   if ( p->criterion == CMP_LE )
1890     {
1891       /* less-than comparision is not meaningfull for
1892          alpha variables, so we shouldn't ever arrive here */
1893       assert (p->indep_width == 0 ) ;
1894
1895       flag_a = ( a->id.f < p->v.critical_value ) ;
1896       flag_b = ( b->id.f < p->v.critical_value ) ;
1897     }
1898   else
1899     {
1900       flag_a = which_group (a, p);
1901       flag_b = which_group (b, p);
1902     }
1903
1904   if (flag_a < flag_b )
1905     return -1;
1906
1907   return (flag_a > flag_b);
1908 }
1909
1910 /* This is a degenerate case of a hash, since it can only return three possible
1911    values.  It's really a comparison, being used as a hash function */
1912
1913 static unsigned
1914 hash_group_binary (const struct group_statistics *g,
1915                   const struct group_properties *p)
1916 {
1917   short flag = -1;
1918
1919   if ( p->criterion == CMP_LE )
1920     {
1921       /* Not meaningfull to do a less than compare for alpha values ? */
1922       assert (p->indep_width == 0 ) ;
1923       flag = ( g->id.f < p->v.critical_value ) ;
1924     }
1925   else if ( p->criterion == CMP_EQ)
1926     {
1927       flag = which_group (g,p);
1928     }
1929   else
1930     NOT_REACHED ();
1931
1932   return flag;
1933 }
1934
1935 /* return 0 if G belongs to group 0,
1936           1 if it belongs to group 1,
1937           2 if it belongs to neither group */
1938 short
1939 which_group (const struct group_statistics *g,
1940             const struct group_properties *p)
1941 {
1942   if ( 0 == compare_values (&g->id, &p->v.g_value[0], p->indep_width))
1943     return 0;
1944
1945   if ( 0 == compare_values (&g->id, &p->v.g_value[1], p->indep_width))
1946     return 1;
1947
1948   return 2;
1949 }
1950
1951 /*
1952   Local Variables:
1953   mode: c
1954   End:
1955 */