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