1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2005, 2006, 2007 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-ordering.h>
23 #include <data/case.h>
24 #include <data/casegrouper.h>
25 #include <data/casereader.h>
26 #include <data/casewriter.h>
27 #include <data/dictionary.h>
28 #include <data/format.h>
29 #include <data/missing-values.h>
30 #include <data/procedure.h>
31 #include <data/short-names.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 case_ordering *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 case_ordering *sc,
237 const struct rank_spec *rank_specs, int n_rank_specs)
239 struct dictionary *d = dataset_dict (ds);
243 for (i = 0 ; i < case_ordering_get_var_cnt (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_next_value_idx (d));
254 while (casegrouper_get_next_group (split_grouper, &split_group))
256 struct case_ordering *ordering;
257 struct casereader *ordered;
258 struct casegrouper *by_grouper;
259 struct casereader *by_group;
262 /* Sort this split group by the BY variables as primary
263 keys and the rank variable as secondary key. */
264 ordering = case_ordering_create ();
265 for (j = 0; j < n_group_vars; j++)
266 case_ordering_add_var (ordering, group_vars[j], SRT_ASCEND);
267 case_ordering_add_var (ordering,
268 case_ordering_get_var (sc, i),
269 case_ordering_get_direction (sc, i));
270 ordered = sort_execute (split_group, ordering);
272 /* Rank the rank variable within this split group. */
273 by_grouper = casegrouper_create_vars (ordered,
274 group_vars, n_group_vars);
275 while (casegrouper_get_next_group (by_grouper, &by_group))
277 /* Rank the rank variable within this BY group
278 within the split group. */
280 rank_sorted_file (by_group, output, d, rank_specs, n_rank_specs,
283 ok = casegrouper_destroy (by_grouper) && ok;
285 ok = casegrouper_destroy (split_grouper);
286 ok = proc_commit (ds) && ok;
287 ok = (proc_set_active_file_data (ds, casewriter_make_reader (output))
296 /* Hardly a rank function !! */
298 rank_n (double c UNUSED, double cc UNUSED, double cc_1 UNUSED,
299 int i UNUSED, double w)
306 rank_rank (double c, double cc, double cc_1,
307 int i, double w UNUSED)
322 rank = cc_1 + (c + 1.0)/ 2.0;
342 rank = cc_1 + c / 2.0 ;
357 rank_rfraction (double c, double cc, double cc_1,
360 return rank_rank (c, cc, cc_1, i, w) / w ;
365 rank_percent (double c, double cc, double cc_1,
368 return rank_rank (c, cc, cc_1, i, w) * 100.0 / w ;
373 rank_proportion (double c, double cc, double cc_1,
376 const double r = rank_rank (c, cc, cc_1, i, w) ;
380 switch ( cmd.fraction )
383 f = (r - 3.0/8.0) / (w + 0.25);
389 f = (r - 1.0/3.0) / (w + 1.0/3.0);
399 return (f > 0) ? f : SYSMIS;
403 rank_normal (double c, double cc, double cc_1,
406 double f = rank_proportion (c, cc, cc_1, i, w);
408 return gsl_cdf_ugaussian_Pinv (f);
412 rank_ntiles (double c, double cc, double cc_1,
415 double r = rank_rank (c, cc, cc_1, i, w);
418 return ( floor (( r * k_ntiles) / ( w + 1) ) + 1);
421 /* Expected value of the order statistics from an exponential distribution */
423 ee (int j, double w_star)
428 for (k = 1 ; k <= j; k++)
429 sum += 1.0 / ( w_star + 1 - k );
436 rank_savage (double c, double cc, double cc_1,
437 int i UNUSED, double w)
440 const int i_1 = floor (cc_1);
441 const int i_2 = floor (cc);
443 const double w_star = (modf (w, &int_part) == 0 ) ? w : floor (w) + 1;
445 const double g_1 = cc_1 - i_1;
446 const double g_2 = cc - i_2;
448 /* The second factor is infinite, when the first is zero.
449 Therefore, evaluate the second, only when the first is non-zero */
450 const double expr1 = (1 - g_1) ? (1 - g_1) * ee(i_1+1, w_star) : ( 1 - g_1);
451 const double expr2 = g_2 ? g_2 * ee (i_2+1, w_star) : g_2 ;
454 return ee (i_1 + 1, w_star) - 1;
456 if ( i_1 + 1 == i_2 )
457 return ( ( expr1 + expr2 )/c ) - 1;
459 if ( i_1 + 2 <= i_2 )
463 for (j = i_1 + 2 ; j <= i_2; ++j )
464 sigma += ee (j, w_star);
465 return ( (expr1 + expr2 + sigma) / c) -1;
472 rank_sorted_file (struct casereader *input,
473 struct casewriter *output,
474 const struct dictionary *dict,
475 const struct rank_spec *rs,
478 const struct variable *rank_var)
480 struct casereader *pass1, *pass2, *pass2_1;
481 struct casegrouper *tie_grouper;
488 input = casereader_create_filter_missing (input, &rank_var, 1,
489 exclude_values, NULL, output);
490 input = casereader_create_filter_weight (input, dict, NULL, output);
492 casereader_split (input, &pass1, &pass2);
494 /* Pass 1: Get total group weight. */
495 for (; casereader_read (pass1, &c); case_destroy (&c))
496 w += dict_get_case_weight (dict, &c, NULL);
497 casereader_destroy (pass1);
499 /* Pass 2: Do ranking. */
500 tie_grouper = casegrouper_create_vars (pass2, &rank_var, 1);
501 while (casegrouper_get_next_group (tie_grouper, &pass2_1))
503 struct casereader *pass2_2;
508 pass2_2 = casereader_clone (pass2_1);
509 taint_propagate (casereader_get_taint (pass2_2),
510 casewriter_get_taint (output));
512 /* Pass 2.1: Sum up weight for tied cases. */
513 for (; casereader_read (pass2_1, &c); case_destroy (&c))
514 tw += dict_get_case_weight (dict, &c, NULL);
516 casereader_destroy (pass2_1);
518 /* Pass 2.2: Rank tied cases. */
519 while (casereader_read (pass2_2, &c))
521 for (i = 0; i < n_rank_specs; ++i)
523 const struct variable *dst_var = rs[i].destvars[dest_idx];
524 double *dst_value = &case_data_rw (&c, dst_var)->f;
525 *dst_value = rank_func[rs[i].rfunc] (tw, cc, cc_1, tie_group, w);
527 casewriter_write (output, &c);
529 casereader_destroy (pass2_2);
533 casegrouper_destroy (tie_grouper);
536 /* Transformation function to enumerate all the cases */
538 create_resort_key (void *key_var_, struct ccase *cc, casenumber case_num)
540 struct variable *key_var = key_var_;
542 case_data_rw(cc, key_var)->f = case_num;
544 return TRNS_CONTINUE;
548 /* Create and return a new variable in which to store the ranks of SRC_VAR
549 accoring to the rank function F.
550 VNAME is the name of the variable to be created.
551 If VNAME is NULL, then a name will be automatically chosen.
553 static struct variable *
554 create_rank_variable (struct dictionary *dict, enum RANK_FUNC f,
555 const struct variable *src_var,
559 struct variable *var = NULL;
560 char name[SHORT_NAME_LEN + 1];
563 var = dict_create_var(dict, vname, 0);
567 snprintf (name, SHORT_NAME_LEN + 1, "%c%s",
568 function_name[f][0], var_get_name (src_var));
570 var = dict_create_var(dict, name, 0);
577 snprintf(func_abb, 4, "%s", function_name[f]);
578 snprintf(name, SHORT_NAME_LEN + 1, "%s%03d", func_abb,
581 var = dict_create_var(dict, name, 0);
587 while ( NULL == var )
590 snprintf(func_abb, 3, "%s", function_name[f]);
592 snprintf(name, SHORT_NAME_LEN + 1,
593 "RNK%s%02d", func_abb, i);
595 var = dict_create_var(dict, name, 0);
602 msg(ME, _("Cannot create new rank variable. All candidates in use."));
606 var_set_both_formats (var, &dest_format[f]);
621 for (i = 0 ; i < n_rank_specs ; ++i )
622 free (rank_specs[i].destvars);
628 case_ordering_destroy (sc);
637 cmd_rank (struct lexer *lexer, struct dataset *ds)
640 struct variable *order;
644 if ( !parse_rank (lexer, ds, &cmd, NULL) )
650 /* If /MISSING=INCLUDE is set, then user missing values are ignored */
651 exclude_values = cmd.miss == RANK_INCLUDE ? MV_SYSTEM : MV_ANY;
653 /* Default to /RANK if no function subcommands are given */
654 if ( !( cmd.sbc_normal || cmd.sbc_ntiles || cmd.sbc_proportion ||
655 cmd.sbc_rfraction || cmd.sbc_savage || cmd.sbc_n ||
656 cmd.sbc_percent || cmd.sbc_rank ) )
658 assert ( n_rank_specs == 0 );
660 rank_specs = xmalloc (sizeof (*rank_specs));
661 rank_specs[0].rfunc = RANK;
662 rank_specs[0].destvars =
663 xcalloc (case_ordering_get_var_cnt (sc), sizeof (struct variable *));
668 assert ( case_ordering_get_var_cnt (sc) == n_src_vars);
670 /* Create variables for all rank destinations which haven't
671 already been created with INTO.
672 Add labels to all the destination variables.
674 for (i = 0 ; i < n_rank_specs ; ++i )
677 for ( v = 0 ; v < n_src_vars ; v ++ )
679 if ( rank_specs[i].destvars[v] == NULL )
681 rank_specs[i].destvars[v] =
682 create_rank_variable (dataset_dict(ds), rank_specs[i].rfunc, src_vars[v], NULL);
685 create_var_label ( rank_specs[i].destvars[v],
687 rank_specs[i].rfunc);
691 if ( cmd.print == RANK_YES )
695 tab_output_text (0, _("Variables Created By RANK"));
696 tab_output_text (0, "\n");
698 for (i = 0 ; i < n_rank_specs ; ++i )
700 for ( v = 0 ; v < n_src_vars ; v ++ )
702 if ( n_group_vars > 0 )
704 struct string varlist;
707 ds_init_empty (&varlist);
708 for ( g = 0 ; g < n_group_vars ; ++g )
710 ds_put_cstr (&varlist, var_get_name (group_vars[g]));
712 if ( g < n_group_vars - 1)
713 ds_put_cstr (&varlist, " ");
716 if ( rank_specs[i].rfunc == NORMAL ||
717 rank_specs[i].rfunc == PROPORTION )
718 tab_output_text (TAT_PRINTF,
719 _("%s into %s(%s of %s using %s BY %s)"),
720 var_get_name (src_vars[v]),
721 var_get_name (rank_specs[i].destvars[v]),
722 function_name[rank_specs[i].rfunc],
723 var_get_name (src_vars[v]),
729 tab_output_text (TAT_PRINTF,
730 _("%s into %s(%s of %s BY %s)"),
731 var_get_name (src_vars[v]),
732 var_get_name (rank_specs[i].destvars[v]),
733 function_name[rank_specs[i].rfunc],
734 var_get_name (src_vars[v]),
737 ds_destroy (&varlist);
741 if ( rank_specs[i].rfunc == NORMAL ||
742 rank_specs[i].rfunc == PROPORTION )
743 tab_output_text (TAT_PRINTF,
744 _("%s into %s(%s of %s using %s)"),
745 var_get_name (src_vars[v]),
746 var_get_name (rank_specs[i].destvars[v]),
747 function_name[rank_specs[i].rfunc],
748 var_get_name (src_vars[v]),
753 tab_output_text (TAT_PRINTF,
754 _("%s into %s(%s of %s)"),
755 var_get_name (src_vars[v]),
756 var_get_name (rank_specs[i].destvars[v]),
757 function_name[rank_specs[i].rfunc],
758 var_get_name (src_vars[v])
765 if ( cmd.sbc_fraction &&
766 ( ! cmd.sbc_normal && ! cmd.sbc_proportion) )
767 msg(MW, _("FRACTION has been specified, but NORMAL and PROPORTION rank functions have not been requested. The FRACTION subcommand will be ignored.") );
769 /* Add a variable which we can sort by to get back the original
771 order = dict_create_var_assert (dataset_dict (ds), "$ORDER_", 0);
773 add_transformation (ds, create_resort_key, 0, order);
776 result = rank_cmd (ds, sc, rank_specs, n_rank_specs);
778 /* Put the active file back in its original order. Delete
779 our sort key, which we don't need anymore. */
781 struct case_ordering *ordering = case_ordering_create ();
782 struct casereader *sorted;
783 case_ordering_add_var (ordering, order, SRT_ASCEND);
784 /* FIXME: loses error conditions. */
785 proc_discard_output (ds);
786 sorted = sort_execute (proc_open (ds), ordering);
787 result = proc_commit (ds) && result;
789 dict_delete_var (dataset_dict (ds), order);
790 result = proc_set_active_file_data (ds, sorted) && result;
796 return (result ? CMD_SUCCESS : CMD_CASCADING_FAILURE);
800 /* Parser for the variables sub command
801 Returns 1 on success */
803 rank_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd UNUSED, void *aux UNUSED)
805 lex_match (lexer, '=');
807 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL)
808 && lex_token (lexer) != T_ALL)
811 sc = parse_case_ordering (lexer, dataset_dict (ds), NULL);
814 case_ordering_get_vars (sc, &src_vars, &n_src_vars);
816 if ( lex_match (lexer, T_BY) )
818 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
823 if (!parse_variables_const (lexer, dataset_dict (ds),
824 &group_vars, &n_group_vars,
825 PV_NO_DUPLICATE | PV_NO_SCRATCH) )
836 /* Parse the [/rank INTO var1 var2 ... varN ] clause */
838 parse_rank_function (struct lexer *lexer, struct dictionary *dict, struct cmd_rank *cmd UNUSED, enum RANK_FUNC f)
843 rank_specs = xnrealloc(rank_specs, n_rank_specs, sizeof *rank_specs);
844 rank_specs[n_rank_specs - 1].rfunc = f;
845 rank_specs[n_rank_specs - 1].destvars = NULL;
847 rank_specs[n_rank_specs - 1].destvars =
848 xcalloc (case_ordering_get_var_cnt (sc),
849 sizeof (struct variable *));
851 if (lex_match_id (lexer, "INTO"))
853 struct variable *destvar;
855 while( lex_token (lexer) == T_ID )
858 if ( dict_lookup_var (dict, lex_tokid (lexer)) != NULL )
860 msg(SE, _("Variable %s already exists."), lex_tokid (lexer));
863 if ( var_count >= case_ordering_get_var_cnt (sc) )
865 msg(SE, _("Too many variables in INTO clause."));
869 destvar = create_rank_variable (dict, f, src_vars[var_count], lex_tokid (lexer));
870 rank_specs[n_rank_specs - 1].destvars[var_count] = destvar ;
882 rank_custom_rank (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
884 struct dictionary *dict = dataset_dict (ds);
886 return parse_rank_function (lexer, dict, cmd, RANK);
890 rank_custom_normal (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
892 struct dictionary *dict = dataset_dict (ds);
894 return parse_rank_function (lexer, dict, cmd, NORMAL);
898 rank_custom_percent (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
900 struct dictionary *dict = dataset_dict (ds);
902 return parse_rank_function (lexer, dict, cmd, PERCENT);
906 rank_custom_rfraction (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
908 struct dictionary *dict = dataset_dict (ds);
910 return parse_rank_function (lexer, dict, cmd, RFRACTION);
914 rank_custom_proportion (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
916 struct dictionary *dict = dataset_dict (ds);
918 return parse_rank_function (lexer, dict, cmd, PROPORTION);
922 rank_custom_n (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
924 struct dictionary *dict = dataset_dict (ds);
926 return parse_rank_function (lexer, dict, cmd, N);
930 rank_custom_savage (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
932 struct dictionary *dict = dataset_dict (ds);
934 return parse_rank_function (lexer, dict, cmd, SAVAGE);
939 rank_custom_ntiles (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
941 struct dictionary *dict = dataset_dict (ds);
943 if ( lex_force_match (lexer, '(') )
945 if ( lex_force_int (lexer) )
947 k_ntiles = lex_integer (lexer);
949 lex_force_match (lexer, ')');
957 return parse_rank_function (lexer, dict, cmd, NTILES);