Implemented calculations for the paired samples t-test
[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 <assert.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
27 #include "alloc.h"
28 #include "str.h"
29 #include "dcdflib/cdflib.h"
30 #include "command.h"
31 #include "lexer.h"
32 #include "error.h"
33 #include "magic.h"
34 #include "tab.h"
35 #include "som.h"
36 #include "value-labels.h"
37 #include "var.h"
38 #include "vfm.h"
39 #include "pool.h"
40 #include "hash.h"
41 #include "stats.h"
42
43 /* (specification)
44    "T-TEST" (tts_):
45      groups=custom;
46      testval=double;
47      variables=varlist("PV_NO_SCRATCH | PV_NUMERIC");
48      pairs=custom;
49      +missing=miss:!analysis/listwise,
50              incl:include/!exclude;
51      format=fmt:!labels/nolabels;
52      criteria=:cin(d:criteria,"%s > 0. && %s < 1.").
53 */
54 /* (declarations) */
55 /* (functions) */
56
57 static struct cmd_t_test cmd;
58
59
60
61 static struct pool *t_test_pool ;
62
63 /* Variable for the GROUPS subcommand, if given. */
64 static struct variable *groups;
65
66 /* GROUPS: Number of values specified by the user; the values
67    specified if any. */
68 static int n_groups_values;
69 static union value groups_values[2];
70
71 /* PAIRS: Number of pairs to be compared ; each pair. */
72 static int n_pairs ;
73 struct pair 
74 {
75   /* The variables comprising the pair */
76   struct variable *v[2];
77
78   /* The correlation coefficient between the variables */
79   double correlation;
80
81   /* The sum of the differences */
82   double sum_of_diffs;
83
84   /* The mean of the differences */
85   double mean_diff;
86
87   /* The sum of the squares of the differences */
88   double ssq_diffs;
89
90   /* The std deviation of the differences */
91   double std_dev_diff;
92 };
93 static struct pair *pairs;
94
95
96 static int parse_value (union value * v, int type) ;
97
98
99 /* Structures and Functions for the Statistics Summary Box */
100 struct ssbox;
101 typedef void populate_ssbox_func(struct ssbox *ssb,
102                                             struct cmd_t_test *cmd);
103 typedef void finalize_ssbox_func(struct ssbox *ssb);
104
105 struct ssbox
106 {
107   struct tab_table *t;
108
109   populate_ssbox_func *populate;
110   finalize_ssbox_func *finalize;
111
112 };
113
114 /* Create a ssbox */
115 void ssbox_create(struct ssbox *ssb,   struct cmd_t_test *cmd, int mode);
116
117 /* Populate a ssbox according to cmd */
118 void ssbox_populate(struct ssbox *ssb, struct cmd_t_test *cmd);
119
120 /* Submit and destroy a ssbox */
121 void ssbox_finalize(struct ssbox *ssb);
122
123 /* A function to create, populate and submit the Paired Samples Correlation 
124    box */
125 void pscbox(struct cmd_t_test *cmd);
126
127
128 /* Structures and Functions for the Test Results Box */
129 struct trbox;
130
131 typedef void populate_trbox_func(struct trbox *trb,
132                                  struct cmd_t_test *cmd);
133 typedef void finalize_trbox_func(struct trbox *trb);
134
135 struct trbox {
136   struct tab_table *t;
137   populate_trbox_func *populate;
138   finalize_trbox_func *finalize;
139 };
140
141 /* Create a trbox */
142 void trbox_create(struct trbox *trb,   struct cmd_t_test *cmd, int mode);
143
144 /* Populate a ssbox according to cmd */
145 void trbox_populate(struct trbox *trb, struct cmd_t_test *cmd);
146
147 /* Submit and destroy a ssbox */
148 void trbox_finalize(struct trbox *trb);
149
150 /* Which mode was T-TEST invoked */
151 enum {
152   T_1_SAMPLE = 0 ,
153   T_IND_SAMPLES, 
154   T_PAIRED
155 };
156
157
158 static int common_calc (struct ccase *);
159 static void common_precalc (void);
160 static void common_postcalc (void);
161
162 static int one_sample_calc (struct ccase *);
163 static void one_sample_precalc (void);
164 static void one_sample_postcalc (void);
165
166 static int  paired_calc (struct ccase *);
167 static void paired_precalc (void);
168 static void paired_postcalc (void);
169
170 static int compare_var_name (const void *a_, const void *b_, void *v_ unused);
171 static unsigned hash_var_name (const void *a_, void *v_ unused);
172
173
174 int
175 cmd_t_test(void)
176 {
177   int mode;
178
179   struct ssbox stat_summary_box;
180   struct trbox test_results_box;
181
182   if (!lex_force_match_id ("T"))
183     return CMD_FAILURE;
184
185   lex_match ('-');
186   lex_match_id ("TEST");
187
188   if ( !parse_t_test(&cmd) )
189     return CMD_FAILURE;
190
191   if (! cmd.sbc_criteria)
192     cmd.criteria=0.95;
193
194   if ( cmd.sbc_testval + cmd.sbc_groups + cmd.sbc_pairs != 1 ) 
195     {
196       msg(SE, 
197           _("Exactly one of TESTVAL, GROUPS or PAIRS subcommands is required")
198           );
199       return CMD_FAILURE;
200     }
201
202   if (cmd.sbc_testval) 
203     mode=T_1_SAMPLE;
204   else if (cmd.sbc_groups)
205     mode=T_IND_SAMPLES;
206   else
207     mode=T_PAIRED;
208
209   if ( mode == T_PAIRED) 
210     {
211       if (cmd.sbc_variables) 
212         {
213           msg(SE, _("VARIABLES subcommand is not appropriate with PAIRS"));
214           return CMD_FAILURE;
215         }
216       else
217         {
218           /* Iterate through the pairs and put each variable that is a 
219              member of a pair into cmd.v_variables */
220
221           int i;
222           struct hsh_iterator hi;
223           struct hsh_table *hash;
224           struct variable *v;
225
226           hash=hsh_create(n_pairs,compare_var_name,hash_var_name,0,0);
227
228           for (i=0; i < n_pairs; ++i)
229             {
230               hsh_insert(hash,pairs[i].v[0]);
231               hsh_insert(hash,pairs[i].v[1]);
232             }
233
234           assert(cmd.n_variables == 0);
235           cmd.n_variables = hsh_count(hash);
236
237           cmd.v_variables = xrealloc(cmd.v_variables,
238                                      sizeof(struct variable) * cmd.n_variables);
239           /* Iterate through the hash */
240           for (i=0,v = (struct variable *) hsh_first(hash,&hi);
241                v != 0;
242                v=hsh_next(hash,&hi) ) 
243             cmd.v_variables[i++]=v;
244
245           hsh_destroy(hash);
246         }
247     }
248
249
250   procedure(common_precalc,common_calc,common_postcalc);
251
252   switch(mode)
253     {
254     case T_1_SAMPLE:
255       procedure(one_sample_precalc,one_sample_calc,one_sample_postcalc);
256       break;
257     case T_PAIRED:
258       procedure(paired_precalc,paired_calc,paired_postcalc);
259       break;
260     }
261   
262
263   t_test_pool = pool_create ();
264
265   ssbox_create(&stat_summary_box,&cmd,mode);
266   ssbox_populate(&stat_summary_box,&cmd);
267   ssbox_finalize(&stat_summary_box);
268
269   if ( mode == T_PAIRED) 
270     {
271       pscbox(&cmd);
272     }
273
274   trbox_create(&test_results_box,&cmd,mode);
275   trbox_populate(&test_results_box,&cmd);
276   trbox_finalize(&test_results_box);
277
278   pool_destroy (t_test_pool);
279
280   t_test_pool=0;
281     
282   return CMD_SUCCESS;
283 }
284
285 static int
286 tts_custom_groups (struct cmd_t_test *cmd unused)
287 {
288   lex_match('=');
289
290   if (token != T_ALL && 
291       (token != T_ID || dict_lookup_var (default_dict, tokid) == NULL)
292      ) 
293   {
294     msg(SE,_("`%s' is not a variable name"),tokid);
295     return 0;
296   }
297
298   groups = parse_variable ();
299   if (!groups)
300     {
301       lex_error ("expecting variable name in GROUPS subcommand");
302       return 0;
303     }
304
305   if (groups->type == T_STRING && groups->width > MAX_SHORT_STRING)
306     {
307       msg (SE, _("Long string variable %s is not valid here."),
308            groups->name);
309       return 0;
310     }
311
312   if (!lex_match ('('))
313     {
314       if (groups->type == NUMERIC)
315         {
316           n_groups_values = 2;
317           groups_values[0].f = 1;
318           groups_values[1].f = 2;
319           return 1;
320         }
321       else
322         {
323           msg (SE, _("When applying GROUPS to a string variable, at "
324                      "least one value must be specified."));
325           return 0;
326         }
327     }
328
329   if (!parse_value (&groups_values[0],groups->type))
330     return 0;
331   n_groups_values = 1;
332
333   lex_match (',');
334   if (lex_match (')'))
335     return 1;
336
337   if (!parse_value (&groups_values[1],groups->type))
338     return 0;
339   n_groups_values = 2;
340
341   if (!lex_force_match (')'))
342     return 0;
343
344   return 1;
345 }
346
347
348
349
350 static int
351 tts_custom_pairs (struct cmd_t_test *cmd unused)
352 {
353   struct variable **vars;
354   int n_vars;
355
356   int n_before_WITH ;
357   int n_after_WITH = -1;
358   int paired ; /* Was the PAIRED keyword given ? */
359
360   lex_match('=');
361
362   if ((token != T_ID || dict_lookup_var (default_dict, tokid) == NULL)
363       && token != T_ALL)
364     {
365       msg(SE,_("`%s' is not a variable name"),tokid);
366       return 0;
367     }
368
369   n_vars=0;
370   if (!parse_variables (default_dict, &vars, &n_vars,
371                         PV_DUPLICATE | PV_NUMERIC | PV_NO_SCRATCH))
372     {
373       free (vars);
374       return 0;
375     }
376   assert (n_vars);
377
378   n_before_WITH=0;
379   if (lex_match (T_WITH))
380     {
381       n_before_WITH = n_vars;
382       if (!parse_variables (default_dict, &vars, &n_vars,
383                             PV_DUPLICATE | PV_APPEND
384                             | PV_NUMERIC | PV_NO_SCRATCH))
385         {
386           free (vars);
387           return 0;
388         }
389       n_after_WITH = n_vars - n_before_WITH;
390     }
391
392   paired = (lex_match ('(') && lex_match_id ("PAIRED") && lex_match (')'));
393
394   /* Determine the number of pairs needed */
395   if (paired)
396     {
397       if (n_before_WITH != n_after_WITH)
398         {
399           free (vars);
400           msg (SE, _("PAIRED was specified but the number of variables "
401                      "preceding WITH (%d) did not match the number "
402                      "following (%d)."),
403                n_before_WITH, n_after_WITH );
404           return 0;
405         }
406       n_pairs=n_before_WITH;
407     }
408   else if (n_before_WITH > 0) /* WITH keyword given, but not PAIRED keyword */
409     {
410       n_pairs=n_before_WITH * n_after_WITH ;
411     }
412   else /* Neither WITH nor PAIRED keyword given */
413     {
414       if (n_vars < 2)
415         {
416           free (vars);
417           msg (SE, _("At least two variables must be specified "
418                      "on PAIRS."));
419           return 0;
420         }
421
422       /* how many ways can you pick 2 from n_vars ? */
423       n_pairs = n_vars * (n_vars -1 ) /2 ;
424     }
425
426   /* Allocate storage for the pairs */
427   pairs = xrealloc(pairs,sizeof(struct pair) *n_pairs);
428
429   /* Populate the pairs with the appropriate variables */
430   if ( paired ) 
431     {
432       int i;
433
434       assert(n_pairs == n_vars/2);
435       for (i = 0; i < n_pairs ; ++i)
436         {
437           pairs[i].v[0] = vars[i];
438           pairs[i].v[1] = vars[i+n_pairs];
439         }
440     }
441   else if (n_before_WITH > 0) /* WITH keyword given, but not PAIRED keyword */
442     {
443       int i,j;
444       int p=0;
445
446       for(i=0 ; i < n_before_WITH ; ++i ) 
447         {
448           for(j=0 ; j < n_after_WITH ; ++j)
449             {
450               pairs[p].v[0] = vars[i];
451               pairs[p].v[1] = vars[j+n_before_WITH];
452               ++p;
453             }
454         }
455     }
456   else /* Neither WITH nor PAIRED given */
457     {
458       int i,j;
459       int p=0;
460       
461       for(i=0 ; i < n_vars ; ++i ) 
462         {
463           for(j=i+1 ; j < n_vars ; ++j)
464             {
465               pairs[p].v[0] = vars[i];
466               pairs[p].v[1] = vars[j];
467               ++p;
468             }
469         }
470     }
471
472   return 1;
473 }
474
475 /* Parses the current token (numeric or string, depending on type)
476     value v and returns success. */
477 static int
478 parse_value (union value * v, int type )
479 {
480   if (type == NUMERIC)
481     {
482       if (!lex_force_num ())
483         return 0;
484       v->f = tokval;
485     }
486   else
487     {
488       if (!lex_force_string ())
489         return 0;
490       strncpy (v->s, ds_value (&tokstr), ds_length (&tokstr));
491     }
492
493   lex_get ();
494
495   return 1;
496 }
497
498
499 /* Implementation of the SSBOX object */
500
501 void ssbox_base_init(struct ssbox *this, int cols,int rows);
502
503 void ssbox_base_finalize(struct ssbox *ssb);
504
505 void ssbox_one_sample_init(struct ssbox *this, 
506                            struct cmd_t_test *cmd );
507
508 void ssbox_independent_samples_init(struct ssbox *this,
509                                     struct cmd_t_test *cmd);
510
511 void ssbox_paired_init(struct ssbox *this,
512                            struct cmd_t_test *cmd);
513
514 /* Factory to create an ssbox */
515 void 
516 ssbox_create(struct ssbox *ssb, struct cmd_t_test *cmd, int mode)
517 {
518     switch (mode) 
519       {
520       case T_1_SAMPLE:
521         ssbox_one_sample_init(ssb,cmd);
522         break;
523       case T_IND_SAMPLES:
524         ssbox_independent_samples_init(ssb,cmd);
525         break;
526       case T_PAIRED:
527         ssbox_paired_init(ssb,cmd);
528         break;
529       default:
530         assert(0);
531       }
532 }
533
534
535 /* Despatcher for the populate method */
536 void
537 ssbox_populate(struct ssbox *ssb,struct cmd_t_test *cmd)
538 {
539   ssb->populate(ssb,cmd);
540 }
541
542
543 /* Despatcher for finalize */
544 void
545 ssbox_finalize(struct ssbox *ssb)
546 {
547   ssb->finalize(ssb);
548 }
549
550
551 /* Submit the box and clear up */
552 void 
553 ssbox_base_finalize(struct ssbox *ssb)
554 {
555   tab_submit(ssb->t);
556 }
557
558 /* Initialize a ssbox struct */
559 void 
560 ssbox_base_init(struct ssbox *this, int cols,int rows)
561 {
562   this->finalize = ssbox_base_finalize;
563   this->t = tab_create (cols, rows, 0);
564
565   tab_columns (this->t, SOM_COL_DOWN, 1);
566   tab_headers (this->t,0,0,1,0); 
567   tab_box (this->t, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, cols -1, rows -1 );
568   tab_hline(this->t, TAL_2,0,cols-1,1);
569   tab_dim (this->t, tab_natural_dimensions);
570 }
571
572 void  ssbox_one_sample_populate(struct ssbox *ssb,
573                               struct cmd_t_test *cmd);
574
575 /* Initialize the one_sample ssbox */
576 void 
577 ssbox_one_sample_init(struct ssbox *this, 
578                            struct cmd_t_test *cmd )
579 {
580   const int hsize=5;
581   const int vsize=cmd->n_variables+1;
582
583   this->populate = ssbox_one_sample_populate;
584
585   ssbox_base_init(this, hsize,vsize);
586   tab_title (this->t, 0, _("One-Sample Statistics"));
587   tab_vline(this->t, TAL_2, 1,0,vsize);
588   tab_text (this->t, 1, 0, TAB_CENTER | TAT_TITLE, _("N"));
589   tab_text (this->t, 2, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
590   tab_text (this->t, 3, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
591   tab_text (this->t, 4, 0, TAB_CENTER | TAT_TITLE, _("SE. Mean"));
592 }
593
594 void ssbox_independent_samples_populate(struct ssbox *ssb,
595                                         struct cmd_t_test *cmd);
596
597 /* Initialize the independent samples ssbox */
598 void 
599 ssbox_independent_samples_init(struct ssbox *this, 
600         struct cmd_t_test *cmd)
601 {
602   int hsize=6;
603   int vsize = cmd->n_variables*2 +1;
604
605   this->populate = ssbox_independent_samples_populate;
606
607   ssbox_base_init(this, hsize,vsize);
608   tab_title (this->t, 0, _("Group Statistics"));
609   tab_vline(this->t,0,1,0,vsize);
610   tab_text (this->t, 1, 0, TAB_CENTER | TAT_TITLE, groups->name);
611   tab_text (this->t, 2, 0, TAB_CENTER | TAT_TITLE, _("N"));
612   tab_text (this->t, 3, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
613   tab_text (this->t, 4, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
614   tab_text (this->t, 5, 0, TAB_CENTER | TAT_TITLE, _("SE. Mean"));
615 }
616
617
618 /* Populate the ssbox for independent samples */
619 void 
620 ssbox_independent_samples_populate(struct ssbox *ssb,
621                               struct cmd_t_test *cmd)
622 {
623   int i;
624
625   char *val_lab1=0;
626   char *val_lab2=0;
627
628   if ( groups->type == NUMERIC ) 
629     {
630       val_lab1 = val_labs_find( groups->val_labs,groups_values[0]); 
631       val_lab2 = val_labs_find( groups->val_labs,groups_values[1]);
632     }
633   else
634     {
635       val_lab1 = groups_values[0].s;
636       val_lab2 = groups_values[1].s;
637     }
638
639   assert(ssb->t);
640
641   for (i=0; i < cmd->n_variables; ++i)
642     {
643       tab_text (ssb->t, 0, i*2+1, TAB_LEFT, cmd->v_variables[i]->name);
644
645       if (val_lab1)
646         tab_text (ssb->t, 1, i*2+1, TAB_LEFT, val_lab1);
647       else
648         tab_float(ssb->t, 1 ,i*2+1, TAB_LEFT, groups_values[0].f, 2,0);
649
650       if (val_lab2)
651         tab_text (ssb->t, 1, i*2+1+1, TAB_LEFT, val_lab2);
652       else
653         tab_float(ssb->t, 1 ,i*2+1+1, TAB_LEFT, groups_values[1].f,2,0);
654     }
655 }
656
657
658 void ssbox_paired_populate(struct ssbox *ssb,
659                            struct cmd_t_test *cmd);
660
661 /* Initialize the paired values ssbox */
662 void 
663 ssbox_paired_init(struct ssbox *this, struct cmd_t_test *cmd unused)
664 {
665   int hsize=6;
666
667   int vsize = n_pairs*2+1;
668
669   this->populate = ssbox_paired_populate;
670
671   ssbox_base_init(this, hsize,vsize);
672   tab_title (this->t, 0, _("Paired Sample Statistics"));
673   tab_vline(this->t,TAL_0,1,0,vsize-1);
674   tab_vline(this->t,TAL_2,2,0,vsize-1);
675   tab_text (this->t, 2, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
676   tab_text (this->t, 3, 0, TAB_CENTER | TAT_TITLE, _("N"));
677   tab_text (this->t, 4, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
678   tab_text (this->t, 5, 0, TAB_CENTER | TAT_TITLE, _("SE. Mean"));
679 }
680
681
682 /* Populate the ssbox for paired values */
683 void 
684 ssbox_paired_populate(struct ssbox *ssb,struct cmd_t_test *cmd unused)
685 {
686   int i;
687
688   assert(ssb->t);
689
690   for (i=0; i < n_pairs; ++i)
691     {
692       int j;
693
694       tab_text (ssb->t, 0, i*2+1, TAB_LEFT | TAT_PRINTF , _("Pair %d"),i);
695
696       for (j=0 ; j < 2 ; ++j) 
697         {
698           struct t_test_proc *ttp;
699
700           ttp=&pairs[i].v[j]->p.t_t;
701
702           /* Titles */
703
704           tab_text (ssb->t, 1, i*2+j+1, TAB_LEFT, pairs[i].v[j]->name);
705
706           /* Values */
707           tab_float (ssb->t,2, i*2+j+1, TAB_RIGHT, ttp->mean, 8, 2);
708           tab_float (ssb->t,3, i*2+j+1, TAB_RIGHT, ttp->n, 2, 0);
709           tab_float (ssb->t,4, i*2+j+1, TAB_RIGHT, ttp->std_dev, 8, 3);
710           tab_float (ssb->t,5, i*2+j+1, TAB_RIGHT, ttp->se_mean, 8, 3);
711
712         }
713
714     }
715
716 }
717
718 /* Populate the one sample ssbox */
719 void 
720 ssbox_one_sample_populate(struct ssbox *ssb, struct cmd_t_test *cmd)
721 {
722   int i;
723
724   assert(ssb->t);
725
726   for (i=0; i < cmd->n_variables; ++i)
727     {
728       struct t_test_proc *ttp;
729       ttp= &cmd->v_variables[i]->p.t_t;
730
731       tab_text (ssb->t, 0, i+1, TAB_LEFT, cmd->v_variables[i]->name);
732       tab_float (ssb->t,1, i+1, TAB_RIGHT, ttp->n, 2, 0);
733       tab_float (ssb->t,2, i+1, TAB_RIGHT, ttp->mean, 8, 2);
734       tab_float (ssb->t,3, i+1, TAB_RIGHT, ttp->std_dev, 8, 2);
735       tab_float (ssb->t,4, i+1, TAB_RIGHT, ttp->se_mean, 8, 3);
736     }
737   
738 }
739
740
741
742 /* Implementation of the Test Results box struct */
743
744 void trbox_base_init(struct trbox *self,int n_vars, int cols);
745 void trbox_base_finalize(struct trbox *trb);
746
747 void trbox_independent_samples_init(struct trbox *trb,
748                                     struct cmd_t_test *cmd );
749
750 void trbox_independent_samples_populate(struct trbox *trb,
751                                         struct cmd_t_test *cmd);
752
753 void trbox_one_sample_init(struct trbox *self,
754                       struct cmd_t_test *cmd );
755
756 void trbox_one_sample_populate(struct trbox *trb,
757                                struct cmd_t_test *cmd);
758
759 void trbox_paired_init(struct trbox *self,
760                        struct cmd_t_test *cmd );
761
762 void trbox_paired_populate(struct trbox *trb,
763                       struct cmd_t_test *cmd);
764
765
766
767 /* Create a trbox according to mode*/
768 void 
769 trbox_create(struct trbox *trb,   
770              struct cmd_t_test *cmd, int mode)
771 {
772     switch (mode) 
773       {
774       case T_1_SAMPLE:
775         trbox_one_sample_init(trb,cmd);
776         break;
777       case T_IND_SAMPLES:
778         trbox_independent_samples_init(trb,cmd);
779         break;
780       case T_PAIRED:
781         trbox_paired_init(trb,cmd);
782         break;
783       default:
784         assert(0);
785       }
786 }
787
788 /* Populate a trbox according to cmd */
789 void 
790 trbox_populate(struct trbox *trb, struct cmd_t_test *cmd)
791 {
792   trb->populate(trb,cmd);
793 }
794
795 /* Submit and destroy a trbox */
796 void 
797 trbox_finalize(struct trbox *trb)
798 {
799   trb->finalize(trb);
800 }
801
802 /* Initialize the independent samples trbox */
803 void 
804 trbox_independent_samples_init(struct trbox *self,
805                            struct cmd_t_test *cmd unused)
806 {
807   const int hsize=11;
808   const int vsize=cmd->n_variables*2+3;
809
810   assert(self);
811   self->populate = trbox_independent_samples_populate;
812
813   trbox_base_init(self,cmd->n_variables*2,hsize);
814   tab_title(self->t,0,_("Independent Samples Test"));
815   tab_hline(self->t,TAL_1,2,hsize-1,1);
816   tab_vline(self->t,TAL_2,2,0,vsize-1);
817   tab_vline(self->t,TAL_1,4,0,vsize-1);
818   tab_box(self->t,-1,-1,-1,TAL_1, 2,1,hsize-2,vsize-1);
819   tab_hline(self->t,TAL_1, hsize-2,hsize-1,2);
820   tab_box(self->t,-1,-1,-1,TAL_1, hsize-2,2,hsize-1,vsize-1);
821   tab_joint_text(self->t, 2, 0, 3, 0, 
822                  TAB_CENTER,_("Levine's Test for Equality of Variances"));
823   tab_joint_text(self->t, 4,0,hsize-1,0,
824                  TAB_CENTER,_("t-test for Equality of Means"));
825
826   tab_text(self->t,2,2, TAB_CENTER | TAT_TITLE,_("F"));
827   tab_text(self->t,3,2, TAB_CENTER | TAT_TITLE,_("Sig."));
828   tab_text(self->t,4,2, TAB_CENTER | TAT_TITLE,_("t"));
829   tab_text(self->t,5,2, TAB_CENTER | TAT_TITLE,_("df"));
830   tab_text(self->t,6,2, TAB_CENTER | TAT_TITLE,_("Sig. (2-tailed)"));
831   tab_text(self->t,7,2, TAB_CENTER | TAT_TITLE,_("Mean Difference"));
832   tab_text(self->t,8,2, TAB_CENTER | TAT_TITLE,_("Std. Error Difference"));
833   tab_text(self->t,9,2, TAB_CENTER | TAT_TITLE,_("Lower"));
834   tab_text(self->t,10,2, TAB_CENTER | TAT_TITLE,_("Upper"));
835
836   tab_joint_text(self->t, 9, 1, 10, 1, TAB_CENTER | TAT_PRINTF, 
837                  _("%d%% Confidence Interval of the Difference"),
838                  (int)round(cmd->criteria*100.0));
839
840 }
841
842 /* Populate the independent samples trbox */
843 void 
844 trbox_independent_samples_populate(struct trbox *self,
845                                    struct cmd_t_test *cmd )
846 {
847   int i;
848
849   assert(self);
850   for (i=0; i < cmd->n_variables; ++i)
851     {
852       tab_text (self->t, 0, i*2+3, TAB_LEFT, cmd->v_variables[i]->name);
853
854       tab_text (self->t, 1, i*2+3, TAB_LEFT, _("Equal variances assumed"));
855
856       tab_text (self->t, 1, i*2+3+1, 
857                 TAB_LEFT, _("Equal variances not assumed"));
858     }
859 }
860
861 /* Initialize the paired samples trbox */
862 void 
863 trbox_paired_init(struct trbox *self,
864                            struct cmd_t_test *cmd unused)
865 {
866
867   const int hsize=10;
868   const int vsize=n_pairs+3;
869
870   self->populate = trbox_paired_populate;
871
872   trbox_base_init(self,n_pairs,hsize);
873   tab_title (self->t, 0, _("Paired Samples Test"));
874   tab_hline(self->t,TAL_1,2,6,1);
875   tab_vline(self->t,TAL_2,2,0,vsize);
876   tab_joint_text(self->t,2,0,6,0,TAB_CENTER,_("Paired Differences"));
877   tab_box(self->t,-1,-1,-1,TAL_1, 2,1,6,vsize-1);
878   tab_box(self->t,-1,-1,-1,TAL_1, 6,0,hsize-1,vsize-1);
879   tab_hline(self->t,TAL_1,5,6, 2);
880   tab_vline(self->t,TAL_0,6,0,1);
881
882   tab_joint_text(self->t, 5, 1, 6, 1, TAB_CENTER | TAT_PRINTF, 
883                  _("%d%% Confidence Interval of the Difference"),
884                  (int)round(cmd->criteria*100.0));
885
886   tab_text (self->t, 2, 2, TAB_CENTER | TAT_TITLE, _("Mean"));
887   tab_text (self->t, 3, 2, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
888   tab_text (self->t, 4, 2, TAB_CENTER | TAT_TITLE, _("Std. Error Mean"));
889   tab_text (self->t, 5, 2, TAB_CENTER | TAT_TITLE, _("Lower"));
890   tab_text (self->t, 6, 2, TAB_CENTER | TAT_TITLE, _("Upper"));
891   tab_text (self->t, 7, 2, TAB_CENTER | TAT_TITLE, _("t"));
892   tab_text (self->t, 8, 2, TAB_CENTER | TAT_TITLE, _("df"));
893   tab_text (self->t, 9, 2, TAB_CENTER | TAT_TITLE, _("Sig. (2-tailed)"));
894 }
895
896 /* Populate the paired samples trbox */
897 void 
898 trbox_paired_populate(struct trbox *trb,
899                               struct cmd_t_test *cmd unused)
900 {
901   int i;
902
903   for (i=0; i < n_pairs; ++i)
904     {
905       int which =1;
906       double p,q;
907       int status;
908       double bound;
909       double se_mean;
910
911       struct variable *v0 = pairs[i].v[0];
912       struct variable *v1 = pairs[i].v[1];
913
914       struct t_test_proc *ttp0 = &v0->p.t_t;
915       struct t_test_proc *ttp1 = &v1->p.t_t;
916
917       double n = ttp0->n;
918       double t;
919       double df = n - 1;
920       
921       tab_text (trb->t, 0, i+3, TAB_LEFT | TAT_PRINTF, _("Pair %d"),i); 
922
923       tab_text (trb->t, 1, i+3, TAB_LEFT | TAT_PRINTF, "%s - %s",
924                 pairs[i].v[0]->name, pairs[i].v[1]->name);
925
926       tab_float(trb->t, 2, i+3, TAB_RIGHT, pairs[i].mean_diff, 8, 4);
927
928       tab_float(trb->t, 3, i+3, TAB_RIGHT, pairs[i].std_dev_diff, 8, 5);
929
930       /* SE Mean */
931       se_mean = pairs[i].std_dev_diff / sqrt(n) ;
932       tab_float(trb->t, 4, i+3, TAB_RIGHT, se_mean, 8,5 );
933
934       /* Now work out the confidence interval */
935       q = (1 - cmd->criteria)/2.0;  /* 2-tailed test */
936       p = 1 - q ;
937       which=2; /* Calc T from p,q and df */
938       cdft(&which, &p, &q, &t, &df, &status, &bound);
939
940       if ( 0 != status )
941         {
942           msg( SE, _("Error calculating T statistic (cdft returned %d)."),status);
943         }
944
945       tab_float(trb->t, 5, i+3, TAB_RIGHT, 
946                 pairs[i].mean_diff - t * se_mean , 8, 4); 
947
948       tab_float(trb->t, 6, i+3, TAB_RIGHT, 
949                 pairs[i].mean_diff + t * se_mean , 8, 4); 
950
951       t = ( ttp0->mean - ttp1->mean)
952         / sqrt ( 
953                 (  sqr(ttp0->s_std_dev) + sqr(ttp1->s_std_dev)  - 
954                    2 * pairs[i].correlation * ttp0->s_std_dev * ttp1->s_std_dev                    )
955                 / (n-1) )
956         ;
957
958       tab_float(trb->t, 7, i+3, TAB_RIGHT, t , 8,3 );
959
960       /* Degrees of freedom */
961       tab_float(trb->t, 8, i+3, TAB_RIGHT, df , 2, 0 );
962
963       which=1;
964       cdft(&which, &p, &q, &t, &df, &status, &bound);
965
966       if ( 0 != status )
967         {
968           msg( SE, _("Error calculating T statistic (cdft returned %d)."),status);
969         }
970
971
972       tab_float(trb->t, 9, i+3, TAB_RIGHT, p*2.0 , 8, 3);
973
974
975     }
976
977 }
978
979 /* Initialize the one sample trbox */
980 void 
981 trbox_one_sample_init(struct trbox *self, struct cmd_t_test *cmd )
982 {
983   const int hsize=7;
984   const int vsize=cmd->n_variables+3;
985
986   self->populate = trbox_one_sample_populate;
987
988   trbox_base_init(self, cmd->n_variables,hsize);
989   tab_title (self->t, 0, _("One-Sample Test"));
990   tab_hline(self->t, TAL_1, 1, hsize - 1, 1);
991   tab_vline(self->t, TAL_2, 1, 0, vsize);
992
993   tab_joint_text(self->t, 1, 0, hsize-1,0, TAB_CENTER | TAT_PRINTF, 
994                  _("Test Value = %f"),cmd->n_testval);
995
996   tab_box(self->t, -1, -1, -1, TAL_1, 1,1,hsize-1,vsize-1);
997
998
999   tab_joint_text(self->t,5,1,6,1,TAB_CENTER  | TAT_PRINTF, 
1000                  _("%d%% Confidence Interval of the Difference"),
1001                  (int)round(cmd->criteria*100.0));
1002
1003   tab_vline(self->t,TAL_0,6,1,1);
1004   tab_hline(self->t,TAL_1,5,6,2);
1005   tab_text (self->t, 1, 2, TAB_CENTER | TAT_TITLE, _("t"));
1006   tab_text (self->t, 2, 2, TAB_CENTER | TAT_TITLE, _("df"));
1007   tab_text (self->t, 3, 2, TAB_CENTER | TAT_TITLE, _("Sig. (2-tailed)"));
1008   tab_text (self->t, 4, 2, TAB_CENTER | TAT_TITLE, _("Mean Difference"));
1009   tab_text (self->t, 5, 2, TAB_CENTER | TAT_TITLE, _("Lower"));
1010   tab_text (self->t, 6, 2, TAB_CENTER | TAT_TITLE, _("Upper"));
1011
1012 }
1013
1014
1015 /* Populate the one sample trbox */
1016 void 
1017 trbox_one_sample_populate(struct trbox *trb, struct cmd_t_test *cmd)
1018 {
1019   int i;
1020
1021   assert(trb->t);
1022
1023   for (i=0; i < cmd->n_variables; ++i)
1024     {
1025       int which =1;
1026       double t;
1027       double p,q;
1028       double df;
1029       int status;
1030       double bound;
1031       struct t_test_proc *ttp;
1032       ttp= &cmd->v_variables[i]->p.t_t;
1033
1034
1035       tab_text (trb->t, 0, i+3, TAB_LEFT, cmd->v_variables[i]->name);
1036
1037       t = (ttp->mean - cmd->n_testval ) * sqrt(ttp->n) / ttp->std_dev ;
1038
1039       tab_float (trb->t, 1, i+3, TAB_RIGHT, t, 8,3);
1040
1041       /* degrees of freedom */
1042       df = ttp->n - 1;
1043
1044       tab_float (trb->t, 2, i+3, TAB_RIGHT, df, 8,0);
1045
1046       cdft(&which, &p, &q, &t, &df, &status, &bound);
1047
1048       if ( 0 != status )
1049         {
1050           msg( SE, _("Error calculating T statistic (cdft returned %d)."),status);
1051         }
1052
1053
1054       /* Multiply by 2 to get 2-tailed significance */
1055       tab_float (trb->t, 3, i+3, TAB_RIGHT, q*2.0, 8,3);
1056
1057       tab_float (trb->t, 4, i+3, TAB_RIGHT, ttp->mean_diff, 8,3);
1058
1059
1060       q = (1 - cmd->criteria)/2.0;  /* 2-tailed test */
1061       p = 1 - q ;
1062       which=2; /* Calc T from p,q and df */
1063       cdft(&which, &p, &q, &t, &df, &status, &bound);
1064       if ( 0 != status )
1065         {
1066           msg( SE, _("Error calculating T statistic (cdft returned %d)."),status);
1067         }
1068
1069       tab_float (trb->t, 5, i+3, TAB_RIGHT,
1070                  ttp->mean_diff - t * ttp->se_mean, 8,4);
1071
1072       tab_float (trb->t, 6, i+3, TAB_RIGHT,
1073                  ttp->mean_diff + t * ttp->se_mean, 8,4);
1074     }
1075 }
1076
1077 /* Base initializer for the generalized trbox */
1078 void 
1079 trbox_base_init(struct trbox *self, int data_rows, int cols)
1080 {
1081   const int rows = 3 + data_rows;
1082
1083   self->finalize = trbox_base_finalize;
1084   self->t = tab_create (cols, rows, 0);
1085   tab_headers (self->t,0,0,3,0); 
1086   tab_box (self->t, TAL_2, TAL_2, TAL_0, TAL_0, 0, 0, cols -1, rows -1);
1087   tab_hline(self->t, TAL_2,0,cols-1,3);
1088   tab_dim (self->t, tab_natural_dimensions);
1089 }
1090
1091
1092 /* Base finalizer for the trbox */
1093 void 
1094 trbox_base_finalize(struct trbox *trb)
1095 {
1096   tab_submit(trb->t);
1097 }
1098
1099
1100 /* Create , populate and submit the Paired Samples Correlation box */
1101 void
1102 pscbox(struct cmd_t_test *cmd)
1103 {
1104   const int rows=1+n_pairs;
1105   const int cols=5;
1106   int i;
1107   
1108   struct tab_table *table;
1109   
1110   table = tab_create (cols,rows,0);
1111
1112   tab_columns (table, SOM_COL_DOWN, 1);
1113   tab_headers (table,0,0,1,0); 
1114   tab_box (table, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, cols -1, rows -1 );
1115   tab_hline(table, TAL_2, 0, cols - 1, 1);
1116   tab_vline(table, TAL_2, 2, 0, rows - 1);
1117   tab_dim(table, tab_natural_dimensions);
1118   tab_title(table, 0, _("Paired Samples Correlations"));
1119
1120   /* column headings */
1121   tab_text(table, 2,0, TAB_CENTER | TAT_TITLE, _("N"));
1122   tab_text(table, 3,0, TAB_CENTER | TAT_TITLE, _("Correlation"));
1123   tab_text(table, 4,0, TAB_CENTER | TAT_TITLE, _("Sig."));
1124
1125
1126   for (i=0; i < n_pairs; ++i)
1127     {
1128       int which =1;
1129       double p,q;
1130
1131       int status;
1132       double bound;
1133
1134       double df = pairs[i].v[0]->p.t_t.n -2;
1135
1136       double correlation_t = 
1137         pairs[i].correlation * sqrt(df) /
1138         sqrt(1 - sqr(pairs[i].correlation));
1139
1140
1141       /* row headings */
1142       tab_text(table, 0,i+1, TAB_LEFT | TAT_TITLE | TAT_PRINTF, 
1143                _("Pair %d"), i);
1144       
1145       tab_text(table, 1,i+1, TAB_LEFT | TAT_TITLE | TAT_PRINTF, 
1146                _("%s & %s"), pairs[i].v[0]->name, pairs[i].v[1]->name);
1147
1148
1149       /* row data */
1150       tab_float(table, 3, i+1, TAB_RIGHT, pairs[i].correlation, 8, 3);
1151       tab_float(table, 2, i+1, TAB_RIGHT, pairs[i].v[0]->p.t_t.n , 4, 0);
1152
1153
1154       cdft(&which, &p, &q, &correlation_t, &df, &status, &bound);
1155
1156       if ( 0 != status )
1157         {
1158           msg( SE, _("Error calculating T statistic (cdft returned %d)."),status);
1159         }
1160
1161
1162       tab_float(table, 4, i+1, TAB_RIGHT, q*2.0, 8, 3);
1163
1164
1165
1166       
1167     }
1168
1169   tab_submit(table);
1170 }
1171
1172
1173
1174 /* Calculation Implementation */
1175
1176 /* Per case calculations common to all variants of the T test */
1177 static int 
1178 common_calc (struct ccase *c)
1179 {
1180   int i;
1181
1182   double weight = dict_get_case_weight(default_dict,c);
1183
1184   for(i=0; i< cmd.n_variables ; ++i) 
1185     {
1186       struct t_test_proc *ttp;
1187       struct variable *v = cmd.v_variables[i];
1188       union value *val = &c->data[v->fv];
1189
1190       ttp= &cmd.v_variables[i]->p.t_t;
1191
1192       if (val->f != SYSMIS) 
1193         {
1194           ttp->n+=weight;
1195           ttp->sum+=weight * val->f;
1196           ttp->ssq+=weight * val->f * val->f;
1197         }
1198     }
1199   return 0;
1200 }
1201
1202 /* Pre calculations common to all variants of the T test */
1203 static void 
1204 common_precalc (void)
1205 {
1206   int i=0;
1207
1208   for(i=0; i< cmd.n_variables ; ++i) 
1209     {
1210       struct t_test_proc *ttp;
1211       ttp= &cmd.v_variables[i]->p.t_t;
1212       
1213       ttp->sum=0;
1214       ttp->n=0;
1215       ttp->ssq=0;
1216       ttp->sum_diff=0;
1217     }
1218 }
1219
1220 /* Post calculations common to all variants of the T test */
1221 void 
1222 common_postcalc (void)
1223 {
1224   int i=0;
1225
1226   for(i=0; i< cmd.n_variables ; ++i) 
1227     {
1228       struct t_test_proc *ttp;
1229       ttp= &cmd.v_variables[i]->p.t_t;
1230       
1231       ttp->mean=ttp->sum / ttp->n;
1232       ttp->s_std_dev= sqrt(
1233                          ( (ttp->ssq / ttp->n ) - ttp->mean * ttp->mean )
1234                          ) ;
1235
1236       ttp->std_dev= sqrt(
1237                          ttp->n/(ttp->n-1) *
1238                          ( (ttp->ssq / ttp->n ) - ttp->mean * ttp->mean )
1239                          ) ;
1240
1241       ttp->se_mean = ttp->std_dev / sqrt(ttp->n);
1242       ttp->mean_diff= ttp->sum_diff / ttp->n;
1243     }
1244 }
1245
1246 /* Per case calculations for one sample t test  */
1247 static int 
1248 one_sample_calc (struct ccase *c)
1249 {
1250   int i;
1251
1252   double weight = dict_get_case_weight(default_dict,c);
1253
1254   for(i=0; i< cmd.n_variables ; ++i) 
1255     {
1256       struct t_test_proc *ttp;
1257       struct variable *v = cmd.v_variables[i];
1258       union value *val = &c->data[v->fv];
1259
1260       ttp= &cmd.v_variables[i]->p.t_t;
1261       
1262       if (val->f != SYSMIS) 
1263         ttp->sum_diff += weight * (val->f - cmd.n_testval);
1264     }
1265
1266   return 0;
1267 }
1268
1269 /* Pre calculations for one sample t test */
1270 static void 
1271 one_sample_precalc (void)
1272 {
1273   int i=0;
1274   
1275   for(i=0; i< cmd.n_variables ; ++i) 
1276     {
1277       struct t_test_proc *ttp;
1278       ttp= &cmd.v_variables[i]->p.t_t;
1279       
1280       ttp->sum_diff=0;
1281     }
1282 }
1283
1284 /* Post calculations for one sample t test */
1285 static void 
1286 one_sample_postcalc (void)
1287 {
1288   int i=0;
1289   
1290   for(i=0; i< cmd.n_variables ; ++i) 
1291     {
1292       struct t_test_proc *ttp;
1293       ttp= &cmd.v_variables[i]->p.t_t;
1294
1295       
1296       ttp->mean_diff = ttp->sum_diff / ttp->n ;
1297     }
1298 }
1299
1300
1301
1302 static int
1303 compare_var_name (const void *a_, const void *b_, void *v_ unused)
1304 {
1305   const struct variable *a = a_;
1306   const struct variable *b = b_;
1307
1308   return strcmp(a->name,b->name);
1309 }
1310
1311 static unsigned
1312 hash_var_name (const void *a_, void *v_ unused)
1313 {
1314   const struct variable *a = a_;
1315
1316   return hsh_hash_bytes (a->name, strlen(a->name));
1317 }
1318
1319
1320 static void 
1321 paired_precalc (void)
1322 {
1323   int i;
1324
1325   for(i=0; i < n_pairs ; ++i )
1326     {
1327       pairs[i].correlation=0;
1328       pairs[i].sum_of_diffs=0;
1329       pairs[i].ssq_diffs=0;
1330     }
1331
1332 }
1333
1334 static int  
1335 paired_calc (struct ccase *c)
1336 {
1337   int i;
1338
1339   for(i=0; i < n_pairs ; ++i )
1340     {
1341       struct variable *v0 = pairs[i].v[0];
1342       struct variable *v1 = pairs[i].v[1];
1343
1344       union value *val0 = &c->data[v0->fv];
1345       union value *val1 = &c->data[v1->fv];
1346
1347       pairs[i].correlation += ( val0->f - pairs[i].v[0]->p.t_t.mean )
1348                               *
1349                               ( val1->f - pairs[i].v[1]->p.t_t.mean );
1350
1351       pairs[i].sum_of_diffs += val0->f - val1->f ;
1352       pairs[i].ssq_diffs += sqr(val0->f - val1->f);
1353
1354     }
1355
1356
1357   return 0;
1358 }
1359
1360 static void 
1361 paired_postcalc (void)
1362 {
1363   int i;
1364
1365   for(i=0; i < n_pairs ; ++i )
1366     {
1367       const double n = pairs[i].v[0]->p.t_t.n ;
1368       
1369       pairs[i].correlation /= pairs[i].v[0]->p.t_t.std_dev * 
1370                               pairs[i].v[1]->p.t_t.std_dev ;
1371       pairs[i].correlation /= pairs[i].v[0]->p.t_t.n -1; 
1372
1373
1374       pairs[i].mean_diff = pairs[i].sum_of_diffs / n ;
1375
1376
1377       pairs[i].std_dev_diff = sqrt (  n / (n - 1) * (
1378                                     ( pairs[i].ssq_diffs / n )
1379                                     - 
1380                                     sqr(pairs[i].mean_diff )
1381                                     ) );
1382
1383     }
1384 }