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