-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.go
343 lines (289 loc) · 8.86 KB
/
calc.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
package main
import (
"fmt"
"image/color"
"log"
"math"
"math/cmplx"
"math/rand"
"runtime"
"time"
"github.com/brainsik/bae/plane"
)
// CalcStyle is an enum representing the type of calculation that will be performed.
type CalcStyle int
const (
Attractor CalcStyle = iota
Julia
Mandelbrot
)
var CalcStyleName = map[int]string{
int(Attractor): "Attractor",
int(Julia): "Julia",
int(Mandelbrot): "Mandelbrot",
}
// CalcPoint is the mapping between coordinate types.
type CalcPoint struct {
Z complex128
XY plane.ImagePoint
}
// ColorResults maps image plane coordinates to a color.
type ColorResults map[plane.ImagePoint]color.NRGBA
// CalcParams contains all the parameters needed to generate an image.
type CalcParams struct {
Plane *plane.Plane
Style CalcStyle
ZF ZFunc
C complex128
Iterations int
Limit float64
CalcArea plane.PlaneView
RPoints, IPoints int
Concurrency int
CF ColorFunc
CFP ColorFuncParams
}
func (cs CalcStyle) String() string {
return CalcStyleName[int(cs)]
}
func (cp CalcPoint) String() string {
return fmt.Sprintf("{%v, %v}", cp.Z, cp.XY)
}
func (cp *CalcParams) String() string {
return fmt.Sprintf(
"CalcParams{\n%v\nStyle: %v\n%v\n%v\n%v\nc: %v\niterations: %v\nlimit: %v\n"+
"calc area: %v\n"+
"real points: %v in (%v -> %v | %v)\nimag points: %v in (%vi -> %vi | %vi)\n"+
"concurrency: %d\n}",
cp.Plane, cp.Style, cp.ZF, cp.CF, cp.CFP, cp.C, cp.Iterations, cp.Limit, cp.CalcArea,
cp.RPoints, real(cp.CalcArea.Min), real(cp.CalcArea.Max), cp.CalcArea.RealLen(),
cp.IPoints, imag(cp.CalcArea.Min), imag(cp.CalcArea.Max), cp.CalcArea.ImagLen(),
cp.Concurrency)
}
// NewCalcParams returns a new CalcParams object based on the given one.
// Some defaults are set for zeroed fields.
func NewCalcParams(cp CalcParams) *CalcParams {
limit := cp.Limit
if limit == 0 {
limit = 2 * math.Max(
cmplx.Abs(cp.Plane.View().Min),
cmplx.Abs(cp.Plane.View().Max))
}
return &CalcParams{
Plane: cp.Plane,
Style: cp.Style,
ZF: cp.ZF,
C: cp.C,
Iterations: cp.Iterations,
Limit: limit,
CalcArea: cp.CalcArea,
RPoints: cp.RPoints,
IPoints: cp.IPoints,
Concurrency: cp.Concurrency,
CF: cp.CF,
CFP: cp.CFP,
}
}
// NewAllPoints is a helper function that sets the calculation area of the
// CalcParams to the entire plane where the orbit of every point in the image
// is calculated.
func (cp CalcParams) NewAllPoints(iterations int, cf ColorFunc, cfp ColorFuncParams) CalcParams {
if iterations <= 0 {
iterations = cp.Iterations
}
return CalcParams{
// modified
CF: cf,
CFP: cfp,
Iterations: iterations,
CalcArea: cp.Plane.View(),
RPoints: cp.Plane.ImageWidth(),
IPoints: cp.Plane.ImageHeight(),
// unchanged
Plane: cp.Plane,
ZF: cp.ZF,
C: cp.C,
Limit: cp.Limit,
Concurrency: cp.Concurrency,
}
}
// MakePlaneProblemSet returns a problem set for an even distribution of points in the calc_area.
func (cp *CalcParams) MakePlaneProblemSet() (problems []CalcPoint) {
if cp.RPoints <= 0 || cp.IPoints <= 0 {
fmt.Printf("RPoints and IPoints need to be non-zero: R:%v, I:%v", cp.RPoints, cp.IPoints)
return
}
r_step := cp.CalcArea.RealLen() / math.Max(float64(cp.RPoints-1), 1)
i_step := cp.CalcArea.ImagLen() / math.Max(float64(cp.IPoints-1), 1)
t_start := time.Now()
r := real(cp.CalcArea.Min)
for r_pt := 0; r_pt < cp.RPoints; r_pt++ {
i := imag(cp.CalcArea.Min)
for i_pt := 0; i_pt < cp.IPoints; i_pt++ {
z := complex(r, i)
xy := cp.Plane.ToImagePoint(z)
problems = append(problems, CalcPoint{Z: z, XY: xy})
i += i_step
}
r += r_step
}
log.Printf("Took %dms to make problem set\n", time.Since(t_start).Milliseconds())
return
}
// MakeImageProblemSet returns a problem set representing every point in the image plane.
func (cp *CalcParams) MakeImageProblemSet() (problems []CalcPoint) {
t_start := time.Now()
for x := 0; x < cp.Plane.ImageWidth(); x++ {
for y := 0; y < cp.Plane.ImageHeight(); y++ {
xy := plane.ImagePoint{X: x, Y: y}
z := cp.Plane.ToComplexPoint(xy)
problems = append(problems, CalcPoint{Z: z, XY: xy})
}
}
log.Printf("Took %dms to make problem set\n", time.Since(t_start).Milliseconds())
return
}
// Calculate does the actual calculations for each point in the problem set.
func (cp *CalcParams) Calculate(problems []CalcPoint) (histogram CalcResults) {
t_start := time.Now()
calc_id := fmt.Sprintf("%p", problems)
showed_progress := make(map[int]bool)
img_width := cp.Plane.ImageWidth()
img_height := cp.Plane.ImageHeight()
// rz_min, rz_max := real(cp.plane.view.min), real(cp.plane.view.max)
// iz_min, iz_max := imag(cp.plane.view.min), imag(cp.plane.view.max)
var total_its, num_escaped, num_periodic uint
histogram = make(CalcResults)
f_zc := cp.ZF.F
for progress, pt := range problems {
var z, c complex128
if cp.Style == Mandelbrot {
z = complex(0, 0)
c = pt.Z
} else {
z = pt.Z
c = cp.C
}
rag := make(map[complex128]bool)
for its := 0; its < cp.Iterations; its++ {
total_its++
z = f_zc(z, c)
xy := cp.Plane.ToImagePoint(z)
// if real(z) < rz_min || real(z) > rz_max || imag(z) < iz_min || imag(z) > iz_max {
// continue
// }
// Escaped?
if cmplx.Abs(z) > cp.Limit {
if cp.Style == Attractor {
histogram.Add(xy, z, 1).Escaped = true
} else {
histogram.Add(pt.XY, pt.Z, 1).Escaped = true
}
num_escaped++
// fmt.Printf("Point %v escaped after %v iterations\n", z0, its)
break
}
// Periodic?
if rag[z] {
if cp.Style == Attractor {
histogram.Add(xy, z, 1).Periodic = true
} else {
histogram.Add(pt.XY, pt.Z, 1).Periodic = true
}
num_periodic++
// fmt.Printf("Point %v become periodic after %v iterations\n", z0, its)
break
}
rag[z] = true
if cp.Style == Attractor {
// Only add to histogram if pixel is in the image plane.
if xy.X >= 0 && xy.X <= img_width && xy.Y >= 0 && xy.Y <= img_height {
histogram.Add(xy, z, 1)
}
} else {
histogram.Add(pt.XY, pt.Z, 1)
}
}
// Show progress.
elapsed := time.Since(t_start).Seconds()
if int(elapsed+1)%6 == 0 && !showed_progress[int(elapsed)] {
percent := float64(progress) / float64(len(problems))
t_remaining := (elapsed / percent) - elapsed
fmt.Printf("[%v] ⌚️ Workin %v %6.0fs remaining\n",
time.Now().Format(time.StampMilli), calc_id, t_remaining)
showed_progress[int(elapsed)] = true
}
}
t_total := time.Since(t_start).Seconds()
max_its := len(problems) * cp.Iterations
fmt.Printf("[%v] ✅ Finish %s %6.0fs (%.0f its/s) • %d its (%1.f%%) • %d escaped, %d periodic\n",
TimestampMilli(), calc_id, t_total,
float64(total_its)/t_total, total_its, 100*float64(total_its)/float64(max_its),
num_escaped, num_periodic)
return
}
func TimestampMilli() string {
return time.Now().Format(time.StampMilli)
}
// CalculateParallel breaks the problem set into chunks and runs conncurrent Calculate routines.
func (cp *CalcParams) CalculateParallel() (histogram CalcResults) {
concurrency := cp.Concurrency
if cp.Concurrency == 0 {
concurrency = int(1.5 * float64(runtime.NumCPU()))
}
var problems []CalcPoint
if cp.Style == Attractor {
problems = cp.MakePlaneProblemSet()
} else {
problems = cp.MakeImageProblemSet()
}
if len(problems) < concurrency {
concurrency = len(problems)
}
chunk_size := len(problems) / concurrency
// Randomly distribute points to prevent calcuation hot spots.
rand.Shuffle(len(problems), func(a, b int) {
problems[a], problems[b] = problems[b], problems[a]
})
fmt.Printf("%v\n\n", cp)
fmt.Printf("Logical CPUs: %v (will use %v concurrent routines)\n", runtime.NumCPU(), concurrency)
fmt.Printf("Orbits to calculate: %d (~%d per routine)\n", len(problems), chunk_size)
// Calculate points.
result_ch := make(chan CalcResults)
for chunk_n := 0; chunk_n < concurrency; chunk_n++ {
chunk_start := chunk_n * chunk_size
chunk_end := chunk_start + chunk_size
// final chunk includes remainder of fractional division
if chunk_n+1 == concurrency {
chunk_end = len(problems)
}
p_chunk := problems[chunk_start:chunk_end]
fmt.Printf("[%v] 🚀 Launch %p | %d orbits\n",
time.Now().Format(time.StampMilli), p_chunk, len(p_chunk))
go func() {
result_ch <- cp.Calculate(p_chunk)
}()
}
// Collect results.
histogram = make(CalcResults)
chunks_received := 0
for r_chunk := range result_ch {
histogram.Merge(r_chunk)
chunks_received++
if chunks_received >= concurrency {
break
}
}
return
}
// ColorImage sets image colors based on the results from Calculate.
func (cp *CalcParams) ColorImage() {
histogram := cp.CalculateParallel()
histogram.PrintStats()
t_start := time.Now()
colors := cp.CF.F(histogram, cp.CFP)
for pt, rgba := range colors {
cp.Plane.SetXYColor(pt.X, pt.Y, rgba)
}
fmt.Printf("Image processing took %dms\n", time.Since(t_start).Milliseconds())
}