forked from psykhi/wordclouds
/
wordcloud.go
487 lines (432 loc) · 10.4 KB
/
wordcloud.go
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
483
484
485
486
487
package wordclouds
import (
"github.com/fogleman/gg"
"golang.org/x/image/font"
"image"
"image/color"
"math"
"math/rand"
"runtime"
"sort"
"sync"
)
type wordCount struct {
word string
count int
}
type word2D struct {
wordCount
x float64
y float64
height float64
boundingBox *Box
}
// Wordcloud object. Create one with NewWordcloud and use Draw() to get the image
type Wordcloud struct {
wordList map[string]int
sortedWordList []wordCount
grid *spatialHashMap
dc *gg.Context
overlapCount int
words2D []*word2D
availableColors []color.Color
randomPlacement bool
width float64
height float64
opts Options
circles map[float64]*circle
fonts map[float64]font.Face
radii []float64
}
type Options struct {
FontMaxSize int
FontMinSize int
RandomPlacement bool
FontFile string
Colors []color.Color
BackgroundColor color.Color
Width int
Height int
Mask []*Box
Debug bool
}
var defaultOptions = Options{
FontMaxSize: 500,
FontMinSize: 10,
RandomPlacement: false,
FontFile: "",
Colors: []color.Color{color.RGBA{}},
BackgroundColor: color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff},
Width: 2048,
Height: 2048,
Mask: make([]*Box, 0),
Debug: false,
}
type Option func(*Options)
// Path to font file
func FontFile(path string) Option {
return func(options *Options) {
options.FontFile = path
}
}
// Output file background color
func BackgroundColor(color color.Color) Option {
return func(options *Options) {
options.BackgroundColor = color
}
}
// Colors to use for the words
func Colors(colors []color.Color) Option {
return func(options *Options) {
options.Colors = colors
}
}
// Max font size
func FontMaxSize(max int) Option {
return func(options *Options) {
options.FontMaxSize = max
}
}
// Min font size
func FontMinSize(min int) Option {
return func(options *Options) {
options.FontMinSize = min
}
}
// A list of bounding boxes where words can not be placed.
// See Mask
func MaskBoxes(mask []*Box) Option {
return func(options *Options) {
options.Mask = mask
}
}
func Width(w int) Option {
return func(options *Options) {
options.Width = w
}
}
func Height(h int) Option {
return func(options *Options) {
options.Height = h
}
}
// Place words randomly
func RandomPlacement(do bool) Option {
return func(options *Options) {
options.RandomPlacement = do
}
}
// Draw bounding boxes around words
func Debug() Option {
return func(options *Options) {
options.Debug = true
}
}
// Initialize a wordcloud based on a map of word frequency.
func NewWordcloud(wordList map[string]int, options ...Option) *Wordcloud {
opts := defaultOptions
for _, opt := range options {
opt(&opts)
}
sortedWordList := make([]wordCount, 0, len(wordList))
for word, count := range wordList {
sortedWordList = append(sortedWordList, wordCount{word: word, count: count})
}
sort.Slice(sortedWordList, func(i, j int) bool {
return sortedWordList[i].count > sortedWordList[j].count
})
dc := gg.NewContext(opts.Width, opts.Height)
dc.SetColor(opts.BackgroundColor)
dc.Clear()
dc.SetRGB(0, 0, 0)
grid := newSpatialHashMap(float64(opts.Width), float64(opts.Height), opts.Height/10)
for _, b := range opts.Mask {
if opts.Debug {
dc.DrawRectangle(b.x(), b.y(), b.w(), b.h())
dc.Stroke()
}
grid.Add(b)
}
radius := 1.0
maxRadius := math.Sqrt(float64(opts.Width*opts.Width + opts.Height*opts.Height))
circles := make(map[float64]*circle)
radii := make([]float64, 0)
for radius < maxRadius {
circles[radius] = newCircle(float64(opts.Width/2), float64(opts.Height/2), radius, 512)
radii = append(radii, radius)
radius = radius + 5.0
}
return &Wordcloud{
wordList: wordList,
sortedWordList: sortedWordList,
grid: grid,
dc: dc,
words2D: make([]*word2D, 0),
randomPlacement: opts.RandomPlacement,
width: float64(opts.Width),
height: float64(opts.Height),
opts: opts,
circles: circles,
fonts: make(map[float64]font.Face),
radii: radii,
}
}
func (w *Wordcloud) getPreciseBoundingBoxes(b *Box) []*Box {
res := make([]*Box, 0)
step := 5
defColor := color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}
for i := int(math.Floor(b.Left)); i < int(b.Right); i = i + step {
for j := int(b.Bottom); j < int(b.Top); j = j + step {
if w.dc.Image().At(i, j) != defColor {
res = append(res, &Box{
float64(j+step) + 5,
float64(i) - 5,
float64(i+step) + 5,
float64(j) - 5,
})
}
}
}
return res
}
func (w *Wordcloud) setFont(size float64) {
_, ok := w.fonts[size]
if !ok {
f, err := gg.LoadFontFace(w.opts.FontFile, size)
if err != nil {
panic(err)
}
w.fonts[size] = f
}
w.dc.SetFontFace(w.fonts[size])
}
func (w *Wordcloud) Place(wc wordCount) bool {
c := w.opts.Colors[rand.Intn(len(w.opts.Colors))]
w.dc.SetColor(c)
size := float64(w.opts.FontMaxSize) * (float64(wc.count) / float64(w.sortedWordList[0].count))
if size < float64(w.opts.FontMinSize) {
size = float64(w.opts.FontMinSize)
}
w.setFont(size)
width, height := w.dc.MeasureString(wc.word)
width += 5
height += 5
x, y, space := w.nextPos(width, height)
if !space {
return false
}
w.dc.DrawStringAnchored(wc.word, x, y, 0.5, 0.5)
box := &Box{
y + height/2 + 0.3*height,
x - width/2,
x + width/2,
math.Max(y-height/2, 0),
}
if height > 40 {
preciseBoxes := w.getPreciseBoundingBoxes(box)
for _, pb := range preciseBoxes {
w.grid.Add(pb)
if w.opts.Debug {
w.dc.DrawRectangle(pb.x(), pb.y(), pb.w(), pb.h())
w.dc.Stroke()
}
}
} else {
w.grid.Add(box)
}
return true
}
// Draw tries to place words one by one, starting with the ones with the highest counts
func (w *Wordcloud) Draw() image.Image {
consecutiveMisses := 0
for _, wc := range w.sortedWordList {
success := w.Place(wc)
if !success {
consecutiveMisses++
if consecutiveMisses > 10 {
return w.dc.Image()
}
continue
}
consecutiveMisses = 0
}
return w.dc.Image()
}
func (w *Wordcloud) nextRandom(width float64, height float64) (x float64, y float64, space bool) {
tries := 0
searching := true
var box Box
for searching && tries < 500000 {
tries++
x, y = float64(rand.Intn(w.dc.Width())), float64(rand.Intn(w.dc.Height()))
// Is that position available?
box.Top = y + height/2
box.Left = x - width/2
box.Right = x + width/2
box.Bottom = y - height/2
if !box.fits(w.width, w.height) {
continue
}
colliding, _ := w.grid.TestCollision(&box, func(a *Box, b *Box) bool {
return a.overlaps(b)
})
if !colliding {
space = true
searching = false
return
}
}
return
}
// Data sent to placement workers
type workerData struct {
radius float64
positions []point
width float64
height float64
}
// Results sent from placement workers
type res struct {
radius float64
x float64
y float64
failed bool
}
// Multithreaded word placement
func (w *Wordcloud) nextPos(width float64, height float64) (x float64, y float64, space bool) {
if w.randomPlacement {
return w.nextRandom(width, height)
}
space = false
x, y = w.width, w.height
stopSendingCh := make(chan struct{}, 1)
aggCh := make(chan res, 100)
workCh := make(chan workerData, runtime.NumCPU())
results := make(map[float64]res)
done := make(map[float64]bool)
stopChannels := make([]chan struct{}, 0)
wg := sync.WaitGroup{}
// Start workers that will test each one "circle" of positions
for i := 0; i < runtime.NumCPU(); i++ {
wg.Add(1)
stopCh := make(chan struct{}, 1)
go func(ch chan struct{}, i int) {
defer wg.Done()
for {
select {
// Receive data
case d, ok := <-workCh:
if !ok {
return
}
// Test the positions and post results on aggCh
aggCh <- w.testRadius(d.radius, d.positions, d.width, d.height)
case <-ch:
// Stop signal
return
}
}
}(stopCh, i)
stopChannels = append(stopChannels, stopCh)
}
// Post positions to test to worker channel
go func() {
for _, r := range w.radii {
c := w.circles[r]
select {
case <-stopSendingCh:
// Stop sending data immediately if a position has already been found
close(workCh)
return
case workCh <- workerData{
radius: r,
positions: c.positions(),
width: width,
height: height,
}:
}
}
// Close channel after all positions have been sent
close(workCh)
}()
defer func() {
// Stop data sending
stopSendingCh <- struct{}{}
// Tell the worker goroutines to stop
for _, c := range stopChannels {
c <- struct{}{}
}
// Purge res channel in case some workers are still sending data
go func() {
for {
select {
case <-aggCh:
default:
return
}
}
}()
// Wait for all goroutines to stop. We want to wait for them so that no thread is accessing internal data structs
// such as the spatial hashmap
wg.Wait()
}()
// Finally, aggregate the results coming from workers
for d := range aggCh {
results[d.radius] = d
done[d.radius] = true
//check if we need to continue
failed := true
// Example: if we know that there's a successful placement at r=10 but have not received results for r=5,
// we need to wait as there might be a closer successful position
for _, r := range w.radii {
if !done[r] {
// Some positions are not done. They might be successful
failed = false
break
}
// We have the successful placement with the lowest radius
if !results[r].failed {
return results[r].x, results[r].y, true
}
}
// We tried it all but could not place the word
if failed {
return
}
}
return
}
// test a series of points on a circle and returns as soon as there's a match
func (w *Wordcloud) testRadius(radius float64, points []point, width float64, height float64) res {
var box Box
var x, y float64
for _, p := range points {
y = p.y
x = p.x
// Is that position available?
box.Top = y + height/2
box.Left = x - width/2
box.Right = x + width/2
box.Bottom = y - height/2
if !box.fits(w.width, w.height) {
continue
}
colliding, _ := w.grid.TestCollision(&box, func(a *Box, b *Box) bool {
return a.overlaps(b)
})
if !colliding {
return res{
x: x,
y: y,
failed: false,
radius: radius,
}
}
}
return res{
x: x,
y: y,
failed: true,
radius: radius,
}
}