1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 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
139
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use num_traits::Float;

use crate::condensed::CondensedMatrix;
use crate::dendrogram::Dendrogram;
use crate::method;
use crate::{LinkageState, Method};

/// Perform hierarchical clustering using Müllner's "generic" algorithm.
///
/// In general, one should prefer to use
/// [`linkage`](fn.linkage.html),
/// since it tries to pick the fastest algorithm depending on the method
/// supplied.
pub fn generic<T: Float>(
    condensed_dissimilarity_matrix: &mut [T],
    observations: usize,
    method: Method,
) -> Dendrogram<T> {
    let matrix = condensed_dissimilarity_matrix;
    let mut state = LinkageState::new();
    let mut steps = Dendrogram::new(observations);
    generic_with(&mut state, matrix, observations, method, &mut steps);
    steps
}

/// Like [`generic`](fn.generic.html), but amortizes allocation.
///
/// See [`linkage_with`](fn.linkage_with.html) for details.
#[inline(never)]
pub fn generic_with<T: Float>(
    state: &mut LinkageState<T>,
    condensed_dissimilarity_matrix: &mut [T],
    observations: usize,
    method: Method,
    steps: &mut Dendrogram<T>,
) {
    let matrix = condensed_dissimilarity_matrix;
    method.square(matrix);
    let mut dis = CondensedMatrix::new(matrix, observations);

    steps.reset(dis.observations());
    if dis.observations() == 0 {
        return;
    }
    state.reset(dis.observations());

    {
        // For each observation `row`, find its nearest neighbor and
        // record it in our heap.
        let nearest = &mut state.nearest;
        state.queue.heapify(|dists| {
            for row in 0..dis.observations() - 1 {
                let (mut min, mut min_dist) = (row + 1, dis[[row, row + 1]]);
                for col in (row + 1)..dis.observations() {
                    if dis[[row, col]] < min_dist {
                        min = col;
                        min_dist = dis[[row, col]];
                    }
                }
                dists[row] = min_dist;
                nearest[row] = min;
            }
        });
    }
    for _ in 0..dis.observations() - 1 {
        loop {
            // `a` is our candidate observation to start with. Ideally,
            // state.nearest[a] will tell us which cluster to merge with,
            // but it could be wrong. It is wrong precisely when
            // the minimum distance associated with `a` (its "priority")
            // is less than dis[[a, state.nearest[a]]]. In that case, we need
            // to rescan the other observations and find its actual nearest
            // neighbor.
            let a = state.queue.peek().unwrap();
            if dis[[a, state.nearest[a]]] == *state.queue.priority(a) {
                break;
            }

            let mut min = T::max_value();
            for x in state.active.range(a..).skip(1) {
                if dis[[a, x]] < min {
                    min = dis[[a, x]];
                    state.nearest[a] = x;
                }
            }
            state.queue.set_priority(a, min);
        }

        let a = state.queue.pop().unwrap();
        let b = state.nearest[a];
        let dist = dis[[a, b]];
        match method {
            Method::Single => single(state, &mut dis, a, b),
            Method::Complete => complete(state, &mut dis, a, b),
            Method::Average => average(state, &mut dis, a, b),
            Method::Weighted => weighted(state, &mut dis, a, b),
            Method::Ward => ward(state, &mut dis, a, b),
            Method::Centroid => centroid(state, &mut dis, a, b),
            Method::Median => median(state, &mut dis, a, b),
        }
        state.merge(steps, a, b, dist);
    }
    state.set.relabel(steps, method);
    method.sqrt(steps);
}

#[inline]
fn single<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;

    for x in state.active.range(..a) {
        method::single(dis[[x, a]], &mut dis[[x, b]]);
        if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::single(dis[[a, x]], &mut dis[[x, b]]);
        if &dis[[x, ab]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, ab]]);
            state.nearest[x] = ab;
        }
    }
    let mut min = *state.queue.priority(b);
    for x in state.active.range(b..).skip(1) {
        method::single(dis[[a, x]], &mut dis[[b, x]]);
        if dis[[ab, x]] < min {
            state.queue.set_priority(b, dis[[ab, x]]);
            state.nearest[b] = x;
            min = dis[[ab, x]];
        }
    }
}

#[inline]
fn complete<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;

    for x in state.active.range(..a) {
        method::complete(dis[[x, a]], &mut dis[[x, b]]);
        if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::complete(dis[[a, x]], &mut dis[[x, b]]);
    }
    for x in state.active.range(b..).skip(1) {
        method::complete(dis[[a, x]], &mut dis[[b, x]]);
    }
}

#[inline]
fn average<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;
    let (size_a, size_b) = (state.sizes[a], state.sizes[b]);

    for x in state.active.range(..a) {
        method::average(dis[[x, a]], &mut dis[[x, b]], size_a, size_b);
        if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::average(dis[[a, x]], &mut dis[[x, b]], size_a, size_b);
        if &dis[[x, ab]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, ab]]);
            state.nearest[x] = ab;
        }
    }
    let mut min = *state.queue.priority(b);
    for x in state.active.range(b..).skip(1) {
        method::average(dis[[a, x]], &mut dis[[b, x]], size_a, size_b);
        if dis[[ab, x]] < min {
            state.queue.set_priority(b, dis[[ab, x]]);
            state.nearest[b] = x;
            min = dis[[ab, x]];
        }
    }
}

#[inline]
fn weighted<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;

    for x in state.active.range(..a) {
        method::weighted(dis[[x, a]], &mut dis[[x, b]]);
        if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::weighted(dis[[a, x]], &mut dis[[x, b]]);
        if &dis[[x, ab]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, ab]]);
            state.nearest[x] = ab;
        }
    }
    let mut min = *state.queue.priority(b);
    for x in state.active.range(b..).skip(1) {
        method::weighted(dis[[a, x]], &mut dis[[b, x]]);
        if dis[[ab, x]] < min {
            state.queue.set_priority(b, dis[[ab, x]]);
            state.nearest[b] = x;
            min = dis[[ab, x]];
        }
    }
}

#[inline]
fn ward<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;
    let (size_a, size_b) = (state.sizes[a], state.sizes[b]);
    let dist = dis[[a, b]];

    for x in state.active.range(..a) {
        method::ward(
            dis[[x, a]],
            &mut dis[[x, b]],
            dist,
            size_a,
            size_b,
            state.sizes[x],
        );
        if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::ward(
            dis[[a, x]],
            &mut dis[[x, b]],
            dist,
            size_a,
            size_b,
            state.sizes[x],
        );
        if &dis[[x, ab]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, ab]]);
            state.nearest[x] = ab;
        }
    }
    let mut min = *state.queue.priority(b);
    for x in state.active.range(b..).skip(1) {
        method::ward(
            dis[[a, x]],
            &mut dis[[b, x]],
            dist,
            size_a,
            size_b,
            state.sizes[x],
        );
        if dis[[ab, x]] < min {
            state.queue.set_priority(b, dis[[ab, x]]);
            state.nearest[b] = x;
            min = dis[[ab, x]];
        }
    }
}

#[inline]
fn centroid<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;
    let (size_a, size_b) = (state.sizes[a], state.sizes[b]);
    let dist = dis[[a, b]];

    for x in state.active.range(..a) {
        method::centroid(dis[[x, a]], &mut dis[[x, b]], dist, size_a, size_b);
        if &dis[[x, b]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, b]]);
            state.nearest[x] = ab;
        } else if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::centroid(dis[[a, x]], &mut dis[[x, b]], dist, size_a, size_b);
        if &dis[[x, ab]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, ab]]);
            state.nearest[x] = ab;
        }
    }
    let mut min = *state.queue.priority(b);
    for x in state.active.range(b..).skip(1) {
        method::centroid(dis[[a, x]], &mut dis[[b, x]], dist, size_a, size_b);
        if dis[[ab, x]] < min {
            state.queue.set_priority(b, dis[[ab, x]]);
            state.nearest[b] = x;
            min = dis[[ab, x]];
        }
    }
}

#[inline]
fn median<T: Float>(
    state: &mut LinkageState<T>,
    dis: &mut CondensedMatrix<'_, T>,
    a: usize,
    b: usize,
) {
    let ab = b;
    let dist = dis[[a, b]];

    for x in state.active.range(..a) {
        method::median(dis[[x, a]], &mut dis[[x, b]], dist);
        if &dis[[x, b]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, b]]);
            state.nearest[x] = ab;
        } else if state.nearest[x] == a {
            state.nearest[x] = ab;
        }
    }
    for x in state.active.range(a..b).skip(1) {
        method::median(dis[[a, x]], &mut dis[[x, b]], dist);
        if &dis[[x, ab]] < state.queue.priority(x) {
            state.queue.set_priority(x, dis[[x, ab]]);
            state.nearest[x] = ab;
        }
    }
    let mut min = *state.queue.priority(b);
    for x in state.active.range(b..).skip(1) {
        method::median(dis[[a, x]], &mut dis[[b, x]], dist);
        if dis[[ab, x]] < min {
            state.queue.set_priority(b, dis[[ab, x]]);
            state.nearest[b] = x;
            min = dis[[ab, x]];
        }
    }
}

#[cfg(test)]
mod tests {
    use super::generic;
    use crate::test::DistinctMatrix;
    use crate::{nnchain, primitive, Method, MethodChain};

    quickcheck::quickcheck! {
        fn prop_generic_single_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Single);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Single);
            dend_prim == dend_generic
        }

        fn prop_generic_complete_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Complete);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Complete);
            dend_prim == dend_generic
        }

        fn prop_generic_average_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Average);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Average);
            dend_prim == dend_generic
        }

        fn prop_generic_weighted_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Weighted);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Weighted);
            dend_prim == dend_generic
        }

        fn prop_generic_ward_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Ward);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Ward);
            dend_prim == dend_generic
        }

        fn prop_generic_centroid_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Centroid);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Centroid);
            dend_prim.eq_with_epsilon(&dend_generic, 0.0000000001)
        }

        fn prop_generic_median_primitive(mat: DistinctMatrix) -> bool {
            let dend_prim = primitive(
                &mut mat.matrix(), mat.len(), Method::Median);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Median);
            dend_prim.eq_with_epsilon(&dend_generic, 0.0000000001)
        }

        fn prop_generic_single_nnchain(mat: DistinctMatrix) -> bool {
            let dend_nnchain = nnchain(
                &mut mat.matrix(), mat.len(), MethodChain::Single);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Single);
            dend_nnchain == dend_generic
        }

        fn prop_generic_complete_nnchain(mat: DistinctMatrix) -> bool {
            let dend_nnchain = nnchain(
                &mut mat.matrix(), mat.len(), MethodChain::Complete);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Complete);
            dend_nnchain == dend_generic
        }

        fn prop_generic_average_nnchain(mat: DistinctMatrix) -> bool {
            let dend_nnchain = nnchain(
                &mut mat.matrix(), mat.len(), MethodChain::Average);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Average);
            dend_nnchain.eq_with_epsilon(&dend_generic, 0.0000000001)
        }

        fn prop_generic_weighted_nnchain(mat: DistinctMatrix) -> bool {
            let dend_nnchain = nnchain(
                &mut mat.matrix(), mat.len(), MethodChain::Weighted);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Weighted);
            dend_nnchain.eq_with_epsilon(&dend_generic, 0.0000000001)
        }

        fn prop_generic_ward_nnchain(mat: DistinctMatrix) -> bool {
            let dend_nnchain = nnchain(
                &mut mat.matrix(), mat.len(), MethodChain::Ward);
            let dend_generic = generic(
                &mut mat.matrix(), mat.len(), Method::Ward);
            dend_nnchain.eq_with_epsilon(&dend_generic, 0.0000000001)
        }
    }

    /*
    #[test]
    fn scratch() {
        let mat = DistinctMatrix::new(vec![
            -0.3928520988346005, -0.19043623101168627, -0.2285449764242029,
            -0.10865130150304014, -0.15117962251653982, 0.18559742613333996,
            0.4048708395026879, -0.30910143021593295, -0.3052958564360515,
            0.25927061422572684, -0.07587885646654446, 0.22119746284084774,
            0.45489623801622536, -0.27321164703150713, -0.31500339748457495,
        ]);
        let dend_prim = primitive(
            &mut mat.matrix(), mat.len(), Method::Centroid);
        let dend_generic = generic(
            &mut mat.matrix(), mat.len(), Method::Centroid);
        assert_eq!(dend_prim, dend_generic);
    }
    */
}