1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2005, 2006, 2007, 2009, 2010, 2011, 2012 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 "data/case.h"
20 #include "data/casegrouper.h"
21 #include "data/casereader.h"
22 #include "data/dataset.h"
23 #include "data/dictionary.h"
24 #include "data/format.h"
25 #include "data/variable.h"
26 #include "data/subcase.h"
27 #include "data/casewriter.h"
28 #include "data/short-names.h"
30 #include "language/command.h"
31 #include "language/lexer/lexer.h"
32 #include "language/lexer/variable-parser.h"
33 #include "language/stats/sort-criteria.h"
35 #include "math/sort.h"
37 #include "libpspp/assertion.h"
38 #include "libpspp/misc.h"
39 #include "libpspp/taint.h"
40 #include "libpspp/pool.h"
41 #include "libpspp/message.h"
44 #include "output/tab.h"
48 #include <gsl/gsl_cdf.h>
51 #define _(msgid) gettext (msgid)
52 #define N_(msgid) (msgid)
56 typedef double (*rank_function_t) (const struct rank*, double c, double cc, double cc_1,
59 static double rank_proportion (const struct rank *, double c, double cc, double cc_1,
62 static double rank_normal (const struct rank *, double c, double cc, double cc_1,
65 static double rank_percent (const struct rank *, double c, double cc, double cc_1,
68 static double rank_rfraction (const struct rank *, double c, double cc, double cc_1,
71 static double rank_rank (const struct rank *, double c, double cc, double cc_1,
74 static double rank_n (const struct rank *, double c, double cc, double cc_1,
77 static double rank_savage (const struct rank *, double c, double cc, double cc_1,
80 static double rank_ntiles (const struct rank *, double c, double cc, double cc_1,
97 static const struct fmt_spec dest_format[n_RANK_FUNCS] = {
98 {FMT_F, 9, 3}, /* rank */
99 {FMT_F, 6, 4}, /* normal */
100 {FMT_F, 6, 2}, /* percent */
101 {FMT_F, 6, 4}, /* rfraction */
102 {FMT_F, 6, 4}, /* proportion */
103 {FMT_F, 6, 0}, /* n */
104 {FMT_F, 3, 0}, /* ntiles */
105 {FMT_F, 8, 4} /* savage */
108 static const char * const function_name[n_RANK_FUNCS] = {
119 static const rank_function_t rank_func[n_RANK_FUNCS] = {
149 enum rank_func rfunc;
150 struct variable **destvars;
154 /* Create and return a new variable in which to store the ranks of SRC_VAR
155 accoring to the rank function F.
156 VNAME is the name of the variable to be created.
157 If VNAME is NULL, then a name will be automatically chosen.
159 static struct variable *
160 create_rank_variable (struct dictionary *dict, enum rank_func f,
161 const struct variable *src_var,
165 struct variable *var = NULL;
166 char name[SHORT_NAME_LEN + 1];
169 var = dict_create_var(dict, vname, 0);
173 snprintf (name, SHORT_NAME_LEN + 1, "%c%s",
174 function_name[f][0], var_get_name (src_var));
176 var = dict_create_var(dict, name, 0);
182 snprintf(func_abb, 4, "%s", function_name[f]);
183 snprintf(name, SHORT_NAME_LEN + 1, "%s%03d", func_abb,
186 var = dict_create_var(dict, name, 0);
192 while ( NULL == var )
195 snprintf(func_abb, 3, "%s", function_name[f]);
197 snprintf(name, SHORT_NAME_LEN + 1,
198 "RNK%s%02d", func_abb, i);
200 var = dict_create_var(dict, name, 0);
207 msg(ME, _("Cannot create new rank variable. All candidates in use."));
211 var_set_both_formats (var, &dest_format[f]);
218 struct dictionary *dict;
222 const struct variable **vars;
225 const struct variable **group_vars;
229 enum mv_class exclude;
231 struct rank_spec *rs;
236 enum fraction fraction;
241 /* Pool on which cell functions may allocate data */
247 destroy_rank (struct rank *rank)
250 free (rank->group_vars);
251 subcase_destroy (&rank->sc);
252 pool_destroy (rank->pool);
256 parse_into (struct lexer *lexer, struct rank *cmd)
259 struct rank_spec *rs = NULL;
261 cmd->rs = pool_realloc (cmd->pool, cmd->rs, sizeof (*cmd->rs) * (cmd->n_rs + 1));
262 rs = &cmd->rs[cmd->n_rs];
264 if (lex_match_id (lexer, "RANK"))
268 else if (lex_match_id (lexer, "NORMAL"))
272 else if (lex_match_id (lexer, "RFRACTION"))
274 rs->rfunc = RFRACTION;
276 else if (lex_match_id (lexer, "N"))
280 else if (lex_match_id (lexer, "SAVAGE"))
284 else if (lex_match_id (lexer, "PERCENT"))
288 else if (lex_match_id (lexer, "PROPORTION"))
290 rs->rfunc = PROPORTION;
292 else if (lex_match_id (lexer, "NTILES"))
294 if ( !lex_force_match (lexer, T_LPAREN))
297 if (! lex_force_int (lexer) )
300 cmd->k_ntiles = lex_integer (lexer);
303 if ( !lex_force_match (lexer, T_RPAREN))
315 rs->destvars = pool_calloc (cmd->pool, cmd->n_vars, sizeof (*rs->destvars));
317 if (lex_match_id (lexer, "INTO"))
319 while( lex_token (lexer) == T_ID )
321 const char *name = lex_tokcstr (lexer);
322 if ( dict_lookup_var (cmd->dict, name) != NULL )
324 msg (SE, _("Variable %s already exists."), name);
328 if ( var_count >= subcase_get_n_fields (&cmd->sc) )
330 msg (SE, _("Too many variables in INTO clause."));
333 rs->destvars[var_count] =
334 create_rank_variable (cmd->dict, rs->rfunc, cmd->vars[var_count], name);
343 /* Hardly a rank function !! */
345 rank_n (const struct rank *cmd UNUSED, double c UNUSED, double cc UNUSED, double cc_1 UNUSED,
346 int i UNUSED, double w)
353 rank_rank (const struct rank *cmd, double c, double cc, double cc_1,
354 int i, double w UNUSED)
369 rank = cc_1 + (c + 1.0)/ 2.0;
389 rank = cc_1 + c / 2.0 ;
404 rank_rfraction (const struct rank *cmd, double c, double cc, double cc_1,
407 return rank_rank (cmd, c, cc, cc_1, i, w) / w ;
412 rank_percent (const struct rank *cmd, double c, double cc, double cc_1,
415 return rank_rank (cmd, c, cc, cc_1, i, w) * 100.0 / w ;
420 rank_proportion (const struct rank *cmd, double c, double cc, double cc_1,
423 const double r = rank_rank (cmd, c, cc, cc_1, i, w) ;
427 switch ( cmd->fraction )
430 f = (r - 3.0/8.0) / (w + 0.25);
436 f = (r - 1.0/3.0) / (w + 1.0/3.0);
446 return (f > 0) ? f : SYSMIS;
450 rank_normal (const struct rank *cmd, double c, double cc, double cc_1,
453 double f = rank_proportion (cmd, c, cc, cc_1, i, w);
455 return gsl_cdf_ugaussian_Pinv (f);
459 rank_ntiles (const struct rank *cmd, double c, double cc, double cc_1,
462 double r = rank_rank (cmd, c, cc, cc_1, i, w);
465 return ( floor (( r * cmd->k_ntiles) / ( w + 1) ) + 1);
468 /* Expected value of the order statistics from an exponential distribution */
470 ee (int j, double w_star)
475 for (k = 1 ; k <= j; k++)
476 sum += 1.0 / ( w_star + 1 - k );
483 rank_savage (const struct rank *cmd UNUSED, double c, double cc, double cc_1,
484 int i UNUSED, double w)
487 const int i_1 = floor (cc_1);
488 const int i_2 = floor (cc);
490 const double w_star = (modf (w, &int_part) == 0 ) ? w : floor (w) + 1;
492 const double g_1 = cc_1 - i_1;
493 const double g_2 = cc - i_2;
495 /* The second factor is infinite, when the first is zero.
496 Therefore, evaluate the second, only when the first is non-zero */
497 const double expr1 = (1 - g_1) ? (1 - g_1) * ee(i_1+1, w_star) : ( 1 - g_1);
498 const double expr2 = g_2 ? g_2 * ee (i_2+1, w_star) : g_2 ;
501 return ee (i_1 + 1, w_star) - 1;
503 if ( i_1 + 1 == i_2 )
504 return ( ( expr1 + expr2 )/c ) - 1;
506 if ( i_1 + 2 <= i_2 )
510 for (j = i_1 + 2 ; j <= i_2; ++j )
511 sigma += ee (j, w_star);
512 return ( (expr1 + expr2 + sigma) / c) -1;
520 rank_sorted_file (struct casereader *input,
521 struct casewriter *output,
522 const struct dictionary *dict,
524 const struct rank *cmd
527 struct casereader *pass1, *pass2, *pass2_1;
528 struct casegrouper *tie_grouper;
534 input = casereader_create_filter_missing (input, &cmd->vars[dest_idx], 1,
535 cmd->exclude, NULL, output);
536 input = casereader_create_filter_weight (input, dict, NULL, output);
538 casereader_split (input, &pass1, &pass2);
540 /* Pass 1: Get total group weight. */
541 for (; (c = casereader_read (pass1)) != NULL; case_unref (c))
542 w += dict_get_case_weight (dict, c, NULL);
543 casereader_destroy (pass1);
545 /* Pass 2: Do ranking. */
546 tie_grouper = casegrouper_create_vars (pass2, &cmd->vars[dest_idx], 1);
547 while (casegrouper_get_next_group (tie_grouper, &pass2_1))
549 struct casereader *pass2_2;
554 pass2_2 = casereader_clone (pass2_1);
555 taint_propagate (casereader_get_taint (pass2_2),
556 casewriter_get_taint (output));
558 /* Pass 2.1: Sum up weight for tied cases. */
559 for (; (c = casereader_read (pass2_1)) != NULL; case_unref (c))
560 tw += dict_get_case_weight (dict, c, NULL);
562 casereader_destroy (pass2_1);
564 /* Pass 2.2: Rank tied cases. */
565 while ((c = casereader_read (pass2_2)) != NULL)
567 c = case_unshare (c);
568 for (i = 0; i < cmd->n_rs; ++i)
570 const struct variable *dst_var = cmd->rs[i].destvars[dest_idx];
571 double *dst_value = &case_data_rw (c, dst_var)->f;
572 *dst_value = rank_func[cmd->rs[i].rfunc] (cmd, tw, cc, cc_1, tie_group, w);
574 casewriter_write (output, c);
576 casereader_destroy (pass2_2);
580 casegrouper_destroy (tie_grouper);
584 /* Transformation function to enumerate all the cases */
586 create_resort_key (void *key_var_, struct ccase **cc, casenumber case_num)
588 struct variable *key_var = key_var_;
590 *cc = case_unshare (*cc);
591 case_data_rw (*cc, key_var)->f = case_num;
593 return TRNS_CONTINUE;
597 rank_cmd (struct dataset *ds, const struct rank *cmd);
601 fraction_name (const struct rank *cmd)
603 static char name[10];
604 switch (cmd->fraction )
607 strcpy (name, "BLOM");
610 strcpy (name, "RANKIT");
613 strcpy (name, "TUKEY");
624 /* Create a label on DEST_VAR, describing its derivation from SRC_VAR and F */
626 create_var_label (struct rank *cmd, struct variable *dest_var,
627 const struct variable *src_var, enum rank_func f)
630 ds_init_empty (&label);
632 if ( cmd->n_group_vars > 0 )
634 struct string group_var_str;
637 ds_init_empty (&group_var_str);
639 for (g = 0 ; g < cmd->n_group_vars ; ++g )
641 if ( g > 0 ) ds_put_cstr (&group_var_str, " ");
642 ds_put_cstr (&group_var_str, var_get_name (cmd->group_vars[g]));
645 ds_put_format (&label, _("%s of %s by %s"), function_name[f],
646 var_get_name (src_var), ds_cstr (&group_var_str));
647 ds_destroy (&group_var_str);
650 ds_put_format (&label, _("%s of %s"),
651 function_name[f], var_get_name (src_var));
653 var_set_label (dest_var, ds_cstr (&label), false);
659 cmd_rank (struct lexer *lexer, struct dataset *ds)
662 struct variable *order;
666 subcase_init_empty (&rank.sc);
670 rank.exclude = MV_ANY;
671 rank.n_group_vars = 0;
672 rank.group_vars = NULL;
673 rank.dict = dataset_dict (ds);
674 rank.ties = TIES_MEAN;
675 rank.fraction = FRAC_BLOM;
677 rank.pool = pool_create ();
679 if (lex_match_id (lexer, "VARIABLES"))
680 lex_force_match (lexer, T_EQUALS);
682 if (!parse_sort_criteria (lexer, rank.dict,
687 rank.n_vars = rank.sc.n_fields;
689 if (lex_match (lexer, T_BY) )
691 if ( ! parse_variables_const (lexer, rank.dict,
692 &rank.group_vars, &rank.n_group_vars,
693 PV_NO_DUPLICATE | PV_NO_SCRATCH))
698 while (lex_token (lexer) != T_ENDCMD )
700 lex_force_match (lexer, T_SLASH);
701 if (lex_match_id (lexer, "TIES"))
703 lex_force_match (lexer, T_EQUALS);
704 if (lex_match_id (lexer, "MEAN"))
706 rank.ties = TIES_MEAN;
708 else if (lex_match_id (lexer, "LOW"))
710 rank.ties = TIES_LOW;
712 else if (lex_match_id (lexer, "HIGH"))
714 rank.ties = TIES_HIGH;
716 else if (lex_match_id (lexer, "CONDENSE"))
718 rank.ties = TIES_CONDENSE;
722 lex_error (lexer, NULL);
726 else if (lex_match_id (lexer, "FRACTION"))
728 lex_force_match (lexer, T_EQUALS);
729 if (lex_match_id (lexer, "BLOM"))
731 rank.fraction = FRAC_BLOM;
733 else if (lex_match_id (lexer, "TUKEY"))
735 rank.fraction = FRAC_TUKEY;
737 else if (lex_match_id (lexer, "VW"))
739 rank.fraction = FRAC_VW;
741 else if (lex_match_id (lexer, "RANKIT"))
743 rank.fraction = FRAC_RANKIT;
747 lex_error (lexer, NULL);
751 else if (lex_match_id (lexer, "PRINT"))
753 lex_force_match (lexer, T_EQUALS);
754 if (lex_match_id (lexer, "YES"))
758 else if (lex_match_id (lexer, "NO"))
764 lex_error (lexer, NULL);
768 else if (lex_match_id (lexer, "MISSING"))
770 lex_force_match (lexer, T_EQUALS);
771 if (lex_match_id (lexer, "INCLUDE"))
773 rank.exclude = MV_SYSTEM;
775 else if (lex_match_id (lexer, "EXCLUDE"))
777 rank.exclude = MV_ANY;
781 lex_error (lexer, NULL);
785 else if (! parse_into (lexer, &rank))
790 /* If no rank specs are given, then apply a default */
793 rank.rs = pool_calloc (rank.pool, 1, sizeof (*rank.rs));
795 rank.rs[0].rfunc = RANK;
796 rank.rs[0].destvars = pool_calloc (rank.pool, rank.n_vars, sizeof (*rank.rs[0].destvars));
799 /* Create variables for all rank destinations which haven't
800 already been created with INTO.
801 Add labels to all the destination variables.
803 for (i = 0 ; i < rank.n_rs ; ++i )
806 struct rank_spec *rs = &rank.rs[i];
808 for ( v = 0 ; v < rank.n_vars ; v ++ )
810 if ( rs->destvars[v] == NULL )
813 create_rank_variable (rank.dict, rs->rfunc, rank.vars[v], NULL);
816 create_var_label (&rank, rs->destvars[v],
826 tab_output_text (0, _("Variables Created By RANK"));
827 tab_output_text (0, "");
829 for (i = 0 ; i < rank.n_rs ; ++i )
831 for ( v = 0 ; v < rank.n_vars ; v ++ )
833 if ( rank.n_group_vars > 0 )
835 struct string varlist;
838 ds_init_empty (&varlist);
839 for ( g = 0 ; g < rank.n_group_vars ; ++g )
841 ds_put_cstr (&varlist, var_get_name (rank.group_vars[g]));
843 if ( g < rank.n_group_vars - 1)
844 ds_put_cstr (&varlist, " ");
847 if ( rank.rs[i].rfunc == NORMAL ||
848 rank.rs[i].rfunc == PROPORTION )
849 tab_output_text_format (0,
850 _("%s into %s(%s of %s using %s BY %s)"),
851 var_get_name (rank.vars[v]),
852 var_get_name (rank.rs[i].destvars[v]),
853 function_name[rank.rs[i].rfunc],
854 var_get_name (rank.vars[v]),
855 fraction_name (&rank),
859 tab_output_text_format (0,
860 _("%s into %s(%s of %s BY %s)"),
861 var_get_name (rank.vars[v]),
862 var_get_name (rank.rs[i].destvars[v]),
863 function_name[rank.rs[i].rfunc],
864 var_get_name (rank.vars[v]),
866 ds_destroy (&varlist);
870 if ( rank.rs[i].rfunc == NORMAL ||
871 rank.rs[i].rfunc == PROPORTION )
872 tab_output_text_format (0,
873 _("%s into %s(%s of %s using %s)"),
874 var_get_name (rank.vars[v]),
875 var_get_name (rank.rs[i].destvars[v]),
876 function_name[rank.rs[i].rfunc],
877 var_get_name (rank.vars[v]),
878 fraction_name (&rank));
881 tab_output_text_format (0,
882 _("%s into %s(%s of %s)"),
883 var_get_name (rank.vars[v]),
884 var_get_name (rank.rs[i].destvars[v]),
885 function_name[rank.rs[i].rfunc],
886 var_get_name (rank.vars[v]));
892 /* Add a variable which we can sort by to get back the original
894 order = dict_create_var_assert (dataset_dict (ds), "$ORDER_", 0);
896 add_transformation (ds, create_resort_key, 0, order);
899 result = rank_cmd (ds, &rank);
901 /* Put the active dataset back in its original order. Delete
902 our sort key, which we don't need anymore. */
904 struct casereader *sorted;
907 /* FIXME: loses error conditions. */
909 proc_discard_output (ds);
910 sorted = sort_execute_1var (proc_open (ds), order);
911 result = proc_commit (ds) && result;
913 dict_delete_var (dataset_dict (ds), order);
914 result = dataset_set_source (ds, sorted) && result;
919 destroy_rank (&rank);
924 destroy_rank (&rank);
931 rank_cmd (struct dataset *ds, const struct rank *cmd)
933 struct dictionary *d = dataset_dict (ds);
937 for (i = 0 ; i < subcase_get_n_fields (&cmd->sc) ; ++i )
939 /* Rank variable at index I in SC. */
940 struct casegrouper *split_grouper;
941 struct casereader *split_group;
942 struct casewriter *output;
944 proc_discard_output (ds);
945 split_grouper = casegrouper_create_splits (proc_open (ds), d);
946 output = autopaging_writer_create (dict_get_proto (d));
948 while (casegrouper_get_next_group (split_grouper, &split_group))
950 struct subcase ordering;
951 struct casereader *ordered;
952 struct casegrouper *by_grouper;
953 struct casereader *by_group;
955 /* Sort this split group by the BY variables as primary
956 keys and the rank variable as secondary key. */
957 subcase_init_vars (&ordering, cmd->group_vars, cmd->n_group_vars);
958 subcase_add_var (&ordering, cmd->vars[i],
959 subcase_get_direction (&cmd->sc, i));
960 ordered = sort_execute (split_group, &ordering);
961 subcase_destroy (&ordering);
963 /* Rank the rank variable within this split group. */
964 by_grouper = casegrouper_create_vars (ordered,
965 cmd->group_vars, cmd->n_group_vars);
966 while (casegrouper_get_next_group (by_grouper, &by_group))
968 /* Rank the rank variable within this BY group
969 within the split group. */
971 rank_sorted_file (by_group, output, d, i, cmd);
974 ok = casegrouper_destroy (by_grouper) && ok;
976 ok = casegrouper_destroy (split_grouper);
977 ok = proc_commit (ds) && ok;
978 ok = (dataset_set_source (ds, casewriter_make_reader (output))