Module: Flock

Defined in:
lib/flock.rb,
ext/flock.c

Constant Summary collapse

METHOD_AVERAGE =
INT2NUM('a')
METHOD_MEDIAN =
INT2NUM('m')
METRIC_EUCLIDIAN =
INT2NUM('e')
METRIC_CITY_BLOCK =
INT2NUM('b')
METRIC_CORRELATION =
INT2NUM('c')
METRIC_ABSOLUTE_CORRELATION =
INT2NUM('a')
METRIC_UNCENTERED_CORRELATION =
INT2NUM('u')
METRIC_ABSOLUTE_UNCENTERED_CORRELATION =
INT2NUM('x')
METRIC_SPEARMAN =
INT2NUM('s')
METRIC_KENDALL =
INT2NUM('k')

Class Method Summary collapse

Class Method Details

.absolute_correlation_distance(vec1, vec2) ⇒ Object



316
317
318
# File 'ext/flock.c', line 316

VALUE rb_acorrelation(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, acorrelation);
}

.absolute_uncentered_correlation_distance(vec1, vec2) ⇒ Object



320
321
322
# File 'ext/flock.c', line 320

VALUE rb_uacorrelation(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, uacorrelation);
}

.cityblock_distance(vec1, vec2) ⇒ Object



304
305
306
# File 'ext/flock.c', line 304

VALUE rb_cityblock(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, cityblock);
}

.correlation_distance(vec1, vec2) ⇒ Object



308
309
310
# File 'ext/flock.c', line 308

VALUE rb_correlation(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, correlation);
}

.euclidian_distance(vec1, vec2) ⇒ Object



300
301
302
# File 'ext/flock.c', line 300

VALUE rb_euclid(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, euclid);
}

.kendall_distance(vec1, vec2) ⇒ Object



328
329
330
# File 'ext/flock.c', line 328

VALUE rb_kendall(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, kendall);
}

.kmeans(*args) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'ext/flock.c', line 24

VALUE rb_kmeans(int argc, VALUE *argv, VALUE self) {
    VALUE size, data, mask, weights, options;
    rb_scan_args(argc, argv, "22", &size, &data, &mask, &options);

    if (TYPE(data) != T_ARRAY)
        rb_raise(rb_eArgError, "data should be an array of arrays");

    if (!NIL_P(mask) && TYPE(mask) != T_ARRAY)
        rb_raise(rb_eArgError, "mask should be an array of arrays");

    if (NIL_P(size) || NUM2INT(rb_Integer(size)) > RARRAY_LEN(data))
        rb_raise(rb_eArgError, "size should be > 0 and <= data size");

    int transpose = opt_int_value(options, "transpose", 0);
    int npass     = opt_int_value(options, "iterations", 1000);
    // a = average, m = means
    int method    = opt_int_value(options, "method", 'a');
    // e = euclidian,
    // b = city-block distance
    // c = correlation
    // a = absolute value of the correlation
    // u = uncentered correlation
    // x = absolute uncentered correlation
    // s = spearman's rank correlation
    // k = kendall's tau
    int dist      = opt_int_value(options, "metric", 'e');

    int i,j;
    int nrows = RARRAY_LEN(data);
    int ncols = RARRAY_LEN(rb_ary_entry(data, 0));
    int nsets = NUM2INT(rb_Integer(size));

    double **cdata          = (double**)malloc(sizeof(double*)*nrows);
    int    **cmask          = (int   **)malloc(sizeof(int   *)*nrows);
    double *cweights        = (double *)malloc(sizeof(double )*ncols);

    double **ccentroid;
    int *ccluster, **ccentroid_mask, dimx = nrows, dimy = ncols, cdimx = nsets, cdimy = ncols;

    for (i = 0; i < nrows; i++) {
        cdata[i]          = (double*)malloc(sizeof(double)*ncols);
        cmask[i]          = (int   *)malloc(sizeof(int   )*ncols);
        for (j = 0; j < ncols; j++) {
            cdata[i][j] = NUM2DBL(rb_Float(rb_ary_entry(rb_ary_entry(data, i), j)));
            cmask[i][j] = NIL_P(mask) ? 1 : NUM2INT(rb_Integer(rb_ary_entry(rb_ary_entry(mask, i), j)));
        }
    }

    weights = NIL_P(options) ? Qnil : rb_hash_aref(options, ID2SYM(rb_intern("weights")));
    for (i = 0; i < ncols; i++) {
        cweights[i] = NIL_P(weights) ? 1.0 : NUM2DBL(rb_Float(rb_ary_entry(weights, i)));
    }

    if (transpose) {
        dimx  = ncols;
        dimy  = nrows;
        cdimx = nrows;
        cdimy = nsets;
    }

    ccluster       = (int    *)malloc(sizeof(int    )*dimx);
    ccentroid      = (double**)malloc(sizeof(double*)*cdimx);
    ccentroid_mask = (int   **)malloc(sizeof(int   *)*cdimx);

    for (i = 0; i < cdimx; i++) {
      ccentroid[i]      = (double*)malloc(sizeof(double)*cdimy);
      ccentroid_mask[i] = (int   *)malloc(sizeof(int   )*cdimy);
    }

    int    ifound;
    double error;

    kcluster(nsets,
        nrows, ncols, cdata, cmask, cweights, transpose, npass, method, dist, ccluster, &error, &ifound);
    getclustercentroids(nsets,
        nrows, ncols, cdata, cmask, ccluster, ccentroid, ccentroid_mask, transpose, method);

    VALUE result   = rb_hash_new();
    VALUE cluster  = rb_ary_new();
    VALUE centroid = rb_ary_new();

    for (i = 0; i < dimx; i++)
        rb_ary_push(cluster, INT2NUM(ccluster[i]));

    for (i = 0; i < cdimx; i++) {
        VALUE point = rb_ary_new();
        for (j = 0; j < cdimy; j++)
            rb_ary_push(point, DBL2NUM(ccentroid[i][j]));
        rb_ary_push(centroid, point);
    }

    rb_hash_aset(result, ID2SYM(rb_intern("cluster")),   cluster);
    rb_hash_aset(result, ID2SYM(rb_intern("centroid")),  centroid);
    rb_hash_aset(result, ID2SYM(rb_intern("error")),     DBL2NUM(error));
    rb_hash_aset(result, ID2SYM(rb_intern("repeated")),  INT2NUM(ifound));

    for (i = 0; i < nrows; i++) {
        free(cdata[i]);
        free(cmask[i]);
    }

    for (i = 0; i < cdimx; i++) {
        free(ccentroid[i]);
        free(ccentroid_mask[i]);
    }

    free(cdata);
    free(cmask);
    free(ccentroid);
    free(ccentroid_mask);
    free(cweights);
    free(ccluster);

    return result;
}

.self_organizing_map(*args) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'ext/flock.c', line 140

VALUE rb_som(int argc, VALUE *argv, VALUE self) {
    VALUE nx, ny, data, mask, weights, options;
    rb_scan_args(argc, argv, "32", &nx, &ny, &data, &mask, &options);

    if (TYPE(data) != T_ARRAY)
        rb_raise(rb_eArgError, "data should be an array of arrays");

    if (!NIL_P(mask) && TYPE(mask) != T_ARRAY)
        rb_raise(rb_eArgError, "mask should be an array of arrays");

    if (NIL_P(nx) || NUM2INT(rb_Integer(nx)) <= 0)
        rb_raise(rb_eArgError, "nx should be > 0");

    if (NIL_P(ny) || NUM2INT(rb_Integer(ny)) <= 0)
        rb_raise(rb_eArgError, "ny should be > 0");

    int nxgrid    = NUM2INT(rb_Integer(nx));
    int nygrid    = NUM2INT(rb_Integer(ny));
    int transpose = opt_int_value(options, "transpose", 0);
    int npass     = opt_int_value(options, "iterations", 1000);

    // e = euclidian,
    // b = city-block distance
    // c = correlation
    // a = absolute value of the correlation
    // u = uncentered correlation
    // x = absolute uncentered correlation
    // s = spearman's rank correlation
    // k = kendall's tau
    int dist      = opt_int_value(options, "metric", 'e');
    double tau    = opt_double_value(options, "tau", 1.0);

    int i, j, k;
    int nrows = RARRAY_LEN(data);
    int ncols = RARRAY_LEN(rb_ary_entry(data, 0));

    double **cdata          = (double**)malloc(sizeof(double*)*nrows);
    int    **cmask          = (int   **)malloc(sizeof(int   *)*nrows);
    double *cweights        = (double *)malloc(sizeof(double )*ncols);

    int **ccluster;
    double ***ccelldata;
    int dimx = nrows, dimy = ncols;

    if (transpose) {
        dimx = ncols;
        dimy = nrows;
    }

    ccluster = (int **)malloc(sizeof(int*)*dimx);
    for (i = 0; i < dimx; i++)
        ccluster[i] = (int*)malloc(sizeof(int)*2);

    for (i = 0; i < nrows; i++) {
        cdata[i]          = (double*)malloc(sizeof(double)*ncols);
        cmask[i]          = (int   *)malloc(sizeof(int   )*ncols);
        for (j = 0; j < ncols; j++) {
            cdata[i][j] = NUM2DBL(rb_Float(rb_ary_entry(rb_ary_entry(data, i), j)));
            cmask[i][j] = NIL_P(mask) ? 1 : NUM2INT(rb_Integer(rb_ary_entry(rb_ary_entry(mask, i), j)));
        }
    }

    weights = NIL_P(options) ? Qnil : rb_hash_aref(options, ID2SYM(rb_intern("weights")));
    for (i = 0; i < ncols; i++) {
        cweights[i] = NIL_P(weights) ? 1.0 : NUM2DBL(rb_Float(rb_ary_entry(weights, i)));
    }

    ccelldata = (double***)malloc(sizeof(double**)*nxgrid);
    for (i = 0; i < nxgrid; i++) {
        ccelldata[i] = (double **)malloc(sizeof(double*)*nygrid);
        for (j = 0; j < nygrid; j++)
            ccelldata[i][j] = (double *)malloc(sizeof(double)*dimy);
    }

    somcluster(nrows, ncols, cdata, cmask, cweights, transpose,
        nxgrid, nygrid, tau, npass, dist, ccelldata, ccluster);

    VALUE result   = rb_hash_new();
    VALUE cluster  = rb_ary_new();
    VALUE centroid = rb_ary_new();

    for (i = 0; i < dimx; i++)
        rb_ary_push(cluster, INT2NUM(ccluster[i][0] * nxgrid + ccluster[i][1]));

    for (i = 0; i < nxgrid; i++) {
        for (j = 0; j < nygrid; j++) {
            VALUE point = rb_ary_new();
            for (k = 0; k < dimy; k++)
                rb_ary_push(point, DBL2NUM(ccelldata[i][j][k]));
            rb_ary_push(centroid, point);
        }
    }

    rb_hash_aset(result, ID2SYM(rb_intern("cluster")),   cluster);
    rb_hash_aset(result, ID2SYM(rb_intern("centroid")),  centroid);

    for (i = 0; i < nrows; i++) {
        free(cdata[i]);
        free(cmask[i]);
    }

    for (i = 0; i < dimx; i++)
        free(ccluster[i]);

    for (i = 0; i < nxgrid; i++) {
        for (j = 0; j < nygrid; j++)
            free(ccelldata[i][j]);
        free(ccelldata[i]);
    }

    free(cdata);
    free(cmask);
    free(ccelldata);
    free(cweights);
    free(ccluster);

    return result;
}

.sparse_array_to_data(sparse_data) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/flock.rb', line 14

def self.sparse_array_to_data sparse_data
  dims = Hash[sparse_data.flatten.uniq.map.with_index{|k,v| [k,v]}]
  data = sparse_data.map do |sv|
    vector = Array.new(dims.size) {0}
    sv.each {|k| vector[dims[k]] = 1 }
    vector
  end
  [dims,data]
end

.sparse_hash_to_data(sparse_data) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/flock.rb', line 4

def self.sparse_hash_to_data sparse_data
  dims = Hash[sparse_data.map(&:keys).flatten.uniq.map.with_index{|k,v| [k,v]}]
  data = sparse_data.map do |sv|
    vector = Array.new(dims.size) {0}
    sv.each {|k,v| vector[dims[k]] = v }
    vector
  end
  [dims,data]
end

.sparse_kmeans(size, sparse_data, options = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/flock.rb', line 24

def self.sparse_kmeans size, sparse_data, options = {}
  dims, data = sparse_data[0].kind_of?(Array) ? sparse_array_to_data(sparse_data) : sparse_hash_to_data(sparse_data)

  if options.key?(:weights)
    weights = Array.new(dims.size) {1}
    options[:weights].each {|k,v| weights[dims[k]] = v }
    options[:weights] = weights
  end

  kmeans(size, data, nil, options)
end

.sparse_self_organizing_map(nx, ny, sparse_data, options = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/flock.rb', line 36

def self.sparse_self_organizing_map nx, ny, sparse_data, options = {}
  dims, data = sparse_data[0].kind_of?(Array) ? sparse_array_to_data(sparse_data) : sparse_hash_to_data(sparse_data)

  if options.key?(:weights)
    weights = Array.new(dims.size) {1}
    options[:weights].each {|k,v| weights[dims[k]] = v }
    options[:weights] = weights
  end

  self_organizing_map(nx, ny, data, nil, options)
end

.spearman_distance(vec1, vec2) ⇒ Object



324
325
326
# File 'ext/flock.c', line 324

VALUE rb_spearman(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, spearman);
}

.uncentered_correlation_distance(vec1, vec2) ⇒ Object



312
313
314
# File 'ext/flock.c', line 312

VALUE rb_ucorrelation(VALUE self, VALUE vec1, VALUE vec2) {
    return rb_distance(vec1, vec2, ucorrelation);
}