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/dictionary.h>
23 #include <data/format.h>
24 #include <data/missing-values.h>
25 #include <data/procedure.h>
26 #include <data/variable.h>
27 #include <data/case-ordering.h>
28 #include <data/case.h>
29 #include <data/casegrouper.h>
30 #include <data/casereader.h>
31 #include <data/casewriter.h>
32 #include <language/command.h>
33 #include <language/stats/sort-criteria.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/taint.h>
36 #include <math/sort.h>
37 #include <output/table.h>
38 #include <output/manager.h>
40 #include <gsl/gsl_cdf.h>
43 #define _(msgid) gettext (msgid)
59 +fraction=fraction:!blom/tukey/vw/rankit;
60 +ties=ties:!mean/low/high/condense;
61 missing=miss:!exclude/include.
66 typedef double (*rank_function_t) (double c, double cc, double cc_1,
69 static double rank_proportion (double c, double cc, double cc_1,
72 static double rank_normal (double c, double cc, double cc_1,
75 static double rank_percent (double c, double cc, double cc_1,
78 static double rank_rfraction (double c, double cc, double cc_1,
81 static double rank_rank (double c, double cc, double cc_1,
84 static double rank_n (double c, double cc, double cc_1,
87 static double rank_savage (double c, double cc, double cc_1,
90 static double rank_ntiles (double c, double cc, double cc_1,
107 static const struct fmt_spec dest_format[n_RANK_FUNCS] = {
108 {FMT_F, 9, 3}, /* rank */
109 {FMT_F, 6, 4}, /* normal */
110 {FMT_F, 6, 2}, /* percent */
111 {FMT_F, 6, 4}, /* rfraction */
112 {FMT_F, 6, 4}, /* proportion */
113 {FMT_F, 6, 0}, /* n */
114 {FMT_F, 3, 0}, /* ntiles */
115 {FMT_F, 8, 4} /* savage */
118 static const char * const function_name[n_RANK_FUNCS] = {
129 static const rank_function_t rank_func[n_RANK_FUNCS] = {
143 enum RANK_FUNC rfunc;
144 struct variable **destvars;
148 /* Categories of missing values to exclude. */
149 static enum mv_class exclude_values;
151 static struct rank_spec *rank_specs;
152 static size_t n_rank_specs;
154 static struct case_ordering *sc;
156 static const struct variable **group_vars;
157 static size_t n_group_vars;
159 static const struct variable **src_vars;
160 static size_t n_src_vars;
165 static struct cmd_rank cmd;
167 static void rank_sorted_file (struct casereader *,
169 const struct dictionary *,
170 const struct rank_spec *rs,
173 const struct variable *rank_var);
178 static char name[10];
179 switch ( cmd.fraction )
182 strcpy (name, "BLOM");
185 strcpy (name, "RANKIT");
188 strcpy (name, "TUKEY");
199 /* Create a label on DEST_VAR, describing its derivation from SRC_VAR and F */
201 create_var_label (struct variable *dest_var,
202 const struct variable *src_var, enum RANK_FUNC f)
205 ds_init_empty (&label);
207 if ( n_group_vars > 0 )
209 struct string group_var_str;
212 ds_init_empty (&group_var_str);
214 for (g = 0 ; g < n_group_vars ; ++g )
216 if ( g > 0 ) ds_put_cstr (&group_var_str, " ");
217 ds_put_cstr (&group_var_str, var_get_name (group_vars[g]));
220 ds_put_format (&label, _("%s of %s by %s"), function_name[f],
221 var_get_name (src_var), ds_cstr (&group_var_str));
222 ds_destroy (&group_var_str);
225 ds_put_format (&label, _("%s of %s"),
226 function_name[f], var_get_name (src_var));
228 var_set_label (dest_var, ds_cstr (&label));
235 rank_cmd (struct dataset *ds, const struct case_ordering *sc,
236 const struct rank_spec *rank_specs, int n_rank_specs)
238 struct case_ordering *base_ordering;
241 const int n_splits = dict_get_split_cnt (dataset_dict (ds));
243 base_ordering = case_ordering_create (dataset_dict (ds));
244 for (i = 0; i < n_splits ; i++)
245 case_ordering_add_var (base_ordering,
246 dict_get_split_vars (dataset_dict (ds))[i],
249 for (i = 0; i < n_group_vars; i++)
250 case_ordering_add_var (base_ordering, group_vars[i], SRT_ASCEND);
251 for (i = 0 ; i < case_ordering_get_var_cnt (sc) ; ++i )
253 struct case_ordering *ordering;
254 struct casegrouper *grouper;
255 struct casereader *group;
256 struct casewriter *output;
257 struct casereader *ranked_file;
259 ordering = case_ordering_clone (base_ordering);
260 case_ordering_add_var (ordering,
261 case_ordering_get_var (sc, i),
262 case_ordering_get_direction (sc, i));
264 proc_discard_output (ds);
265 grouper = casegrouper_create_case_ordering (sort_execute (proc_open (ds),
268 output = autopaging_writer_create (dict_get_next_value_idx (
270 while (casegrouper_get_next_group (grouper, &group))
271 rank_sorted_file (group, output, dataset_dict (ds),
272 rank_specs, n_rank_specs,
274 ok = casegrouper_destroy (grouper);
275 ok = proc_commit (ds) && ok;
276 ranked_file = casewriter_make_reader (output);
277 ok = proc_set_active_file_data (ds, ranked_file) && ok;
281 case_ordering_destroy (base_ordering);
286 /* Hardly a rank function !! */
288 rank_n (double c UNUSED, double cc UNUSED, double cc_1 UNUSED,
289 int i UNUSED, double w)
296 rank_rank (double c, double cc, double cc_1,
297 int i, double w UNUSED)
312 rank = cc_1 + (c + 1.0)/ 2.0;
332 rank = cc_1 + c / 2.0 ;
347 rank_rfraction (double c, double cc, double cc_1,
350 return rank_rank (c, cc, cc_1, i, w) / w ;
355 rank_percent (double c, double cc, double cc_1,
358 return rank_rank (c, cc, cc_1, i, w) * 100.0 / w ;
363 rank_proportion (double c, double cc, double cc_1,
366 const double r = rank_rank (c, cc, cc_1, i, w) ;
370 switch ( cmd.fraction )
373 f = (r - 3.0/8.0) / (w + 0.25);
379 f = (r - 1.0/3.0) / (w + 1.0/3.0);
389 return (f > 0) ? f : SYSMIS;
393 rank_normal (double c, double cc, double cc_1,
396 double f = rank_proportion (c, cc, cc_1, i, w);
398 return gsl_cdf_ugaussian_Pinv (f);
402 rank_ntiles (double c, double cc, double cc_1,
405 double r = rank_rank (c, cc, cc_1, i, w);
408 return ( floor (( r * k_ntiles) / ( w + 1) ) + 1);
411 /* Expected value of the order statistics from an exponential distribution */
413 ee (int j, double w_star)
418 for (k = 1 ; k <= j; k++)
419 sum += 1.0 / ( w_star + 1 - k );
426 rank_savage (double c, double cc, double cc_1,
427 int i UNUSED, double w)
430 const int i_1 = floor (cc_1);
431 const int i_2 = floor (cc);
433 const double w_star = (modf (w, &int_part) == 0 ) ? w : floor (w) + 1;
435 const double g_1 = cc_1 - i_1;
436 const double g_2 = cc - i_2;
438 /* The second factor is infinite, when the first is zero.
439 Therefore, evaluate the second, only when the first is non-zero */
440 const double expr1 = (1 - g_1) ? (1 - g_1) * ee(i_1+1, w_star) : ( 1 - g_1);
441 const double expr2 = g_2 ? g_2 * ee (i_2+1, w_star) : g_2 ;
444 return ee (i_1 + 1, w_star) - 1;
446 if ( i_1 + 1 == i_2 )
447 return ( ( expr1 + expr2 )/c ) - 1;
449 if ( i_1 + 2 <= i_2 )
453 for (j = i_1 + 2 ; j <= i_2; ++j )
454 sigma += ee (j, w_star);
455 return ( (expr1 + expr2 + sigma) / c) -1;
462 rank_sorted_file (struct casereader *input,
463 struct casewriter *output,
464 const struct dictionary *dict,
465 const struct rank_spec *rs,
468 const struct variable *rank_var)
470 struct casereader *pass1, *pass2, *pass2_1;
471 struct casegrouper *tie_grouper;
478 input = casereader_create_filter_missing (input, &rank_var, 1,
479 exclude_values, output);
480 input = casereader_create_filter_weight (input, dict, NULL, output);
482 casereader_split (input, &pass1, &pass2);
484 /* Pass 1: Get total group weight. */
485 for (; casereader_read (pass1, &c); case_destroy (&c))
486 w += dict_get_case_weight (dict, &c, NULL);
487 casereader_destroy (pass1);
489 /* Pass 2: Do ranking. */
490 tie_grouper = casegrouper_create_vars (pass2, &rank_var, 1);
491 while (casegrouper_get_next_group (tie_grouper, &pass2_1))
493 struct casereader *pass2_2;
498 pass2_2 = casereader_clone (pass2_1);
499 taint_propagate (casereader_get_taint (pass2_2),
500 casewriter_get_taint (output));
502 /* Pass 2.1: Sum up weight for tied cases. */
503 for (; casereader_read (pass2_1, &c); case_destroy (&c))
504 tw += dict_get_case_weight (dict, &c, NULL);
506 casereader_destroy (pass2_1);
508 /* Pass 2.2: Rank tied cases. */
509 while (casereader_read (pass2_2, &c))
511 for (i = 0; i < n_rank_specs; ++i)
513 const struct variable *dst_var = rs[i].destvars[dest_idx];
514 double *dst_value = &case_data_rw (&c, dst_var)->f;
515 *dst_value = rank_func[rs[i].rfunc] (tw, cc, cc_1, tie_group, w);
517 casewriter_write (output, &c);
519 casereader_destroy (pass2_2);
523 casegrouper_destroy (tie_grouper);
526 /* Transformation function to enumerate all the cases */
528 create_resort_key (void *key_var_, struct ccase *cc, casenumber case_num)
530 struct variable *key_var = key_var_;
532 case_data_rw(cc, key_var)->f = case_num;
534 return TRNS_CONTINUE;
538 /* Create and return a new variable in which to store the ranks of SRC_VAR
539 accoring to the rank function F.
540 VNAME is the name of the variable to be created.
541 If VNAME is NULL, then a name will be automatically chosen.
543 static struct variable *
544 create_rank_variable (struct dictionary *dict, enum RANK_FUNC f,
545 const struct variable *src_var,
549 struct variable *var = NULL;
550 char name[SHORT_NAME_LEN + 1];
553 var = dict_create_var(dict, vname, 0);
557 snprintf (name, SHORT_NAME_LEN + 1, "%c%s",
558 function_name[f][0], var_get_name (src_var));
560 var = dict_create_var(dict, name, 0);
567 snprintf(func_abb, 4, "%s", function_name[f]);
568 snprintf(name, SHORT_NAME_LEN + 1, "%s%03d", func_abb,
571 var = dict_create_var(dict, name, 0);
577 while ( NULL == var )
580 snprintf(func_abb, 3, "%s", function_name[f]);
582 snprintf(name, SHORT_NAME_LEN + 1,
583 "RNK%s%02d", func_abb, i);
585 var = dict_create_var(dict, name, 0);
592 msg(ME, _("Cannot create new rank variable. All candidates in use."));
596 var_set_both_formats (var, &dest_format[f]);
611 for (i = 0 ; i < n_rank_specs ; ++i )
612 free (rank_specs[i].destvars);
618 case_ordering_destroy (sc);
627 cmd_rank (struct lexer *lexer, struct dataset *ds)
630 struct variable *order;
634 if ( !parse_rank (lexer, ds, &cmd, NULL) )
640 /* If /MISSING=INCLUDE is set, then user missing values are ignored */
641 exclude_values = cmd.miss == RANK_INCLUDE ? MV_SYSTEM : MV_ANY;
643 /* Default to /RANK if no function subcommands are given */
644 if ( !( cmd.sbc_normal || cmd.sbc_ntiles || cmd.sbc_proportion ||
645 cmd.sbc_rfraction || cmd.sbc_savage || cmd.sbc_n ||
646 cmd.sbc_percent || cmd.sbc_rank ) )
648 assert ( n_rank_specs == 0 );
650 rank_specs = xmalloc (sizeof (*rank_specs));
651 rank_specs[0].rfunc = RANK;
652 rank_specs[0].destvars =
653 xcalloc (case_ordering_get_var_cnt (sc), sizeof (struct variable *));
658 assert ( case_ordering_get_var_cnt (sc) == n_src_vars);
660 /* Create variables for all rank destinations which haven't
661 already been created with INTO.
662 Add labels to all the destination variables.
664 for (i = 0 ; i < n_rank_specs ; ++i )
667 for ( v = 0 ; v < n_src_vars ; v ++ )
669 if ( rank_specs[i].destvars[v] == NULL )
671 rank_specs[i].destvars[v] =
672 create_rank_variable (dataset_dict(ds), rank_specs[i].rfunc, src_vars[v], NULL);
675 create_var_label ( rank_specs[i].destvars[v],
677 rank_specs[i].rfunc);
681 if ( cmd.print == RANK_YES )
685 tab_output_text (0, _("Variables Created By RANK"));
686 tab_output_text (0, "\n");
688 for (i = 0 ; i < n_rank_specs ; ++i )
690 for ( v = 0 ; v < n_src_vars ; v ++ )
692 if ( n_group_vars > 0 )
694 struct string varlist;
697 ds_init_empty (&varlist);
698 for ( g = 0 ; g < n_group_vars ; ++g )
700 ds_put_cstr (&varlist, var_get_name (group_vars[g]));
702 if ( g < n_group_vars - 1)
703 ds_put_cstr (&varlist, " ");
706 if ( rank_specs[i].rfunc == NORMAL ||
707 rank_specs[i].rfunc == PROPORTION )
708 tab_output_text (TAT_PRINTF,
709 _("%s into %s(%s of %s using %s BY %s)"),
710 var_get_name (src_vars[v]),
711 var_get_name (rank_specs[i].destvars[v]),
712 function_name[rank_specs[i].rfunc],
713 var_get_name (src_vars[v]),
719 tab_output_text (TAT_PRINTF,
720 _("%s into %s(%s of %s BY %s)"),
721 var_get_name (src_vars[v]),
722 var_get_name (rank_specs[i].destvars[v]),
723 function_name[rank_specs[i].rfunc],
724 var_get_name (src_vars[v]),
727 ds_destroy (&varlist);
731 if ( rank_specs[i].rfunc == NORMAL ||
732 rank_specs[i].rfunc == PROPORTION )
733 tab_output_text (TAT_PRINTF,
734 _("%s into %s(%s of %s using %s)"),
735 var_get_name (src_vars[v]),
736 var_get_name (rank_specs[i].destvars[v]),
737 function_name[rank_specs[i].rfunc],
738 var_get_name (src_vars[v]),
743 tab_output_text (TAT_PRINTF,
744 _("%s into %s(%s of %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])
755 if ( cmd.sbc_fraction &&
756 ( ! cmd.sbc_normal && ! cmd.sbc_proportion) )
757 msg(MW, _("FRACTION has been specified, but NORMAL and PROPORTION rank functions have not been requested. The FRACTION subcommand will be ignored.") );
759 /* Add a variable which we can sort by to get back the original
761 order = dict_create_var_assert (dataset_dict (ds), "$ORDER_", 0);
763 add_transformation (ds, create_resort_key, 0, order);
766 result = rank_cmd (ds, sc, rank_specs, n_rank_specs);
768 /* Put the active file back in its original order. Delete
769 our sort key, which we don't need anymore. */
771 struct case_ordering *ordering = case_ordering_create (dataset_dict (ds));
772 struct casereader *sorted;
773 case_ordering_add_var (ordering, order, SRT_ASCEND);
774 /* FIXME: loses error conditions. */
775 proc_discard_output (ds);
776 sorted = sort_execute (proc_open (ds), ordering);
777 result = proc_commit (ds) && result;
779 dict_delete_var (dataset_dict (ds), order);
780 result = proc_set_active_file_data (ds, sorted) && result;
786 return (result ? CMD_SUCCESS : CMD_CASCADING_FAILURE);
790 /* Parser for the variables sub command
791 Returns 1 on success */
793 rank_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd UNUSED, void *aux UNUSED)
795 lex_match (lexer, '=');
797 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL)
798 && lex_token (lexer) != T_ALL)
801 sc = parse_case_ordering (lexer, dataset_dict (ds), NULL);
804 case_ordering_get_vars (sc, &src_vars, &n_src_vars);
806 if ( lex_match (lexer, T_BY) )
808 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
813 if (!parse_variables_const (lexer, dataset_dict (ds),
814 &group_vars, &n_group_vars,
815 PV_NO_DUPLICATE | PV_NO_SCRATCH) )
826 /* Parse the [/rank INTO var1 var2 ... varN ] clause */
828 parse_rank_function (struct lexer *lexer, struct dictionary *dict, struct cmd_rank *cmd UNUSED, enum RANK_FUNC f)
833 rank_specs = xnrealloc(rank_specs, n_rank_specs, sizeof *rank_specs);
834 rank_specs[n_rank_specs - 1].rfunc = f;
835 rank_specs[n_rank_specs - 1].destvars = NULL;
837 rank_specs[n_rank_specs - 1].destvars =
838 xcalloc (case_ordering_get_var_cnt (sc),
839 sizeof (struct variable *));
841 if (lex_match_id (lexer, "INTO"))
843 struct variable *destvar;
845 while( lex_token (lexer) == T_ID )
848 if ( dict_lookup_var (dict, lex_tokid (lexer)) != NULL )
850 msg(SE, _("Variable %s already exists."), lex_tokid (lexer));
853 if ( var_count >= case_ordering_get_var_cnt (sc) )
855 msg(SE, _("Too many variables in INTO clause."));
859 destvar = create_rank_variable (dict, f, src_vars[var_count], lex_tokid (lexer));
860 rank_specs[n_rank_specs - 1].destvars[var_count] = destvar ;
872 rank_custom_rank (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
874 struct dictionary *dict = dataset_dict (ds);
876 return parse_rank_function (lexer, dict, cmd, RANK);
880 rank_custom_normal (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
882 struct dictionary *dict = dataset_dict (ds);
884 return parse_rank_function (lexer, dict, cmd, NORMAL);
888 rank_custom_percent (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
890 struct dictionary *dict = dataset_dict (ds);
892 return parse_rank_function (lexer, dict, cmd, PERCENT);
896 rank_custom_rfraction (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
898 struct dictionary *dict = dataset_dict (ds);
900 return parse_rank_function (lexer, dict, cmd, RFRACTION);
904 rank_custom_proportion (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
906 struct dictionary *dict = dataset_dict (ds);
908 return parse_rank_function (lexer, dict, cmd, PROPORTION);
912 rank_custom_n (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
914 struct dictionary *dict = dataset_dict (ds);
916 return parse_rank_function (lexer, dict, cmd, N);
920 rank_custom_savage (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
922 struct dictionary *dict = dataset_dict (ds);
924 return parse_rank_function (lexer, dict, cmd, SAVAGE);
929 rank_custom_ntiles (struct lexer *lexer, struct dataset *ds, struct cmd_rank *cmd, void *aux UNUSED )
931 struct dictionary *dict = dataset_dict (ds);
933 if ( lex_force_match (lexer, '(') )
935 if ( lex_force_int (lexer) )
937 k_ntiles = lex_integer (lexer);
939 lex_force_match (lexer, ')');
947 return parse_rank_function (lexer, dict, cmd, NTILES);