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