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