Class: Kmeans::Dendrogram

Inherits:
Object
  • Object
show all
Defined in:
lib/kmeans/dendrogram.rb

Instance Method Summary collapse

Constructor Details

#initialize(user_options = {}) ⇒ Dendrogram

Returns a new instance of Dendrogram.



8
9
10
11
12
13
14
15
16
# File 'lib/kmeans/dendrogram.rb', line 8

def initialize(user_options = {})
  @options = {
    :imagefile => 'clusters.png',
    :font_path => '/usr/share/fonts/truetype/vlgothic/VL-Gothic-Regular.ttf',
    :stroke => 'transparent',
    :fill => 'black',
    :pointsize => 10
  }.merge(user_options)
end

Instance Method Details

#drawdendrogram(clust, labels) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/kmeans/dendrogram.rb', line 18

def drawdendrogram(clust, labels)
  h = getheight(clust) * 20
  w = 1200
  depth = getdepth(clust)

  scaling = Float(w-150)/depth

  img = Image.new(w,h)
  draw = Draw.new
  draw.stroke('red')
  draw.stroke_width(1)
  draw.line(0, h/2, 10, h/2)

  drawnode(draw, clust, 10, (h/2), scaling, labels)

  draw.draw(img)
  img.write(@options[:imagefile])
end

#drawnode(draw, clust, x, y, scaling, labels) ⇒ Object



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
# File 'lib/kmeans/dendrogram.rb', line 37

def drawnode(draw, clust, x, y, scaling, labels)
  if clust.id < 0
    h1 = getheight(clust.left) * 20
    h2 = getheight(clust.right) * 20
    top = y-(h1+h2)/2
    bottom = y+(h1+h2)/2

    ll = clust.distance*scaling

    draw.stroke('red')
    draw.line(x, top+h1/2, x, bottom-h2/2)

    draw.line(x, top+h1/2, x+ll, top+h1/2)
    draw.line(x, bottom-h2/2, x+ll, bottom-h2/2)

    drawnode(draw, clust.left, x+ll, top+h1/2, scaling, labels)
    drawnode(draw, clust.right, x+ll, bottom-h2/2, scaling, labels)
  else
    draw.font = @options[:font_path]
    draw.stroke(@options[:stroke])
    draw.fill(@options[:fill])
    draw.pointsize = @options[:pointsize]
    label = labels[clust.id]
    draw.text(x+3, y+4, label) if label != nil
  end
end

#getdepth(clust) ⇒ Object



64
65
66
67
# File 'lib/kmeans/dendrogram.rb', line 64

def getdepth(clust)
  return 0 if clust.left == nil && clust.right == nil
  return [getdepth(clust.left),getdepth(clust.right)].max + clust.distance
end

#getheight(clust) ⇒ Object



69
70
71
72
# File 'lib/kmeans/dendrogram.rb', line 69

def getheight(clust)
  return 1 if clust.left == nil && clust.right == nil
  return getheight(clust.left) + getheight(clust.right)
end