Debian Codegraph @

tests/testthat/test-common_subtrees.R

raw
1 # library(testthat)
2 suppressPackageStartupMessages(library(dendextend))
3
4 context("common subtrees")
5
6
7 test_that("rank_values_with_clusters works", {
8 expect_equal(
9 rank_values_with_clusters(c(1, 2, 3)),
10 1:3
11 )
12
13 expect_equal(
14 rank_values_with_clusters(c(1, 1, 3)),
15 c(1L, 1L, 2L)
16 )
17
18 expect_equal(
19 rank_values_with_clusters(c(0.1, 0.1, 3000)),
20 c(1L, 1L, 2L)
21 )
22
23 expect_equal(
24 rank_values_with_clusters(c(3, 1, 2)),
25 1:3
26 )
27 #
28 expect_equal(
29 rank_values_with_clusters(c(1, 3, 3, 3, 3, 3, 3, 4, 2, 2)),
30 c(1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 4L, 4L)
31 )
32
33 expect_equal(
34 rank_values_with_clusters(c(3, 1, 2), ignore0 = TRUE),
35 1:3
36 )
37
38 expect_equal(
39 rank_values_with_clusters(c(3, 1, 2), ignore0 = FALSE),
40 1:3
41 )
42
43 expect_equal(
44 rank_values_with_clusters(c(3, 1, 0, 2), ignore0 = TRUE),
45 c(1, 2, 0, 3)
46 )
47
48 expect_equal(
49 rank_values_with_clusters(c(3, 1, 0, 2), ignore0 = FALSE),
50 1:4
51 )
52 })
53
54
55 test_that("nodes_with_shared_labels works", {
56
57 hc1 <- hclust(dist(mtcars[1:5, ]), method = "complete")
58 dend1 <- as.dendrogram(hc1)
59 hc2 <- hclust(dist(mtcars[1:5, ]), method = "ave")
60 dend2 <- as.dendrogram(hc2)
61
62 # shared nodes should match specified pattern
63 expect_identical(
64 nodes_with_shared_labels(dend1, dend2),
65 c(F, T, T, T, T, T, F, T, T)
66 )
67
68 })
69
70
71 test_that("replace_unique_items_with_0_and_rank works", {
72
73 # replace '5' with 0 because it is unique, convert all other values to a rank
74 x <- c(4,4,3,3,5)
75 expect_identical(
76 replace_unique_items_with_0_and_rank(x),
77 c(1,1,2,2,0)
78 )
79 })
80
81
82 test_that("common_subtrees_clusters works", {
83 suppressWarnings(RNGversion("3.5.0"))
84
85 hc1 <- hclust(dist(mtcars[1:5, ]), method = "complete")
86 dend1 <- as.dendrogram(hc1)
87 hc2 <- hclust(dist(mtcars[1:5, ]), method = "ave")
88 dend2 <- as.dendrogram(hc2)
89
90 # three subtrees should be in common
91 expect_identical(
92 common_subtrees_clusters(dend1, dend2),
93 c(1,1,1,0,0)
94 )
95
96 # temporarily redefine is.leaf to access and cover lines of code otherwise not possible
97 set.seed(3)
98 with_mocked_bindings(
99 common_subtrees_clusters(dend1, dend2),
100 is.leaf = function(x) sample(c(T,F), 1)
101 )
102 })