1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2005, 2006, 2007, 2009, 2010, 2011 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include <gsl/gsl_cdf.h>
23 #include "data/case.h"
24 #include "data/casegrouper.h"
25 #include "data/casereader.h"
26 #include "data/casewriter.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/short-names.h"
32 #include "data/subcase.h"
33 #include "data/variable.h"
34 #include "language/command.h"
35 #include "language/stats/sort-criteria.h"
36 #include "libpspp/compiler.h"
37 #include "libpspp/taint.h"
38 #include "math/sort.h"
39 #include "output/tab.h"
42 #define _(msgid) gettext (msgid)
58 +fraction=fraction:!blom/tukey/vw/rankit;
59 +ties=ties:!mean/low/high/condense;
60 missing=miss:!exclude/include.
65 typedef double (*rank_function_t) (double c, double cc, double cc_1,
68 static double rank_proportion (double c, double cc, double cc_1,
71 static double rank_normal (double c, double cc, double cc_1,
74 static double rank_percent (double c, double cc, double cc_1,
77 static double rank_rfraction (double c, double cc, double cc_1,
80 static double rank_rank (double c, double cc, double cc_1,
83 static double rank_n (double c, double cc, double cc_1,
86 static double rank_savage (double c, double cc, double cc_1,
89 static double rank_ntiles (double c, double cc, double cc_1,
106 static const struct fmt_spec dest_format[n_RANK_FUNCS] = {
107 {FMT_F, 9, 3}, /* rank */
108 {FMT_F, 6, 4}, /* normal */
109 {FMT_F, 6, 2}, /* percent */
110 {FMT_F, 6, 4}, /* rfraction */
111 {FMT_F, 6, 4}, /* proportion */
112 {FMT_F, 6, 0}, /* n */
113 {FMT_F, 3, 0}, /* ntiles */
114 {FMT_F, 8, 4} /* savage */
117 static const char * const function_name[n_RANK_FUNCS] = {
128 static const rank_function_t rank_func[n_RANK_FUNCS] = {
142 enum RANK_FUNC rfunc;
143 struct variable **destvars;
147 /* Categories of missing values to exclude. */
148 static enum mv_class exclude_values;
150 static struct rank_spec *rank_specs;
151 static size_t n_rank_specs;
153 static struct subcase sc;
155 static const struct variable **group_vars;
156 static size_t n_group_vars;
158 static const struct variable **src_vars;
159 static size_t n_src_vars;
164 static struct cmd_rank cmd;
166 static void rank_sorted_file (struct casereader *,
168 const struct dictionary *,
169 const struct rank_spec *rs,
172 const struct variable *rank_var);
177 static char name[10];
178 switch ( cmd.fraction )
181 strcpy (name, "BLOM");
184 strcpy (name, "RANKIT");
187 strcpy (name, "TUKEY");
198 /* Create a label on DEST_VAR, describing its derivation from SRC_VAR and F */
200 create_var_label (struct variable *dest_var,
201 const struct variable *src_var, enum RANK_FUNC f)
204 ds_init_empty (&label);
206 if ( n_group_vars > 0 )
208 struct string group_var_str;
211 ds_init_empty (&group_var_str);
213 for (g = 0 ; g < n_group_vars ; ++g )
215 if ( g > 0 ) ds_put_cstr (&group_var_str, " ");
216 ds_put_cstr (&group_var_str, var_get_name (group_vars[g]));
219 ds_put_format (&label, _("%s of %s by %s"), function_name[f],
220 var_get_name (src_var), ds_cstr (&group_var_str));
221 ds_destroy (&group_var_str);
224 ds_put_format (&label, _("%s of %s"),
225 function_name[f], var_get_name (src_var));
227 var_set_label (dest_var, ds_cstr (&label), false);
234 rank_cmd (struct dataset *ds, const struct subcase *sc,
235 const struct rank_spec *rank_specs, int n_rank_specs)
237 struct dictionary *d = dataset_dict (ds);
241 for (i = 0 ; i < subcase_get_n_fields (sc) ; ++i )
243 /* Rank variable at index I in SC. */
244 struct casegrouper *split_grouper;
245 struct casereader *split_group;
246 struct casewriter *output;
248 proc_discard_output (ds);
249 split_grouper = casegrouper_create_splits (proc_open (ds), d);
250 output = autopaging_writer_create (dict_get_proto (d));
252 while (casegrouper_get_next_group (split_grouper, &split_group))
254 struct subcase ordering;
255 struct casereader *ordered;
256 struct casegrouper *by_grouper;
257 struct casereader *by_group;
259 /* Sort this split group by the BY variables as primary
260 keys and the rank variable as secondary key. */
261 subcase_init_vars (&ordering, group_vars, n_group_vars);
262 subcase_add_var (&ordering, src_vars[i],
263 subcase_get_direction (sc, i));
264 ordered = sort_execute (split_group, &ordering);
265 subcase_destroy (&ordering);
267 /* Rank the rank variable within this split group. */
268 by_grouper = casegrouper_create_vars (ordered,
269 group_vars, n_group_vars);
270 while (casegrouper_get_next_group (by_grouper, &by_group))
272 /* Rank the rank variable within this BY group
273 within the split group. */
275 rank_sorted_file (by_group, output, d, rank_specs, n_rank_specs,
278 ok = casegrouper_destroy (by_grouper) && ok;
280 ok = casegrouper_destroy (split_grouper);
281 ok = proc_commit (ds) && ok;
282 ok = (dataset_set_source (ds, casewriter_make_reader (output))
291 /* Hardly a rank function !! */
293 rank_n (double c UNUSED, double cc UNUSED, double cc_1 UNUSED,
294 int i UNUSED, double w)
301 rank_rank (double c, double cc, double cc_1,
302 int i, double w UNUSED)
317 rank = cc_1 + (c + 1.0)/ 2.0;
337 rank = cc_1 + c / 2.0 ;
352 rank_rfraction (double c, double cc, double cc_1,
355 return rank_rank (c, cc, cc_1, i, w) / w ;
360 rank_percent (double c, double cc, double cc_1,
363 return rank_rank (c, cc, cc_1, i, w) * 100.0 / w ;
368 rank_proportion (double c, double cc, double cc_1,
371 const double r = rank_rank (c, cc, cc_1, i, w) ;
375 switch ( cmd.fraction )
378 f = (r - 3.0/8.0) / (w + 0.25);
384 f = (r - 1.0/3.0) / (w + 1.0/3.0);
394 return (f > 0) ? f : SYSMIS;
398 rank_normal (double c, double cc, double cc_1,
401 double f = rank_proportion (c, cc, cc_1, i, w);
403 return gsl_cdf_ugaussian_Pinv (f);
407 rank_ntiles (double c, double cc, double cc_1,
410 double r = rank_rank (c, cc, cc_1, i, w);
413 return ( floor (( r * k_ntiles) / ( w + 1) ) + 1);
416 /* Expected value of the order statistics from an exponential distribution */
418 ee (int j, double w_star)
423 for (k = 1 ; k <= j; k++)
424 sum += 1.0 / ( w_star + 1 - k );
431 rank_savage (double c, double cc, double cc_1,
432 int i UNUSED, double w)
435 const int i_1 = floor (cc_1);
436 const int i_2 = floor (cc);
438 const double w_star = (modf (w, &int_part) == 0 ) ? w : floor (w) + 1;
440 const double g_1 = cc_1 - i_1;
441 const double g_2 = cc - i_2;
443 /* The second factor is infinite, when the first is zero.
444 Therefore, evaluate the second, only when the first is non-zero */
445 const double expr1 = (1 - g_1) ? (1 - g_1) * ee(i_1+1, w_star) : ( 1 - g_1);
446 const double expr2 = g_2 ? g_2 * ee (i_2+1, w_star) : g_2 ;
449 return ee (i_1 + 1, w_star) - 1;
451 if ( i_1 + 1 == i_2 )
452 return ( ( expr1 + expr2 )/c ) - 1;
454 if ( i_1 + 2 <= i_2 )
458 for (j = i_1 + 2 ; j <= i_2; ++j )
459 sigma += ee (j, w_star);
460 return ( (expr1 + expr2 + sigma) / c) -1;
467 rank_sorted_file (struct casereader *input,
468 struct casewriter *output,
469 const struct dictionary *dict,
470 const struct rank_spec *rs,
473 const struct variable *rank_var)
475 struct casereader *pass1, *pass2, *pass2_1;
476 struct casegrouper *tie_grouper;
483 input = casereader_create_filter_missing (input, &rank_var, 1,
484 exclude_values, NULL, output);
485 input = casereader_create_filter_weight (input, dict, NULL, output);
487 casereader_split (input, &pass1, &pass2);
489 /* Pass 1: Get total group weight. */
490 for (; (c = casereader_read (pass1)) != NULL; case_unref (c))
491 w += dict_get_case_weight (dict, c, NULL);
492 casereader_destroy (pass1);
494 /* Pass 2: Do ranking. */
495 tie_grouper = casegrouper_create_vars (pass2, &rank_var, 1);
496 while (casegrouper_get_next_group (tie_grouper, &pass2_1))
498 struct casereader *pass2_2;
503 pass2_2 = casereader_clone (pass2_1);
504 taint_propagate (casereader_get_taint (pass2_2),
505 casewriter_get_taint (output));
507 /* Pass 2.1: Sum up weight for tied cases. */
508 for (; (c = casereader_read (pass2_1)) != NULL; case_unref (c))
509 tw += dict_get_case_weight (dict, c, NULL);
511 casereader_destroy (pass2_1);
513 /* Pass 2.2: Rank tied cases. */
514 while ((c = casereader_read (pass2_2)) != NULL)
516 c = case_unshare (c);
517 for (i = 0; i < n_rank_specs; ++i)
519 const struct variable *dst_var = rs[i].destvars[dest_idx];
520 double *dst_value = &case_data_rw (c, dst_var)->f;
521 *dst_value = rank_func[rs[i].rfunc] (tw, cc, cc_1, tie_group, w);
523 casewriter_write (output, c);
525 casereader_destroy (pass2_2);
529 casegrouper_destroy (tie_grouper);
532 /* Transformation function to enumerate all the cases */
534 create_resort_key (void *key_var_, struct ccase **cc, casenumber case_num)
536 struct variable *key_var = key_var_;
538 *cc = case_unshare (*cc);
539 case_data_rw (*cc, key_var)->f = case_num;
541 return TRNS_CONTINUE;
545 /* Create and return a new variable in which to store the ranks of SRC_VAR
546 accoring to the rank function F.
547 VNAME is the name of the variable to be created.
548 If VNAME is NULL, then a name will be automatically chosen.
550 static struct variable *
551 create_rank_variable (struct dictionary *dict, enum RANK_FUNC f,
552 const struct variable *src_var,
556 struct variable *var = NULL;
557 char name[SHORT_NAME_LEN + 1];
560 var = dict_create_var(dict, vname, 0);
564 snprintf (name, SHORT_NAME_LEN + 1, "%c%s",
565 function_name[f][0], var_get_name (src_var));
567 var = dict_create_var(dict, name, 0);
574 snprintf(func_abb, 4, "%s", function_name[f]);
575 snprintf(name, SHORT_NAME_LEN + 1, "%s%03d", func_abb,
578 var = dict_create_var(dict, name, 0);
584 while ( NULL == var )
587 snprintf(func_abb, 3, "%s", function_name[f]);
589 snprintf(name, SHORT_NAME_LEN + 1,
590 "RNK%s%02d", func_abb, i);
592 var = dict_create_var(dict, name, 0);
599 msg(ME, _("Cannot create new rank variable. All candidates in use."));
603 var_set_both_formats (var, &dest_format[f]);
618 for (i = 0 ; i < n_rank_specs ; ++i )
619 free (rank_specs[i].destvars);
625 subcase_destroy (&sc);
633 cmd_rank (struct lexer *lexer, struct dataset *ds)
636 struct variable *order;
640 subcase_init_empty (&sc);
641 if ( !parse_rank (lexer, ds, &cmd, NULL) )
647 /* If /MISSING=INCLUDE is set, then user missing values are ignored */
648 exclude_values = cmd.miss == RANK_INCLUDE ? MV_SYSTEM : MV_ANY;
650 /* Default to /RANK if no function subcommands are given */
651 if ( !( cmd.sbc_normal || cmd.sbc_ntiles || cmd.sbc_proportion ||
652 cmd.sbc_rfraction || cmd.sbc_savage || cmd.sbc_n ||
653 cmd.sbc_percent || cmd.sbc_rank ) )
655 assert ( n_rank_specs == 0 );
657 rank_specs = xmalloc (sizeof (*rank_specs));
658 rank_specs[0].rfunc = RANK;
659 rank_specs[0].destvars =
660 xcalloc (subcase_get_n_fields (&sc), sizeof (struct variable *));
665 assert ( subcase_get_n_fields (&sc) == n_src_vars);
667 /* Create variables for all rank destinations which haven't
668 already been created with INTO.
669 Add labels to all the destination variables.
671 for (i = 0 ; i < n_rank_specs ; ++i )
674 for ( v = 0 ; v < n_src_vars ; v ++ )
676 struct dictionary *dict = dataset_dict (ds);
678 if ( rank_specs[i].destvars[v] == NULL )
680 rank_specs[i].destvars[v] =
681 create_rank_variable (dict, rank_specs[i].rfunc, src_vars[v], NULL);
684 create_var_label ( rank_specs[i].destvars[v],
686 rank_specs[i].rfunc);
690 if ( cmd.print == RANK_YES )
694 tab_output_text (0, _("Variables Created By RANK"));
695 tab_output_text (0, "");
697 for (i = 0 ; i < n_rank_specs ; ++i )
699 for ( v = 0 ; v < n_src_vars ; v ++ )
701 if ( n_group_vars > 0 )
703 struct string varlist;
706 ds_init_empty (&varlist);
707 for ( g = 0 ; g < n_group_vars ; ++g )
709 ds_put_cstr (&varlist, var_get_name (group_vars[g]));
711 if ( g < n_group_vars - 1)
712 ds_put_cstr (&varlist, " ");
715 if ( rank_specs[i].rfunc == NORMAL ||
716 rank_specs[i].rfunc == PROPORTION )
717 tab_output_text_format (0,
718 _("%s into %s(%s of %s using %s BY %s)"),
719 var_get_name (src_vars[v]),
720 var_get_name (rank_specs[i].destvars[v]),
721 function_name[rank_specs[i].rfunc],
722 var_get_name (src_vars[v]),
727 tab_output_text_format (0,
728 _("%s into %s(%s of %s BY %s)"),
729 var_get_name (src_vars[v]),
730 var_get_name (rank_specs[i].destvars[v]),
731 function_name[rank_specs[i].rfunc],
732 var_get_name (src_vars[v]),
734 ds_destroy (&varlist);
738 if ( rank_specs[i].rfunc == NORMAL ||
739 rank_specs[i].rfunc == PROPORTION )
740 tab_output_text_format (0,
741 _("%s into %s(%s of %s using %s)"),
742 var_get_name (src_vars[v]),
743 var_get_name (rank_specs[i].destvars[v]),
744 function_name[rank_specs[i].rfunc],
745 var_get_name (src_vars[v]),
749 tab_output_text_format (0,
750 _("%s into %s(%s of %s)"),
751 var_get_name (src_vars[v]),
752 var_get_name (rank_specs[i].destvars[v]),
753 function_name[rank_specs[i].rfunc],
754 var_get_name (src_vars[v]));
760 if ( cmd.sbc_fraction &&
761 ( ! cmd.sbc_normal && ! cmd.sbc_proportion) )
762 msg(MW, _("FRACTION has been specified, but NORMAL and PROPORTION rank functions have not been requested. The FRACTION subcommand will be ignored.") );
764 /* Add a variable which we can sort by to get back the original
766 order = dict_create_var_assert (dataset_dict (ds), "$ORDER_", 0);
768 add_transformation (ds, create_resort_key, 0, order);
771 result = rank_cmd (ds, &sc, rank_specs, n_rank_specs);
773 /* Put the active dataset back in its original order. Delete
774 our sort key, which we don't need anymore. */
776 struct casereader *sorted;
778 /* FIXME: loses error conditions. */
780 proc_discard_output (ds);
781 sorted = sort_execute_1var (proc_open (ds), order);
782 result = proc_commit (ds) && result;
784 dict_delete_var (dataset_dict (ds), order);
785 result = dataset_set_source (ds, sorted) && result;
791 return (result ? CMD_SUCCESS : CMD_CASCADING_FAILURE);
795 /* Parser for the variables sub command
796 Returns 1 on success */
798 rank_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd UNUSED, void *aux UNUSED)
800 lex_match (lexer, T_EQUALS);
802 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokcstr (lexer)) == NULL)
803 && lex_token (lexer) != T_ALL)
806 if (!parse_sort_criteria (lexer, dataset_dict (ds), &sc, &src_vars, NULL))
808 n_src_vars = subcase_get_n_fields (&sc);
810 if ( lex_match (lexer, T_BY) )
812 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokcstr (lexer)) == NULL))
817 if (!parse_variables_const (lexer, dataset_dict (ds),
818 &group_vars, &n_group_vars,
819 PV_NO_DUPLICATE | PV_NO_SCRATCH) )
830 /* Parse the [/rank INTO var1 var2 ... varN ] clause */
832 parse_rank_function (struct lexer *lexer, struct dictionary *dict, struct cmd_rank *cmd UNUSED, enum RANK_FUNC f)
837 rank_specs = xnrealloc(rank_specs, n_rank_specs, sizeof *rank_specs);
838 rank_specs[n_rank_specs - 1].rfunc = f;
839 rank_specs[n_rank_specs - 1].destvars = NULL;
841 rank_specs[n_rank_specs - 1].destvars =
842 xcalloc (subcase_get_n_fields (&sc), sizeof (struct variable *));
844 if (lex_match_id (lexer, "INTO"))
846 struct variable *destvar;
848 while( lex_token (lexer) == T_ID )
851 if ( dict_lookup_var (dict, lex_tokcstr (lexer)) != NULL )
853 msg(SE, _("Variable %s already exists."), lex_tokcstr (lexer));
856 if ( var_count >= subcase_get_n_fields (&sc) )
858 msg(SE, _("Too many variables in INTO clause."));
862 destvar = create_rank_variable (dict, f, src_vars[var_count], lex_tokcstr (lexer));
863 rank_specs[n_rank_specs - 1].destvars[var_count] = destvar ;
875 rank_custom_rank (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
877 struct dictionary *dict = dataset_dict (ds);
879 return parse_rank_function (lexer, dict, cmd, RANK);
883 rank_custom_normal (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
885 struct dictionary *dict = dataset_dict (ds);
887 return parse_rank_function (lexer, dict, cmd, NORMAL);
891 rank_custom_percent (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
893 struct dictionary *dict = dataset_dict (ds);
895 return parse_rank_function (lexer, dict, cmd, PERCENT);
899 rank_custom_rfraction (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
901 struct dictionary *dict = dataset_dict (ds);
903 return parse_rank_function (lexer, dict, cmd, RFRACTION);
907 rank_custom_proportion (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
909 struct dictionary *dict = dataset_dict (ds);
911 return parse_rank_function (lexer, dict, cmd, PROPORTION);
915 rank_custom_n (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
917 struct dictionary *dict = dataset_dict (ds);
919 return parse_rank_function (lexer, dict, cmd, N);
923 rank_custom_savage (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
925 struct dictionary *dict = dataset_dict (ds);
927 return parse_rank_function (lexer, dict, cmd, SAVAGE);
932 rank_custom_ntiles (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
934 struct dictionary *dict = dataset_dict (ds);
936 if ( lex_force_match (lexer, T_LPAREN) )
938 if ( lex_force_int (lexer) )
940 k_ntiles = lex_integer (lexer);
942 lex_force_match (lexer, T_RPAREN);
950 return parse_rank_function (lexer, dict, cmd, NTILES);