1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 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/>. */
20 #include <data/procedure.h>
21 #include <language/lexer/variable-parser.h>
22 #include <language/lexer/value-parser.h>
23 #include <language/lexer/lexer.h>
25 #include <data/casegrouper.h>
26 #include <data/casereader.h>
27 #include <data/casewriter.h>
28 #include <data/dictionary.h>
29 #include <data/format.h>
30 #include <math/sort.h>
31 #include <data/subcase.h>
34 #include <libpspp/misc.h>
36 #include <gsl/gsl_cdf.h>
37 #include <output/table.h>
39 #include <output/charts/plot-chart.h>
40 #include <output/charts/cartesian.h>
43 #define _(msgid) gettext (msgid)
44 #define N_(msgid) msgid
49 const struct variable **vars;
51 struct variable *state_var ;
52 union value state_value;
54 /* Plot the roc curve */
56 /* Plot the reference line */
63 bool bi_neg_exp; /* True iff the bi-negative exponential critieria
65 enum mv_class exclude;
67 bool invert ; /* True iff a smaller test result variable indicates
71 static int run_roc (struct dataset *ds, struct cmd_roc *roc);
74 cmd_roc (struct lexer *lexer, struct dataset *ds)
77 const struct dictionary *dict = dataset_dict (ds);
82 roc.print_coords = false;
85 roc.reference = false;
87 roc.bi_neg_exp = false;
90 if (!parse_variables_const (lexer, dict, &roc.vars, &roc.n_vars,
91 PV_APPEND | PV_NO_DUPLICATE | PV_NUMERIC))
94 if ( ! lex_force_match (lexer, T_BY))
99 roc.state_var = parse_variable (lexer, dict);
101 if ( !lex_force_match (lexer, '('))
106 parse_value (lexer, &roc.state_value, var_get_width (roc.state_var));
109 if ( !lex_force_match (lexer, ')'))
115 while (lex_token (lexer) != '.')
117 lex_match (lexer, '/');
118 if (lex_match_id (lexer, "MISSING"))
120 lex_match (lexer, '=');
121 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
123 if (lex_match_id (lexer, "INCLUDE"))
125 roc.exclude = MV_SYSTEM;
127 else if (lex_match_id (lexer, "EXCLUDE"))
129 roc.exclude = MV_ANY;
133 lex_error (lexer, NULL);
138 else if (lex_match_id (lexer, "PLOT"))
140 lex_match (lexer, '=');
141 if (lex_match_id (lexer, "CURVE"))
144 if (lex_match (lexer, '('))
146 roc.reference = true;
147 lex_force_match_id (lexer, "REFERENCE");
148 lex_force_match (lexer, ')');
151 else if (lex_match_id (lexer, "NONE"))
157 lex_error (lexer, NULL);
161 else if (lex_match_id (lexer, "PRINT"))
163 lex_match (lexer, '=');
164 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
166 if (lex_match_id (lexer, "SE"))
170 else if (lex_match_id (lexer, "COORDINATES"))
172 roc.print_coords = true;
176 lex_error (lexer, NULL);
181 else if (lex_match_id (lexer, "CRITERIA"))
183 lex_match (lexer, '=');
184 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
186 if (lex_match_id (lexer, "CUTOFF"))
188 lex_force_match (lexer, '(');
189 if (lex_match_id (lexer, "INCLUDE"))
191 roc.exclude = MV_SYSTEM;
193 else if (lex_match_id (lexer, "EXCLUDE"))
195 roc.exclude = MV_USER | MV_SYSTEM;
199 lex_error (lexer, NULL);
202 lex_force_match (lexer, ')');
204 else if (lex_match_id (lexer, "TESTPOS"))
206 lex_force_match (lexer, '(');
207 if (lex_match_id (lexer, "LARGE"))
211 else if (lex_match_id (lexer, "SMALL"))
217 lex_error (lexer, NULL);
220 lex_force_match (lexer, ')');
222 else if (lex_match_id (lexer, "CI"))
224 lex_force_match (lexer, '(');
225 lex_force_num (lexer);
226 roc.ci = lex_number (lexer);
228 lex_force_match (lexer, ')');
230 else if (lex_match_id (lexer, "DISTRIBUTION"))
232 lex_force_match (lexer, '(');
233 if (lex_match_id (lexer, "FREE"))
235 roc.bi_neg_exp = false;
237 else if (lex_match_id (lexer, "NEGEXPO"))
239 roc.bi_neg_exp = true;
243 lex_error (lexer, NULL);
246 lex_force_match (lexer, ')');
250 lex_error (lexer, NULL);
257 lex_error (lexer, NULL);
271 do_roc (struct cmd_roc *roc, struct casereader *group, struct dictionary *dict);
275 run_roc (struct dataset *ds, struct cmd_roc *roc)
277 struct dictionary *dict = dataset_dict (ds);
279 struct casereader *group;
281 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
282 while (casegrouper_get_next_group (grouper, &group))
284 do_roc (roc, group, dataset_dict (ds));
286 ok = casegrouper_destroy (grouper);
287 ok = proc_commit (ds) && ok;
294 dump_casereader (struct casereader *reader)
297 struct casereader *r = casereader_clone (reader);
299 for ( ; (c = casereader_read (r) ); case_unref (c))
302 for (i = 0 ; i < case_get_value_cnt (c); ++i)
304 printf ("%g ", case_data_idx (c, i)->f);
309 casereader_destroy (r);
313 match_positives (const struct ccase *c, void *aux)
315 struct cmd_roc *roc = aux;
317 return 0 == value_compare_3way (case_data (c, roc->state_var),
319 var_get_width (roc->state_var));
337 struct casewriter *cutpoint_wtr;
338 struct casereader *cutpoint_rdr;
353 static struct casereader *
354 accumulate_counts (struct casereader *cutpoint_rdr,
355 double result, double weight,
356 bool (*pos_cond) (double, double),
357 int true_index, int false_index)
359 const struct caseproto *proto = casereader_get_proto (cutpoint_rdr);
360 struct casewriter *w =
361 autopaging_writer_create (proto);
362 struct casereader *r = casereader_clone (cutpoint_rdr);
364 double prev_cp = SYSMIS;
367 for ( ; (cpc = casereader_read (r) ); case_unref (cpc))
369 struct ccase *new_case;
370 const double cp = case_data_idx (cpc, CUTPOINT)->f;
372 /* We don't want duplicates here */
376 new_case = case_clone (cpc);
378 if ( pos_cond (result, cp))
380 case_data_rw_idx (new_case, true_index)->f += weight;
384 case_data_rw_idx (new_case, false_index)->f += weight;
389 casewriter_write (w, new_case);
391 casereader_destroy (r);
393 return casewriter_make_reader (w);
398 static void output_roc (struct roc_state *rs, const struct cmd_roc *roc);
401 static struct casereader *
402 process_group (const struct variable *var, struct casereader *reader,
403 bool (*pred) (double, double),
404 const struct dictionary *dict,
406 struct casereader **cutpoint_rdr,
407 bool (*pos_cond) (double, double),
412 const struct variable *w = dict_get_weight (dict);
413 struct casereader *r1 =
414 casereader_create_distinct (sort_execute_1var (reader, var), var, w);
416 const int weight_idx = w ? var_get_case_index (w) :
417 caseproto_get_n_widths (casereader_get_proto (r1)) - 1;
421 struct casereader *rclone = casereader_clone (r1);
422 struct casewriter *wtr;
423 struct caseproto *proto = caseproto_create ();
425 proto = caseproto_add_width (proto, 0);
426 proto = caseproto_add_width (proto, 0);
427 proto = caseproto_add_width (proto, 0);
429 wtr = autopaging_writer_create (proto);
433 for ( ; (c1 = casereader_read (r1) ); case_unref (c1))
436 struct casereader *r2 = casereader_clone (rclone);
438 const double weight1 = case_data_idx (c1, weight_idx)->f;
439 const double d1 = case_data (c1, var)->f;
443 *cutpoint_rdr = accumulate_counts (*cutpoint_rdr, d1, weight1,
445 true_index, false_index);
447 struct ccase *new_case = case_create (proto);
451 for ( ; (c2 = casereader_read (r2) ); case_unref (c2))
453 const double d2 = case_data (c2, var)->f;
454 const double weight2 = case_data_idx (c2, weight_idx)->f;
461 else if ( pred (d2, d1))
467 case_data_rw_idx (new_case, VALUE)->f = d1;
468 case_data_rw_idx (new_case, N_EQ)->f = n_eq;
469 case_data_rw_idx (new_case, N_PRED)->f = n_pred;
471 casewriter_write (wtr, new_case);
473 casereader_destroy (r2);
476 casereader_destroy (r1);
477 casereader_destroy (rclone);
479 return casewriter_make_reader (wtr);
483 gt (double d1, double d2)
490 ge (double d1, double d2)
496 lt (double d1, double d2)
501 static struct casereader *
502 process_positive_group (const struct variable *var, struct casereader *reader,
503 const struct dictionary *dict,
504 struct roc_state *rs)
506 return process_group (var, reader, gt, dict, &rs->n1,
513 static struct casereader *
514 process_negative_group (const struct variable *var, struct casereader *reader,
515 const struct dictionary *dict,
516 struct roc_state *rs)
518 return process_group (var, reader, lt, dict, &rs->n2,
528 append_cutpoint (struct casewriter *writer, double cutpoint)
530 struct ccase *cc = case_create (casewriter_get_proto (writer));
532 case_data_rw_idx (cc, CUTPOINT)->f = cutpoint;
533 case_data_rw_idx (cc, TP)->f = 0;
534 case_data_rw_idx (cc, FN)->f = 0;
535 case_data_rw_idx (cc, TN)->f = 0;
536 case_data_rw_idx (cc, FP)->f = 0;
539 casewriter_write (writer, cc);
544 do_roc (struct cmd_roc *roc, struct casereader *input, struct dictionary *dict)
548 struct roc_state *rs = xcalloc (roc->n_vars, sizeof *rs);
550 struct casewriter *neg_wtr = autopaging_writer_create (casereader_get_proto (input));
552 struct casereader *negatives = NULL;
553 struct casereader *positives = NULL;
556 /* Prepare the cutpoints */
558 struct casereader *r = casereader_clone (input);
560 struct caseproto *proto = caseproto_create ();
562 struct subcase ordering;
563 subcase_init (&ordering, CUTPOINT, 0, SC_ASCEND);
566 proto = caseproto_add_width (proto, 0); /* cutpoint */
567 proto = caseproto_add_width (proto, 0); /* TP */
568 proto = caseproto_add_width (proto, 0); /* FN */
569 proto = caseproto_add_width (proto, 0); /* TN */
570 proto = caseproto_add_width (proto, 0); /* FP */
573 for (i = 0 ; i < roc->n_vars; ++i)
575 rs[i].cutpoint_wtr = sort_create_writer (&ordering, proto);
576 rs[i].prev_result = SYSMIS;
577 rs[i].max = -DBL_MAX;
581 for (; (c = casereader_read (r)) != NULL; case_unref (c))
583 const double weight = dict_get_case_weight (dict, c, NULL);
584 for (i = 0 ; i < roc->n_vars; ++i)
586 const double result = case_data (c, roc->vars[i])->f;
588 minimize (&rs[i].min, result);
589 maximize (&rs[i].max, result);
591 if ( rs[i].prev_result != SYSMIS && rs[i].prev_result != result )
593 const double mean = (result + rs[i].prev_result ) / 2.0;
594 append_cutpoint (rs[i].cutpoint_wtr, mean);
597 rs[i].prev_result = result;
600 casereader_destroy (r);
603 /* Append the min and max cutpoints */
604 for (i = 0 ; i < roc->n_vars; ++i)
606 append_cutpoint (rs[i].cutpoint_wtr, rs[i].min - 1);
607 append_cutpoint (rs[i].cutpoint_wtr, rs[i].max + 1);
609 rs[i].cutpoint_rdr = casewriter_make_reader (rs[i].cutpoint_wtr);
614 casereader_create_filter_func (input,
621 for (i = 0 ; i < roc->n_vars; ++i)
624 struct casereader *n_neg ;
625 const struct variable *var = roc->vars[i];
627 struct casereader *neg ;
628 struct casereader *pos = casereader_clone (positives);
630 struct casereader *n_pos =
631 process_positive_group (var, pos, dict, &rs[i]);
633 if ( negatives == NULL)
635 negatives = casewriter_make_reader (neg_wtr);
638 neg = casereader_clone (negatives);
640 n_neg = process_negative_group (var, neg, dict, &rs[i]);
643 printf ("Positives:\n");
644 dump_casereader (n_pos);
646 printf ("Negatives:\n");
647 dump_casereader (n_neg);
650 /* Simple join on VALUE */
651 for ( ; (cpos = casereader_read (n_pos) ); case_unref (cpos))
653 struct ccase *cneg = NULL;
654 double dneg = -DBL_MAX;
655 const double dpos = case_data_idx (cpos, VALUE)->f;
661 cneg = casereader_read (n_neg);
664 dneg = case_data_idx (cneg, VALUE)->f;
669 double n_pos_eq = case_data_idx (cpos, N_EQ)->f;
670 double n_neg_eq = case_data_idx (cneg, N_EQ)->f;
671 double n_pos_gt = case_data_idx (cpos, N_PRED)->f;
672 double n_neg_lt = case_data_idx (cneg, N_PRED)->f;
674 rs[i].auc += n_pos_gt * n_neg_eq + (n_pos_eq * n_neg_eq) / 2.0;
676 n_neg_eq * ( pow2 (n_pos_gt) + n_pos_gt * n_pos_eq + pow2 (n_pos_eq) / 3.0);
678 n_pos_eq * ( pow2 (n_neg_lt) + n_neg_lt * n_neg_eq + pow2 (n_neg_eq) / 3.0);
685 rs[i].auc /= rs[i].n1 * rs[i].n2;
687 rs[i].auc = 1 - rs[i].auc;
689 if ( roc->bi_neg_exp )
691 rs[i].q1hat = rs[i].auc / ( 2 - rs[i].auc);
692 rs[i].q2hat = 2 * pow2 (rs[i].auc) / ( 1 + rs[i].auc);
696 rs[i].q1hat /= rs[i].n2 * pow2 (rs[i].n1);
697 rs[i].q2hat /= rs[i].n1 * pow2 (rs[i].n2);
702 casereader_destroy (positives);
703 casereader_destroy (negatives);
705 output_roc (rs, roc);
714 show_auc (struct roc_state *rs, const struct cmd_roc *roc)
717 const int n_fields = roc->print_se ? 5 : 1;
718 const int n_cols = roc->n_vars > 1 ? n_fields + 1: n_fields;
719 const int n_rows = 2 + roc->n_vars;
720 struct tab_table *tbl = tab_create (n_cols, n_rows, 0);
722 if ( roc->n_vars > 1)
723 tab_title (tbl, _("Area Under the Curve"));
725 tab_title (tbl, _("Area Under the Curve (%s)"), var_to_string (roc->vars[0]));
727 tab_headers (tbl, n_cols - n_fields, 0, 1, 0);
729 tab_dim (tbl, tab_natural_dimensions, NULL);
731 tab_text (tbl, n_cols - n_fields, 1, TAT_TITLE, _("Area"));
733 tab_hline (tbl, TAL_2, 0, n_cols - 1, 2);
744 tab_text (tbl, n_cols - 4, 1, TAT_TITLE, _("Std. Error"));
745 tab_text (tbl, n_cols - 3, 1, TAT_TITLE, _("Asymptotic Sig."));
747 tab_text (tbl, n_cols - 2, 1, TAT_TITLE, _("Lower Bound"));
748 tab_text (tbl, n_cols - 1, 1, TAT_TITLE, _("Upper Bound"));
750 tab_joint_text (tbl, n_cols - 2, 0, 4, 0,
751 TAT_TITLE | TAB_CENTER | TAT_PRINTF,
752 _("Asymp. %g%% Confidence Interval"), roc->ci);
753 tab_vline (tbl, 0, n_cols - 1, 0, 0);
754 tab_hline (tbl, TAL_1, n_cols - 2, n_cols - 1, 1);
757 if ( roc->n_vars > 1)
758 tab_text (tbl, 0, 1, TAT_TITLE, _("Variable under test"));
760 if ( roc->n_vars > 1)
761 tab_vline (tbl, TAL_2, 1, 0, n_rows - 1);
764 for ( i = 0 ; i < roc->n_vars ; ++i )
766 tab_text (tbl, 0, 2 + i, TAT_TITLE, var_to_string (roc->vars[i]));
768 tab_double (tbl, n_cols - n_fields, 2 + i, 0, rs[i].auc, NULL);
773 const double sd_0_5 = sqrt ((rs[i].n1 + rs[i].n2 + 1) /
774 (12 * rs[i].n1 * rs[i].n2));
778 se = rs[i].auc * (1 - rs[i].auc) + (rs[i].n1 - 1) * (rs[i].q1hat - pow2 (rs[i].auc)) +
779 (rs[i].n2 - 1) * (rs[i].q2hat - pow2 (rs[i].auc));
781 se /= rs[i].n1 * rs[i].n2;
785 tab_double (tbl, n_cols - 4, 2 + i, 0,
789 ci = 1 - roc->ci / 100.0;
790 yy = gsl_cdf_gaussian_Qinv (ci, se) ;
792 tab_double (tbl, n_cols - 2, 2 + i, 0,
796 tab_double (tbl, n_cols - 1, 2 + i, 0,
800 tab_double (tbl, n_cols - 3, 2 + i, 0,
801 2.0 * gsl_cdf_ugaussian_Q (fabs ((rs[i].auc - 0.5 ) / sd_0_5)),
811 show_summary (const struct cmd_roc *roc)
813 const int n_cols = 3;
814 const int n_rows = 4;
815 struct tab_table *tbl = tab_create (n_cols, n_rows, 0);
817 tab_title (tbl, _("Case Summary"));
819 tab_headers (tbl, 1, 0, 2, 0);
821 tab_dim (tbl, tab_natural_dimensions, NULL);
830 tab_hline (tbl, TAL_2, 0, n_cols - 1, 2);
831 tab_vline (tbl, TAL_2, 1, 0, n_rows - 1);
834 tab_hline (tbl, TAL_2, 1, n_cols - 1, 1);
835 tab_vline (tbl, TAL_1, 2, 1, n_rows - 1);
838 tab_text (tbl, 0, 1, TAT_TITLE | TAB_LEFT, var_to_string (roc->state_var));
839 tab_text (tbl, 1, 1, TAT_TITLE, _("Unweighted"));
840 tab_text (tbl, 2, 1, TAT_TITLE, _("Weighted"));
842 tab_joint_text (tbl, 1, 0, 2, 0,
843 TAT_TITLE | TAB_CENTER,
844 _("Valid N (listwise)"));
847 tab_text (tbl, 0, 2, TAB_LEFT, _("Positive"));
848 tab_text (tbl, 0, 3, TAB_LEFT, _("Negative"));
852 tab_double (tbl, 1, 2, 0, roc->pos, &F_8_0);
853 tab_double (tbl, 1, 3, 0, roc->neg, &F_8_0);
855 tab_double (tbl, 2, 2, 0, roc->pos_weighted, 0);
856 tab_double (tbl, 2, 3, 0, roc->neg_weighted, 0);
864 show_coords (struct roc_state *rs, const struct cmd_roc *roc)
868 const int n_cols = roc->n_vars > 1 ? 4 : 3;
870 struct tab_table *tbl ;
872 for (i = 0; i < roc->n_vars; ++i)
873 n_rows += casereader_count_cases (rs[i].cutpoint_rdr);
875 tbl = tab_create (n_cols, n_rows, 0);
877 if ( roc->n_vars > 1)
878 tab_title (tbl, _("Coordinates of the Curve"));
880 tab_title (tbl, _("Coordinates of the Curve (%s)"), var_to_string (roc->vars[0]));
883 tab_headers (tbl, 1, 0, 1, 0);
885 tab_dim (tbl, tab_natural_dimensions, NULL);
887 tab_hline (tbl, TAL_2, 0, n_cols - 1, 1);
889 if ( roc->n_vars > 1)
890 tab_text (tbl, 0, 0, TAT_TITLE, _("Test variable"));
892 tab_text (tbl, n_cols - 3, 0, TAT_TITLE, _("Positive if greater than or equal to"));
893 tab_text (tbl, n_cols - 2, 0, TAT_TITLE, _("Sensitivity"));
894 tab_text (tbl, n_cols - 1, 0, TAT_TITLE, _("1 - Specificity"));
903 if ( roc->n_vars > 1)
904 tab_vline (tbl, TAL_2, 1, 0, n_rows - 1);
906 for (i = 0; i < roc->n_vars; ++i)
909 struct casereader *r = casereader_clone (rs[i].cutpoint_rdr);
911 if ( roc->n_vars > 1)
912 tab_text (tbl, 0, x, TAT_TITLE, var_to_string (roc->vars[i]));
915 tab_hline (tbl, TAL_1, 0, n_cols - 1, x);
918 for (; (cc = casereader_read (r)) != NULL;
919 case_unref (cc), x++)
921 const double se = case_data_idx (cc, TP)->f /
923 case_data_idx (cc, TP)->f
925 case_data_idx (cc, FN)->f
928 const double sp = case_data_idx (cc, TN)->f /
930 case_data_idx (cc, TN)->f
932 case_data_idx (cc, FP)->f
935 tab_double (tbl, n_cols - 3, x, 0, case_data_idx (cc, CUTPOINT)->f,
936 var_get_print_format (roc->vars[i]));
938 tab_double (tbl, n_cols - 2, x, 0, se, NULL);
939 tab_double (tbl, n_cols - 1, x, 0, 1 - sp, NULL);
942 casereader_destroy (r);
950 draw_roc (struct roc_state *rs, const struct cmd_roc *roc)
954 struct chart *roc_chart = chart_create ();
956 chart_write_title (roc_chart, _("ROC Curve"));
957 chart_write_xlabel (roc_chart, _("1 - Specificity"));
958 chart_write_ylabel (roc_chart, _("Sensitivity"));
960 chart_write_xscale (roc_chart, 0, 1, 5);
961 chart_write_yscale (roc_chart, 0, 1, 5);
963 if ( roc->reference )
965 chart_line (roc_chart, 1.0, 0,
970 for (i = 0; i < roc->n_vars; ++i)
973 struct casereader *r = casereader_clone (rs[i].cutpoint_rdr);
975 chart_vector_start (roc_chart, var_get_name (roc->vars[i]));
976 for (; (cc = casereader_read (r)) != NULL;
979 double se = case_data_idx (cc, TP)->f;
980 double sp = case_data_idx (cc, TN)->f;
982 se /= case_data_idx (cc, FN)->f +
983 case_data_idx (cc, TP)->f ;
985 sp /= case_data_idx (cc, TN)->f +
986 case_data_idx (cc, FP)->f ;
988 chart_vector (roc_chart, 1 - sp, se);
990 chart_vector_end (roc_chart);
991 casereader_destroy (r);
994 chart_write_legend (roc_chart);
996 chart_submit (roc_chart);
1001 output_roc (struct roc_state *rs, const struct cmd_roc *roc)
1011 if ( roc->print_coords )
1012 show_coords (rs, roc);