1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2011, 2012, 2015 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 <gsl/gsl_matrix.h>
20 #include <gsl/gsl_permutation.h>
21 #include <gsl/gsl_sort_vector.h>
22 #include <gsl/gsl_statistics.h>
26 #include "data/case.h"
27 #include "data/casegrouper.h"
28 #include "data/casereader.h"
29 #include "data/casewriter.h"
30 #include "data/dataset.h"
31 #include "data/dictionary.h"
32 #include "data/format.h"
33 #include "data/missing-values.h"
34 #include "language/command.h"
35 #include "language/lexer/lexer.h"
36 #include "language/lexer/variable-parser.h"
37 #include "libpspp/message.h"
38 #include "libpspp/misc.h"
39 #include "libpspp/assertion.h"
40 #include "libpspp/str.h"
41 #include "math/random.h"
42 #include "output/tab.h"
43 #include "output/text-item.h"
46 #define _(msgid) gettext (msgid)
47 #define N_(msgid) msgid
58 const struct variable **vars;
61 double epsilon; /* The convergence criterium */
63 int ngroups; /* Number of group. (Given by the user) */
64 int maxiter; /* Maximum iterations (Given by the user) */
65 bool print_cluster_membership; /* true => print membership */
66 bool print_initial_clusters; /* true => print initial cluster */
67 bool no_initial; /* true => simplified initial cluster selection */
68 bool no_update; /* true => do not iterate */
70 const struct variable *wv; /* Weighting variable. */
72 enum missing_type missing_type;
73 enum mv_class exclude;
76 /* Holds all of the information for the functions. int n, holds the number of
77 observation and its default value is -1. We set it in
78 kmeans_recalculate_centers in first invocation. */
81 gsl_matrix *centers; /* Centers for groups. */
82 gsl_matrix *updated_centers;
85 gsl_vector_long *num_elements_groups;
87 gsl_matrix *initial_centers; /* Initial random centers. */
88 double convergence_criteria;
89 gsl_permutation *group_order; /* Group order for reporting. */
92 static struct Kmeans *kmeans_create (const struct qc *qc);
94 static void kmeans_get_nearest_group (const struct Kmeans *kmeans, struct ccase *c, const struct qc *, int *, double *, int *, double *);
96 static void kmeans_order_groups (struct Kmeans *kmeans, const struct qc *);
98 static void kmeans_cluster (struct Kmeans *kmeans, struct casereader *reader, const struct qc *);
100 static void quick_cluster_show_centers (struct Kmeans *kmeans, bool initial, const struct qc *);
102 static void quick_cluster_show_membership (struct Kmeans *kmeans, const struct casereader *reader, const struct qc *);
104 static void quick_cluster_show_number_cases (struct Kmeans *kmeans, const struct qc *);
106 static void quick_cluster_show_results (struct Kmeans *kmeans, const struct casereader *reader, const struct qc *);
108 int cmd_quick_cluster (struct lexer *lexer, struct dataset *ds);
110 static void kmeans_destroy (struct Kmeans *kmeans);
112 /* Creates and returns a struct of Kmeans with given casereader 'cs', parsed
113 variables 'variables', number of cases 'n', number of variables 'm', number
114 of clusters and amount of maximum iterations. */
115 static struct Kmeans *
116 kmeans_create (const struct qc *qc)
118 struct Kmeans *kmeans = xmalloc (sizeof (struct Kmeans));
119 kmeans->centers = gsl_matrix_alloc (qc->ngroups, qc->n_vars);
120 kmeans->updated_centers = gsl_matrix_alloc (qc->ngroups, qc->n_vars);
121 kmeans->num_elements_groups = gsl_vector_long_alloc (qc->ngroups);
122 kmeans->group_order = gsl_permutation_alloc (kmeans->centers->size1);
123 kmeans->initial_centers = NULL;
129 kmeans_destroy (struct Kmeans *kmeans)
131 gsl_matrix_free (kmeans->centers);
132 gsl_matrix_free (kmeans->updated_centers);
133 gsl_matrix_free (kmeans->initial_centers);
135 gsl_vector_long_free (kmeans->num_elements_groups);
137 gsl_permutation_free (kmeans->group_order);
143 diff_matrix (const gsl_matrix *m1, const gsl_matrix *m2)
146 double max_diff = -INFINITY;
147 for (i = 0; i < m1->size1; ++i)
150 for (j = 0; j < m1->size2; ++j)
152 diff += pow2 (gsl_matrix_get (m1,i,j) - gsl_matrix_get (m2,i,j) );
164 matrix_mindist (const gsl_matrix *m, int *mn, int *mm)
167 double mindist = INFINITY;
168 for (i = 0; i < m->size1 - 1; ++i)
170 for (j = i + 1; j < m->size1; ++j)
174 for (k = 0; k < m->size2; ++k)
176 diff_sq += pow2 (gsl_matrix_get (m, j, k) - gsl_matrix_get (m, i, k));
178 if (diff_sq < mindist)
193 /* Return the distance of C from the group whose index is WHICH */
195 dist_from_case (const struct Kmeans *kmeans, const struct ccase *c, const struct qc *qc, int which)
199 for (j = 0; j < qc->n_vars; j++)
201 const union value *val = case_data (c, qc->vars[j]);
202 if ( var_is_value_missing (qc->vars[j], val, qc->exclude))
205 dist += pow2 (gsl_matrix_get (kmeans->centers, which, j) - val->f);
211 /* Return the minimum distance of the group WHICH and all other groups */
213 min_dist_from (const struct Kmeans *kmeans, const struct qc *qc, int which)
217 double mindist = INFINITY;
218 for (i = 0; i < qc->ngroups; i++)
224 for (j = 0; j < qc->n_vars; j++)
226 dist += pow2 (gsl_matrix_get (kmeans->centers, i, j) - gsl_matrix_get (kmeans->centers, which, j));
240 /* Calculate the intial cluster centers. */
242 kmeans_initial_centers (struct Kmeans *kmeans, const struct casereader *reader, const struct qc *qc)
247 struct casereader *cs = casereader_clone (reader);
248 for (; (c = casereader_read (cs)) != NULL; case_unref (c))
250 bool missing = false;
251 for (j = 0; j < qc->n_vars; ++j)
253 const union value *val = case_data (c, qc->vars[j]);
254 if ( var_is_value_missing (qc->vars[j], val, qc->exclude))
260 if (nc < qc->ngroups)
261 gsl_matrix_set (kmeans->centers, nc, j, val->f);
267 if (nc++ < qc->ngroups)
276 double m = matrix_mindist (kmeans->centers, &mn, &mm);
278 kmeans_get_nearest_group (kmeans, c, qc, &mq, &delta, &mp, NULL);
280 /* If the distance between C and the nearest group, is greater than the distance
281 between the two groups which are clostest to each other, then one group must be replaced */
283 /* Out of mn and mm, which is the clostest of the two groups to C ? */
284 int which = (dist_from_case (kmeans, c, qc, mn) > dist_from_case (kmeans, c, qc, mm)) ? mm : mn;
286 for (j = 0; j < qc->n_vars; ++j)
288 const union value *val = case_data (c, qc->vars[j]);
289 gsl_matrix_set (kmeans->centers, which, j, val->f);
292 else if (dist_from_case (kmeans, c, qc, mp) > min_dist_from (kmeans, qc, mq))
293 /* If the distance between C and the second nearest group (MP) is greater than the
294 smallest distance between the nearest group (MQ) and any other group, then replace
297 for (j = 0; j < qc->n_vars; ++j)
299 const union value *val = case_data (c, qc->vars[j]);
300 gsl_matrix_set (kmeans->centers, mq, j, val->f);
306 casereader_destroy (cs);
308 kmeans->convergence_criteria = qc->epsilon * matrix_mindist (kmeans->centers, NULL, NULL);
310 /* As it is the first iteration, the variable kmeans->initial_centers is NULL
311 and it is created once for reporting issues. */
312 kmeans->initial_centers = gsl_matrix_alloc (qc->ngroups, qc->n_vars);
313 gsl_matrix_memcpy (kmeans->initial_centers, kmeans->centers);
317 /* Return the index of the group which is nearest to the case C */
319 kmeans_get_nearest_group (const struct Kmeans *kmeans, struct ccase *c, const struct qc *qc, int *g_q, double *delta_q, int *g_p, double *delta_p)
324 double mindist0 = INFINITY;
325 double mindist1 = INFINITY;
326 for (i = 0; i < qc->ngroups; i++)
329 for (j = 0; j < qc->n_vars; j++)
331 const union value *val = case_data (c, qc->vars[j]);
332 if ( var_is_value_missing (qc->vars[j], val, qc->exclude))
335 dist += pow2 (gsl_matrix_get (kmeans->centers, i, j) - val->f);
346 else if (dist < mindist1)
370 kmeans_order_groups (struct Kmeans *kmeans, const struct qc *qc)
372 gsl_vector *v = gsl_vector_alloc (qc->ngroups);
373 gsl_matrix_get_col (v, kmeans->centers, 0);
374 gsl_sort_vector_index (kmeans->group_order, v);
379 Does iterations, checks convergency. */
381 kmeans_cluster (struct Kmeans *kmeans, struct casereader *reader, const struct qc *qc)
385 kmeans_initial_centers (kmeans, reader, qc);
387 gsl_matrix_memcpy (kmeans->updated_centers, kmeans->centers);
390 for (int xx = 0 ; xx < qc->maxiter ; ++xx)
392 gsl_vector_long_set_all (kmeans->num_elements_groups, 0.0);
397 struct casereader *r = casereader_clone (reader);
399 for (; (c = casereader_read (r)) != NULL; case_unref (c))
403 bool missing = false;
405 for (j = 0; j < qc->n_vars; j++)
407 const union value *val = case_data (c, qc->vars[j]);
408 if ( var_is_value_missing (qc->vars[j], val, qc->exclude))
415 double mindist = INFINITY;
416 for (g = 0; g < qc->ngroups; ++g)
418 double d = dist_from_case (kmeans, c, qc, g);
427 long *n = gsl_vector_long_ptr (kmeans->num_elements_groups, group);
428 *n += qc->wv ? case_data (c, qc->wv)->f : 1.0;
431 for (j = 0; j < qc->n_vars; ++j)
433 const union value *val = case_data (c, qc->vars[j]);
434 if ( var_is_value_missing (qc->vars[j], val, qc->exclude))
436 double *x = gsl_matrix_ptr (kmeans->updated_centers, group, j);
437 *x += val->f * (qc->wv ? case_data (c, qc->wv)->f : 1.0);
441 casereader_destroy (r);
446 /* Divide the cluster sums by the number of items in each cluster */
447 for (g = 0; g < qc->ngroups; ++g)
449 for (j = 0; j < qc->n_vars; ++j)
451 long n = gsl_vector_long_get (kmeans->num_elements_groups, g);
452 double *x = gsl_matrix_ptr (kmeans->updated_centers, g, j);
453 *x /= n + 1; // Plus 1 for the initial centers
458 gsl_matrix_memcpy (kmeans->centers, kmeans->updated_centers);
463 gsl_vector_long_set_all (kmeans->num_elements_groups, 0.0);
464 gsl_matrix_set_all (kmeans->updated_centers, 0.0);
466 struct casereader *cs = casereader_clone (reader);
467 for (; (c = casereader_read (cs)) != NULL; case_unref (c))
470 kmeans_get_nearest_group (kmeans, c, qc, &group, NULL, NULL, NULL);
472 for (j = 0; j < qc->n_vars; ++j)
474 const union value *val = case_data (c, qc->vars[j]);
475 if ( var_is_value_missing (qc->vars[j], val, qc->exclude))
478 double *x = gsl_matrix_ptr (kmeans->updated_centers, group, j);
482 long *n = gsl_vector_long_ptr (kmeans->num_elements_groups, group);
483 *n += qc->wv ? case_data (c, qc->wv)->f : 1.0;
486 casereader_destroy (cs);
489 /* Divide the cluster sums by the number of items in each cluster */
490 for (g = 0; g < qc->ngroups; ++g)
492 for (j = 0; j < qc->n_vars; ++j)
494 long n = gsl_vector_long_get (kmeans->num_elements_groups, g);
495 double *x = gsl_matrix_ptr (kmeans->updated_centers, g, j);
500 double d = diff_matrix (kmeans->updated_centers, kmeans->centers);
501 if (d < kmeans->convergence_criteria)
510 /* Reports centers of clusters.
511 Initial parameter is optional for future use.
512 If initial is true, initial cluster centers are reported. Otherwise,
513 resulted centers are reported. */
515 quick_cluster_show_centers (struct Kmeans *kmeans, bool initial, const struct qc *qc)
520 nc = qc->ngroups + 1;
522 t = tab_create (nc, nr);
523 tab_headers (t, 0, nc - 1, 0, 1);
527 tab_title (t, _("Final Cluster Centers"));
531 tab_title (t, _("Initial Cluster Centers"));
533 tab_box (t, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, nc - 1, nr - 1);
534 tab_joint_text (t, 1, 0, nc - 1, 0, TAB_CENTER, _("Cluster"));
535 tab_hline (t, TAL_1, 1, nc - 1, 2);
538 for (i = 0; i < qc->ngroups; i++)
540 tab_text_format (t, (i + 1), currow, TAB_CENTER, "%d", (i + 1));
543 tab_hline (t, TAL_1, 1, nc - 1, currow);
545 for (i = 0; i < qc->n_vars; i++)
547 tab_text (t, 0, currow + i, TAB_LEFT,
548 var_to_string (qc->vars[i]));
551 for (i = 0; i < qc->ngroups; i++)
553 for (j = 0; j < qc->n_vars; j++)
557 tab_double (t, i + 1, j + 4, TAB_CENTER,
558 gsl_matrix_get (kmeans->centers,
559 kmeans->group_order->data[i], j),
560 var_get_print_format (qc->vars[j]), RC_OTHER);
564 tab_double (t, i + 1, j + 4, TAB_CENTER,
565 gsl_matrix_get (kmeans->initial_centers,
566 kmeans->group_order->data[i], j),
567 var_get_print_format (qc->vars[j]), RC_OTHER);
574 /* Reports cluster membership for each case. */
576 quick_cluster_show_membership (struct Kmeans *kmeans, const struct casereader *reader, const struct qc *qc)
582 struct casereader *cs = casereader_clone (reader);
585 t = tab_create (nc, nr);
586 tab_headers (t, 0, nc - 1, 0, 0);
587 tab_title (t, _("Cluster Membership"));
588 tab_text (t, 0, 0, TAB_CENTER, _("Case Number"));
589 tab_text (t, 1, 0, TAB_CENTER, _("Cluster"));
590 tab_box (t, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, nc - 1, nr - 1);
591 tab_hline (t, TAL_1, 0, nc - 1, 1);
593 gsl_permutation *ip = gsl_permutation_alloc (qc->ngroups);
594 gsl_permutation_inverse (ip, kmeans->group_order);
596 for (i = 0; (c = casereader_read (cs)) != NULL; i++, case_unref (c))
599 assert (i < kmeans->n);
600 kmeans_get_nearest_group (kmeans, c, qc, &clust, NULL, NULL, NULL);
601 clust = ip->data[clust];
602 tab_text_format (t, 0, i+1, TAB_CENTER, "%d", (i + 1));
603 tab_text_format (t, 1, i+1, TAB_CENTER, "%d", (clust + 1));
605 gsl_permutation_free (ip);
606 assert (i == kmeans->n);
608 casereader_destroy (cs);
612 /* Reports number of cases of each single cluster. */
614 quick_cluster_show_number_cases (struct Kmeans *kmeans, const struct qc *qc)
621 nr = qc->ngroups + 1;
622 t = tab_create (nc, nr);
623 tab_headers (t, 0, nc - 1, 0, 0);
624 tab_title (t, _("Number of Cases in each Cluster"));
625 tab_box (t, TAL_2, TAL_2, TAL_0, TAL_1, 0, 0, nc - 1, nr - 1);
626 tab_text (t, 0, 0, TAB_LEFT, _("Cluster"));
629 for (i = 0; i < qc->ngroups; i++)
631 tab_text_format (t, 1, i, TAB_CENTER, "%d", (i + 1));
633 kmeans->num_elements_groups->data[kmeans->group_order->data[i]];
634 tab_text_format (t, 2, i, TAB_CENTER, "%d", numelem);
638 tab_text (t, 0, qc->ngroups, TAB_LEFT, _("Valid"));
639 tab_text_format (t, 2, qc->ngroups, TAB_LEFT, "%ld", total);
645 quick_cluster_show_results (struct Kmeans *kmeans, const struct casereader *reader, const struct qc *qc)
647 kmeans_order_groups (kmeans, qc); /* what does this do? */
649 if( qc->print_initial_clusters )
650 quick_cluster_show_centers (kmeans, true, qc);
651 quick_cluster_show_centers (kmeans, false, qc);
652 quick_cluster_show_number_cases (kmeans, qc);
653 if( qc->print_cluster_membership )
654 quick_cluster_show_membership(kmeans, reader, qc);
658 cmd_quick_cluster (struct lexer *lexer, struct dataset *ds)
661 struct Kmeans *kmeans;
663 const struct dictionary *dict = dataset_dict (ds);
666 qc.epsilon = DBL_EPSILON;
667 qc.missing_type = MISS_LISTWISE;
669 qc.print_cluster_membership = false; /* default = do not output case cluster membership */
670 qc.print_initial_clusters = false; /* default = do not print initial clusters */
671 qc.no_initial = false; /* default = use well separated initial clusters */
672 qc.no_update = false; /* default = iterate until convergence or max iterations */
674 if (!parse_variables_const (lexer, dict, &qc.vars, &qc.n_vars,
675 PV_NO_DUPLICATE | PV_NUMERIC))
677 return (CMD_FAILURE);
680 while (lex_token (lexer) != T_ENDCMD)
682 lex_match (lexer, T_SLASH);
684 if (lex_match_id (lexer, "MISSING"))
686 lex_match (lexer, T_EQUALS);
687 while (lex_token (lexer) != T_ENDCMD
688 && lex_token (lexer) != T_SLASH)
690 if (lex_match_id (lexer, "LISTWISE") || lex_match_id (lexer, "DEFAULT"))
692 qc.missing_type = MISS_LISTWISE;
694 else if (lex_match_id (lexer, "PAIRWISE"))
696 qc.missing_type = MISS_PAIRWISE;
698 else if (lex_match_id (lexer, "INCLUDE"))
700 qc.exclude = MV_SYSTEM;
702 else if (lex_match_id (lexer, "EXCLUDE"))
708 lex_error (lexer, NULL);
713 else if (lex_match_id (lexer, "PRINT"))
715 lex_match (lexer, T_EQUALS);
716 while (lex_token (lexer) != T_ENDCMD
717 && lex_token (lexer) != T_SLASH)
719 if (lex_match_id (lexer, "CLUSTER"))
720 qc.print_cluster_membership = true;
721 else if (lex_match_id (lexer, "INITIAL"))
722 qc.print_initial_clusters = true;
725 lex_error (lexer, NULL);
730 else if (lex_match_id (lexer, "CRITERIA"))
732 lex_match (lexer, T_EQUALS);
733 while (lex_token (lexer) != T_ENDCMD
734 && lex_token (lexer) != T_SLASH)
736 if (lex_match_id (lexer, "CLUSTERS"))
738 if (lex_force_match (lexer, T_LPAREN) &&
739 lex_force_int (lexer))
741 qc.ngroups = lex_integer (lexer);
744 lex_error (lexer, _("The number of clusters must be positive"));
748 if (!lex_force_match (lexer, T_RPAREN))
752 else if (lex_match_id (lexer, "CONVERGE"))
754 if (lex_force_match (lexer, T_LPAREN) &&
755 lex_force_num (lexer))
757 qc.epsilon = lex_number (lexer);
760 lex_error (lexer, _("The convergence criterium must be positive"));
764 if (!lex_force_match (lexer, T_RPAREN))
768 else if (lex_match_id (lexer, "MXITER"))
770 if (lex_force_match (lexer, T_LPAREN) &&
771 lex_force_int (lexer))
773 qc.maxiter = lex_integer (lexer);
776 lex_error (lexer, _("The number of iterations must be positive"));
780 if (!lex_force_match (lexer, T_RPAREN))
784 else if (lex_match_id (lexer, "NOINITIAL"))
786 qc.no_initial = true;
788 else if (lex_match_id (lexer, "NOUPDATE"))
794 lex_error (lexer, NULL);
801 lex_error (lexer, NULL);
806 qc.wv = dict_get_weight (dict);
809 struct casereader *group;
810 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
812 while (casegrouper_get_next_group (grouper, &group))
814 if ( qc.missing_type == MISS_LISTWISE )
816 group = casereader_create_filter_missing (group, qc.vars, qc.n_vars,
821 kmeans = kmeans_create (&qc);
822 kmeans_cluster (kmeans, group, &qc);
823 quick_cluster_show_results (kmeans, group, &qc);
824 kmeans_destroy (kmeans);
825 casereader_destroy (group);
827 ok = casegrouper_destroy (grouper);
829 ok = proc_commit (ds) && ok;