1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2005, 2006, 2007, 2009 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/>. */
22 #include <data/case.h>
23 #include <data/casegrouper.h>
24 #include <data/casereader.h>
25 #include <data/casewriter.h>
26 #include <data/dictionary.h>
27 #include <data/format.h>
28 #include <data/missing-values.h>
29 #include <data/procedure.h>
30 #include <data/short-names.h>
31 #include <data/subcase.h>
32 #include <data/variable.h>
33 #include <language/command.h>
34 #include <language/stats/sort-criteria.h>
35 #include <libpspp/compiler.h>
36 #include <libpspp/taint.h>
37 #include <math/sort.h>
38 #include <output/manager.h>
39 #include <output/table.h>
41 #include <gsl/gsl_cdf.h>
44 #define _(msgid) gettext (msgid)
60 +fraction=fraction:!blom/tukey/vw/rankit;
61 +ties=ties:!mean/low/high/condense;
62 missing=miss:!exclude/include.
67 typedef double (*rank_function_t) (double c, double cc, double cc_1,
70 static double rank_proportion (double c, double cc, double cc_1,
73 static double rank_normal (double c, double cc, double cc_1,
76 static double rank_percent (double c, double cc, double cc_1,
79 static double rank_rfraction (double c, double cc, double cc_1,
82 static double rank_rank (double c, double cc, double cc_1,
85 static double rank_n (double c, double cc, double cc_1,
88 static double rank_savage (double c, double cc, double cc_1,
91 static double rank_ntiles (double c, double cc, double cc_1,
108 static const struct fmt_spec dest_format[n_RANK_FUNCS] = {
109 {FMT_F, 9, 3}, /* rank */
110 {FMT_F, 6, 4}, /* normal */
111 {FMT_F, 6, 2}, /* percent */
112 {FMT_F, 6, 4}, /* rfraction */
113 {FMT_F, 6, 4}, /* proportion */
114 {FMT_F, 6, 0}, /* n */
115 {FMT_F, 3, 0}, /* ntiles */
116 {FMT_F, 8, 4} /* savage */
119 static const char * const function_name[n_RANK_FUNCS] = {
130 static const rank_function_t rank_func[n_RANK_FUNCS] = {
144 enum RANK_FUNC rfunc;
145 struct variable **destvars;
149 /* Categories of missing values to exclude. */
150 static enum mv_class exclude_values;
152 static struct rank_spec *rank_specs;
153 static size_t n_rank_specs;
155 static struct subcase sc;
157 static const struct variable **group_vars;
158 static size_t n_group_vars;
160 static const struct variable **src_vars;
161 static size_t n_src_vars;
166 static struct cmd_rank cmd;
168 static void rank_sorted_file (struct casereader *,
170 const struct dictionary *,
171 const struct rank_spec *rs,
174 const struct variable *rank_var);
179 static char name[10];
180 switch ( cmd.fraction )
183 strcpy (name, "BLOM");
186 strcpy (name, "RANKIT");
189 strcpy (name, "TUKEY");
200 /* Create a label on DEST_VAR, describing its derivation from SRC_VAR and F */
202 create_var_label (struct variable *dest_var,
203 const struct variable *src_var, enum RANK_FUNC f)
206 ds_init_empty (&label);
208 if ( n_group_vars > 0 )
210 struct string group_var_str;
213 ds_init_empty (&group_var_str);
215 for (g = 0 ; g < n_group_vars ; ++g )
217 if ( g > 0 ) ds_put_cstr (&group_var_str, " ");
218 ds_put_cstr (&group_var_str, var_get_name (group_vars[g]));
221 ds_put_format (&label, _("%s of %s by %s"), function_name[f],
222 var_get_name (src_var), ds_cstr (&group_var_str));
223 ds_destroy (&group_var_str);
226 ds_put_format (&label, _("%s of %s"),
227 function_name[f], var_get_name (src_var));
229 var_set_label (dest_var, ds_cstr (&label));
236 rank_cmd (struct dataset *ds, const struct subcase *sc,
237 const struct rank_spec *rank_specs, int n_rank_specs)
239 struct dictionary *d = dataset_dict (ds);
243 for (i = 0 ; i < subcase_get_n_fields (sc) ; ++i )
245 /* Rank variable at index I in SC. */
246 struct casegrouper *split_grouper;
247 struct casereader *split_group;
248 struct casewriter *output;
250 proc_discard_output (ds);
251 split_grouper = casegrouper_create_splits (proc_open (ds), d);
252 output = autopaging_writer_create (dict_get_proto (d));
254 while (casegrouper_get_next_group (split_grouper, &split_group))
256 struct subcase ordering;
257 struct casereader *ordered;
258 struct casegrouper *by_grouper;
259 struct casereader *by_group;
261 /* Sort this split group by the BY variables as primary
262 keys and the rank variable as secondary key. */
263 subcase_init_vars (&ordering, group_vars, n_group_vars);
264 subcase_add_var (&ordering, src_vars[i],
265 subcase_get_direction (sc, i));
266 ordered = sort_execute (split_group, &ordering);
267 subcase_destroy (&ordering);
269 /* Rank the rank variable within this split group. */
270 by_grouper = casegrouper_create_vars (ordered,
271 group_vars, n_group_vars);
272 while (casegrouper_get_next_group (by_grouper, &by_group))
274 /* Rank the rank variable within this BY group
275 within the split group. */
277 rank_sorted_file (by_group, output, d, rank_specs, n_rank_specs,
280 ok = casegrouper_destroy (by_grouper) && ok;
282 ok = casegrouper_destroy (split_grouper);
283 ok = proc_commit (ds) && ok;
284 ok = (proc_set_active_file_data (ds, casewriter_make_reader (output))
293 /* Hardly a rank function !! */
295 rank_n (double c UNUSED, double cc UNUSED, double cc_1 UNUSED,
296 int i UNUSED, double w)
303 rank_rank (double c, double cc, double cc_1,
304 int i, double w UNUSED)
319 rank = cc_1 + (c + 1.0)/ 2.0;
339 rank = cc_1 + c / 2.0 ;
354 rank_rfraction (double c, double cc, double cc_1,
357 return rank_rank (c, cc, cc_1, i, w) / w ;
362 rank_percent (double c, double cc, double cc_1,
365 return rank_rank (c, cc, cc_1, i, w) * 100.0 / w ;
370 rank_proportion (double c, double cc, double cc_1,
373 const double r = rank_rank (c, cc, cc_1, i, w) ;
377 switch ( cmd.fraction )
380 f = (r - 3.0/8.0) / (w + 0.25);
386 f = (r - 1.0/3.0) / (w + 1.0/3.0);
396 return (f > 0) ? f : SYSMIS;
400 rank_normal (double c, double cc, double cc_1,
403 double f = rank_proportion (c, cc, cc_1, i, w);
405 return gsl_cdf_ugaussian_Pinv (f);
409 rank_ntiles (double c, double cc, double cc_1,
412 double r = rank_rank (c, cc, cc_1, i, w);
415 return ( floor (( r * k_ntiles) / ( w + 1) ) + 1);
418 /* Expected value of the order statistics from an exponential distribution */
420 ee (int j, double w_star)
425 for (k = 1 ; k <= j; k++)
426 sum += 1.0 / ( w_star + 1 - k );
433 rank_savage (double c, double cc, double cc_1,
434 int i UNUSED, double w)
437 const int i_1 = floor (cc_1);
438 const int i_2 = floor (cc);
440 const double w_star = (modf (w, &int_part) == 0 ) ? w : floor (w) + 1;
442 const double g_1 = cc_1 - i_1;
443 const double g_2 = cc - i_2;
445 /* The second factor is infinite, when the first is zero.
446 Therefore, evaluate the second, only when the first is non-zero */
447 const double expr1 = (1 - g_1) ? (1 - g_1) * ee(i_1+1, w_star) : ( 1 - g_1);
448 const double expr2 = g_2 ? g_2 * ee (i_2+1, w_star) : g_2 ;
451 return ee (i_1 + 1, w_star) - 1;
453 if ( i_1 + 1 == i_2 )
454 return ( ( expr1 + expr2 )/c ) - 1;
456 if ( i_1 + 2 <= i_2 )
460 for (j = i_1 + 2 ; j <= i_2; ++j )
461 sigma += ee (j, w_star);
462 return ( (expr1 + expr2 + sigma) / c) -1;
469 rank_sorted_file (struct casereader *input,
470 struct casewriter *output,
471 const struct dictionary *dict,
472 const struct rank_spec *rs,
475 const struct variable *rank_var)
477 struct casereader *pass1, *pass2, *pass2_1;
478 struct casegrouper *tie_grouper;
485 input = casereader_create_filter_missing (input, &rank_var, 1,
486 exclude_values, NULL, output);
487 input = casereader_create_filter_weight (input, dict, NULL, output);
489 casereader_split (input, &pass1, &pass2);
491 /* Pass 1: Get total group weight. */
492 for (; (c = casereader_read (pass1)) != NULL; case_unref (c))
493 w += dict_get_case_weight (dict, c, NULL);
494 casereader_destroy (pass1);
496 /* Pass 2: Do ranking. */
497 tie_grouper = casegrouper_create_vars (pass2, &rank_var, 1);
498 while (casegrouper_get_next_group (tie_grouper, &pass2_1))
500 struct casereader *pass2_2;
505 pass2_2 = casereader_clone (pass2_1);
506 taint_propagate (casereader_get_taint (pass2_2),
507 casewriter_get_taint (output));
509 /* Pass 2.1: Sum up weight for tied cases. */
510 for (; (c = casereader_read (pass2_1)) != NULL; case_unref (c))
511 tw += dict_get_case_weight (dict, c, NULL);
513 casereader_destroy (pass2_1);
515 /* Pass 2.2: Rank tied cases. */
516 while ((c = casereader_read (pass2_2)) != NULL)
518 c = case_unshare (c);
519 for (i = 0; i < n_rank_specs; ++i)
521 const struct variable *dst_var = rs[i].destvars[dest_idx];
522 double *dst_value = &case_data_rw (c, dst_var)->f;
523 *dst_value = rank_func[rs[i].rfunc] (tw, cc, cc_1, tie_group, w);
525 casewriter_write (output, c);
527 casereader_destroy (pass2_2);
531 casegrouper_destroy (tie_grouper);
534 /* Transformation function to enumerate all the cases */
536 create_resort_key (void *key_var_, struct ccase **cc, casenumber case_num)
538 struct variable *key_var = key_var_;
540 *cc = case_unshare (*cc);
541 case_data_rw (*cc, key_var)->f = case_num;
543 return TRNS_CONTINUE;
547 /* Create and return a new variable in which to store the ranks of SRC_VAR
548 accoring to the rank function F.
549 VNAME is the name of the variable to be created.
550 If VNAME is NULL, then a name will be automatically chosen.
552 static struct variable *
553 create_rank_variable (struct dictionary *dict, enum RANK_FUNC f,
554 const struct variable *src_var,
558 struct variable *var = NULL;
559 char name[SHORT_NAME_LEN + 1];
562 var = dict_create_var(dict, vname, 0);
566 snprintf (name, SHORT_NAME_LEN + 1, "%c%s",
567 function_name[f][0], var_get_name (src_var));
569 var = dict_create_var(dict, name, 0);
576 snprintf(func_abb, 4, "%s", function_name[f]);
577 snprintf(name, SHORT_NAME_LEN + 1, "%s%03d", func_abb,
580 var = dict_create_var(dict, name, 0);
586 while ( NULL == var )
589 snprintf(func_abb, 3, "%s", function_name[f]);
591 snprintf(name, SHORT_NAME_LEN + 1,
592 "RNK%s%02d", func_abb, i);
594 var = dict_create_var(dict, name, 0);
601 msg(ME, _("Cannot create new rank variable. All candidates in use."));
605 var_set_both_formats (var, &dest_format[f]);
620 for (i = 0 ; i < n_rank_specs ; ++i )
621 free (rank_specs[i].destvars);
627 subcase_destroy (&sc);
635 cmd_rank (struct lexer *lexer, struct dataset *ds)
638 struct variable *order;
642 subcase_init_empty (&sc);
643 if ( !parse_rank (lexer, ds, &cmd, NULL) )
649 /* If /MISSING=INCLUDE is set, then user missing values are ignored */
650 exclude_values = cmd.miss == RANK_INCLUDE ? MV_SYSTEM : MV_ANY;
652 /* Default to /RANK if no function subcommands are given */
653 if ( !( cmd.sbc_normal || cmd.sbc_ntiles || cmd.sbc_proportion ||
654 cmd.sbc_rfraction || cmd.sbc_savage || cmd.sbc_n ||
655 cmd.sbc_percent || cmd.sbc_rank ) )
657 assert ( n_rank_specs == 0 );
659 rank_specs = xmalloc (sizeof (*rank_specs));
660 rank_specs[0].rfunc = RANK;
661 rank_specs[0].destvars =
662 xcalloc (subcase_get_n_fields (&sc), sizeof (struct variable *));
667 assert ( subcase_get_n_fields (&sc) == n_src_vars);
669 /* Create variables for all rank destinations which haven't
670 already been created with INTO.
671 Add labels to all the destination variables.
673 for (i = 0 ; i < n_rank_specs ; ++i )
676 for ( v = 0 ; v < n_src_vars ; v ++ )
678 if ( rank_specs[i].destvars[v] == NULL )
680 rank_specs[i].destvars[v] =
681 create_rank_variable (dataset_dict(ds), 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, "\n");
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 (TAT_PRINTF,
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]),
728 tab_output_text (TAT_PRINTF,
729 _("%s into %s(%s of %s BY %s)"),
730 var_get_name (src_vars[v]),
731 var_get_name (rank_specs[i].destvars[v]),
732 function_name[rank_specs[i].rfunc],
733 var_get_name (src_vars[v]),
736 ds_destroy (&varlist);
740 if ( rank_specs[i].rfunc == NORMAL ||
741 rank_specs[i].rfunc == PROPORTION )
742 tab_output_text (TAT_PRINTF,
743 _("%s into %s(%s of %s using %s)"),
744 var_get_name (src_vars[v]),
745 var_get_name (rank_specs[i].destvars[v]),
746 function_name[rank_specs[i].rfunc],
747 var_get_name (src_vars[v]),
752 tab_output_text (TAT_PRINTF,
753 _("%s into %s(%s of %s)"),
754 var_get_name (src_vars[v]),
755 var_get_name (rank_specs[i].destvars[v]),
756 function_name[rank_specs[i].rfunc],
757 var_get_name (src_vars[v])
764 if ( cmd.sbc_fraction &&
765 ( ! cmd.sbc_normal && ! cmd.sbc_proportion) )
766 msg(MW, _("FRACTION has been specified, but NORMAL and PROPORTION rank functions have not been requested. The FRACTION subcommand will be ignored.") );
768 /* Add a variable which we can sort by to get back the original
770 order = dict_create_var_assert (dataset_dict (ds), "$ORDER_", 0);
772 add_transformation (ds, create_resort_key, 0, order);
775 result = rank_cmd (ds, &sc, rank_specs, n_rank_specs);
777 /* Put the active file back in its original order. Delete
778 our sort key, which we don't need anymore. */
780 struct casereader *sorted;
782 /* FIXME: loses error conditions. */
784 proc_discard_output (ds);
785 sorted = sort_execute_1var (proc_open (ds), order);
786 result = proc_commit (ds) && result;
788 dict_delete_var (dataset_dict (ds), order);
789 result = proc_set_active_file_data (ds, sorted) && result;
795 return (result ? CMD_SUCCESS : CMD_CASCADING_FAILURE);
799 /* Parser for the variables sub command
800 Returns 1 on success */
802 rank_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd UNUSED, void *aux UNUSED)
804 lex_match (lexer, '=');
806 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL)
807 && lex_token (lexer) != T_ALL)
810 if (!parse_sort_criteria (lexer, dataset_dict (ds), &sc, &src_vars, NULL))
812 n_src_vars = subcase_get_n_fields (&sc);
814 if ( lex_match (lexer, T_BY) )
816 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
821 if (!parse_variables_const (lexer, dataset_dict (ds),
822 &group_vars, &n_group_vars,
823 PV_NO_DUPLICATE | PV_NO_SCRATCH) )
834 /* Parse the [/rank INTO var1 var2 ... varN ] clause */
836 parse_rank_function (struct lexer *lexer, struct dictionary *dict, struct cmd_rank *cmd UNUSED, enum RANK_FUNC f)
841 rank_specs = xnrealloc(rank_specs, n_rank_specs, sizeof *rank_specs);
842 rank_specs[n_rank_specs - 1].rfunc = f;
843 rank_specs[n_rank_specs - 1].destvars = NULL;
845 rank_specs[n_rank_specs - 1].destvars =
846 xcalloc (subcase_get_n_fields (&sc), sizeof (struct variable *));
848 if (lex_match_id (lexer, "INTO"))
850 struct variable *destvar;
852 while( lex_token (lexer) == T_ID )
855 if ( dict_lookup_var (dict, lex_tokid (lexer)) != NULL )
857 msg(SE, _("Variable %s already exists."), lex_tokid (lexer));
860 if ( var_count >= subcase_get_n_fields (&sc) )
862 msg(SE, _("Too many variables in INTO clause."));
866 destvar = create_rank_variable (dict, f, src_vars[var_count], lex_tokid (lexer));
867 rank_specs[n_rank_specs - 1].destvars[var_count] = destvar ;
879 rank_custom_rank (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
881 struct dictionary *dict = dataset_dict (ds);
883 return parse_rank_function (lexer, dict, cmd, RANK);
887 rank_custom_normal (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
889 struct dictionary *dict = dataset_dict (ds);
891 return parse_rank_function (lexer, dict, cmd, NORMAL);
895 rank_custom_percent (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
897 struct dictionary *dict = dataset_dict (ds);
899 return parse_rank_function (lexer, dict, cmd, PERCENT);
903 rank_custom_rfraction (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
905 struct dictionary *dict = dataset_dict (ds);
907 return parse_rank_function (lexer, dict, cmd, RFRACTION);
911 rank_custom_proportion (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
913 struct dictionary *dict = dataset_dict (ds);
915 return parse_rank_function (lexer, dict, cmd, PROPORTION);
919 rank_custom_n (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
921 struct dictionary *dict = dataset_dict (ds);
923 return parse_rank_function (lexer, dict, cmd, N);
927 rank_custom_savage (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
929 struct dictionary *dict = dataset_dict (ds);
931 return parse_rank_function (lexer, dict, cmd, SAVAGE);
936 rank_custom_ntiles (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
938 struct dictionary *dict = dataset_dict (ds);
940 if ( lex_force_match (lexer, '(') )
942 if ( lex_force_int (lexer) )
944 k_ntiles = lex_integer (lexer);
946 lex_force_match (lexer, ')');
954 return parse_rank_function (lexer, dict, cmd, NTILES);