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