-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.go
518 lines (469 loc) · 13.8 KB
/
gui.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package engine
import (
"fmt"
"github.com/barnex/cuda5/cu"
"github.com/barnex/gui"
"github.com/mumax/3/cuda"
"github.com/mumax/3/util"
"log"
"math/rand"
"net/http"
"path"
"reflect"
"sync"
"time"
)
// global GUI state stores what is currently shown in the web page.
var gui_ = guistate{Quants: make(map[string]Quantity), Params: make(map[string]Param)}
type guistate struct {
*gui.Page // GUI elements (buttons...)
Quants map[string]Quantity // displayable quantities by name
Params map[string]Param // displayable parameters by name
render // renders displayed quantity
mutex sync.Mutex // protects eventCacheBreaker and keepalive
_eventCacheBreaker int // changed on any event to make sure display is updated
keepalive time.Time
}
// Returns the time when updateKeepAlive was called.
func (g *guistate) KeepAlive() time.Time {
g.mutex.Lock()
defer g.mutex.Unlock()
return g.keepalive
}
// Called on each http request to signal browser is still open.
func (g *guistate) UpdateKeepAlive() {
g.mutex.Lock()
defer g.mutex.Unlock()
g.keepalive = time.Now()
}
// displayable quantity in GUI Parameters section
type Param interface {
NComp() int
Name() string
Unit() string
getRegion(int) []float64
IsUniform() bool
}
func GUIAdd(name string, value interface{}) {
gui_.Add(name, value)
}
// Internal:add a quantity to the GUI, will be visible in web interface.
// Automatically called by Decl*(), still before PrepareServer()
func (g *guistate) Add(name string, value interface{}) {
if v, ok := value.(Param); ok {
g.Params[name] = v
}
if v, ok := value.(Quantity); ok {
g.Quants[name] = v
}
}
// Once Params/Quants have been declared and added,
// initialize the GUI Page (pre-renders template) and register http handlers
func (g *guistate) PrepareServer() {
g.Page = gui.NewPage(templText, g)
util.SetProgress(gui_.Prog)
g.OnAnyEvent(func() {
g.incCacheBreaker()
})
http.Handle("/", g)
http.HandleFunc("/render/", g.ServeRender)
http.HandleFunc("/plot/", servePlot)
g.prepareConsole()
g.prepareMesh()
g.prepareGeom()
g.prepareM()
g.prepareSolver()
g.prepareDisplay()
g.prepareParam()
g.prepareOnUpdate()
}
// see prepareServer
func (g *guistate) prepareConsole() {
g.OnEvent("cli", func() {
cmd := g.StringValue("cli")
Inject <- func() { g.EvalGUI(cmd) }
g.Set("cli", "")
})
}
// see prepareServer
func (g *guistate) prepareMesh() {
g.Disable("setmesh", true) // button only enabled if pressing makes sense
const MESHWARN = "⚠ Click to update mesh (may take some time)"
warnmesh := func() {
g.Disable("setmesh", false)
g.Set("setmeshwarn", MESHWARN)
}
g.OnEvent("nx", func() { Inject <- func() { lazy_gridsize[X] = g.IntValue("nx"); warnmesh() } })
g.OnEvent("ny", func() { Inject <- func() { lazy_gridsize[Y] = g.IntValue("ny"); warnmesh() } })
g.OnEvent("nz", func() { Inject <- func() { lazy_gridsize[Z] = g.IntValue("nz"); warnmesh() } })
g.OnEvent("cx", func() { Inject <- func() { lazy_cellsize[X] = g.FloatValue("cx"); warnmesh() } })
g.OnEvent("cy", func() { Inject <- func() { lazy_cellsize[Y] = g.FloatValue("cy"); warnmesh() } })
g.OnEvent("cz", func() { Inject <- func() { lazy_cellsize[Z] = g.FloatValue("cz"); warnmesh() } })
g.OnEvent("px", func() { Inject <- func() { lazy_pbc[X] = g.IntValue("px"); warnmesh() } })
g.OnEvent("py", func() { Inject <- func() { lazy_pbc[Y] = g.IntValue("py"); warnmesh() } })
g.OnEvent("pz", func() { Inject <- func() { lazy_pbc[Z] = g.IntValue("pz"); warnmesh() } })
g.OnEvent("setmesh", func() {
g.Disable("setmesh", true)
Inject <- (func() {
g.EvalGUI(fmt.Sprintf("SetMesh(%v, %v, %v, %v, %v, %v, %v, %v, %v)",
g.Value("nx"), g.Value("ny"), g.Value("nz"),
g.Value("cx"), g.Value("cy"), g.Value("cz"),
g.Value("px"), g.Value("py"), g.Value("pz")))
})
g.Set("setmeshwarn", "mesh up to date")
})
}
// see prepareServer
func (g *guistate) prepareGeom() {
g.OnEvent("geomselect", func() {
ident := g.StringValue("geomselect")
t := World.Resolve(ident).Type()
// set sensible args: world size
args := "("
for i := 0; i < t.NumIn(); i++ {
val := 0.0
if i < 3 {
val = Mesh().WorldSize()[i]
}
if i > 0 {
args += ", "
}
args += fmt.Sprint(val)
}
args += ")"
// overwrite args for special cases
switch {
case ident == "Cell":
args = "(0, 0, 0)"
case ident == "XRange" || ident == "YRange" || ident == "ZRange":
args = "(0, inf)"
case ident == "Layers":
args = "(0, 1)"
case ident == "ImageShape":
args = `("filename.png")`
}
g.Set("geomargs", args)
g.Set("geomdoc", g.Doc(ident))
})
g.OnEvent("setgeom", func() {
Inject <- (func() {
g.EvalGUI(fmt.Sprint("SetGeom(", g.StringValue("geomselect"), g.StringValue("geomargs"), ")"))
})
})
}
// see prepareServer
func (g *guistate) prepareM() {
g.OnEvent("mselect", func() {
ident := g.StringValue("mselect")
t := World.Resolve(ident).Type()
args := "("
for i := 0; i < t.NumIn(); i++ {
if i > 0 {
args += ", "
}
args += "1"
}
args += ")"
// overwrite args for special cases
switch ident {
case "VortexWall":
args = "(1, -1, 1, 1)"
}
g.Set("margs", args)
g.Set("mdoc", g.Doc(ident))
})
g.OnEvent("setm", func() {
Inject <- (func() {
g.EvalGUI(fmt.Sprint("m = ", g.StringValue("mselect"), g.StringValue("margs")))
})
})
}
var (
solvertypes = map[string]string{"euler": "1", "heun": "2"}
solvernames = map[int]string{1: "euler", 2: "heun"}
)
// see prepareServer
func (g *guistate) prepareSolver() {
g.OnEvent("run", g.cmd("Run", "runtime"))
g.OnEvent("steps", g.cmd("Steps", "runsteps"))
g.OnEvent("break", func() { Inject <- func() { pause = true } })
g.OnEvent("mindt", func() { Inject <- func() { g.EvalGUI("MinDt=" + g.StringValue("mindt")) } })
g.OnEvent("maxdt", func() { Inject <- func() { g.EvalGUI("MaxDt=" + g.StringValue("maxdt")) } })
g.OnEvent("fixdt", func() { Inject <- func() { g.EvalGUI("FixDt=" + g.StringValue("fixdt")) } })
g.OnEvent("maxerr", func() { Inject <- func() { g.EvalGUI("MaxErr=" + g.StringValue("maxerr")) } })
g.OnEvent("solvertype", func() {
Inject <- func() {
typ := solvertypes[g.StringValue("solvertype")]
g.EvalGUI("SetSolver(" + typ + ")")
if Solver.FixDt == 0 { // euler must have fixed time step
Solver.FixDt = 1e-15
}
}
})
}
// see prepareServer
func (g *guistate) prepareParam() {
for _, p := range g.Params {
p := p
n := p.Name()
g.OnEvent(n, func() {
cmd := p.Name()
r := g.Value("region")
if r == -1 {
cmd += " = "
} else {
cmd += fmt.Sprint(".SetRegion(", r, ", ")
}
if p.NComp() == 3 {
cmd += "vector " // space needed
}
cmd += g.StringValue(p.Name())
if r != -1 {
cmd += ")"
}
Inject <- func() {
g.EvalGUI(cmd)
}
})
}
g.OnEvent("Temp", func() {
Inject <- func() {
if Solver.FixDt == 0 {
g.EvalGUI("FixDt = 10e-15") // finite temperature requires fixed time step
}
g.EvalGUI("Temp = " + g.StringValue("Temp"))
}
})
}
// see prepareServer
func (g *guistate) prepareDisplay() {
g.OnEvent("renderQuant", func() {
g.render.mutex.Lock()
defer g.render.mutex.Unlock()
name := g.StringValue("renderQuant")
q := g.Quants[name]
if q == nil {
LogOutput("display: unknown quantity:", name)
return
}
g.render.quant = q
g.Set("renderDoc", g.Doc(g.StringValue("renderQuant")))
})
g.OnEvent("renderComp", func() {
g.render.mutex.Lock()
defer g.render.mutex.Unlock()
g.render.comp = g.StringValue("renderComp")
// TODO: set to "" if q.Ncomp < 3
})
g.OnEvent("renderLayer", func() {
g.render.mutex.Lock()
defer g.render.mutex.Unlock()
g.render.layer = g.IntValue("renderLayer")
g.Set("renderLayerLabel", fmt.Sprint(g.render.layer, "/", Mesh().Size()[Z]))
})
g.OnEvent("renderScale", func() {
g.render.mutex.Lock()
defer g.render.mutex.Unlock()
g.render.scale = maxScale - g.IntValue("renderScale")
g.Set("renderScaleLabel", fmt.Sprint("1/", g.render.scale))
})
}
// see prepareServer
func (g *guistate) prepareOnUpdate() {
g.OnUpdate(func() {
g.UpdateKeepAlive() // keep track of when browser was last seen alive
if GetBusy() { // busy, e.g., calculating kernel, run loop will not accept commands.
g.disableControls(true)
return
} else {
g.disableControls(false) // make sure everything is enabled
//g.Prog(0, 100, "Running") // reset progress bar in case we forgot
}
Inject <- (func() { // sends to run loop to be executed in between time steps
g.Set("console", hist)
// mesh
g.Set("nx", lazy_gridsize[X])
g.Set("ny", lazy_gridsize[Y])
g.Set("nz", lazy_gridsize[Z])
g.Set("cx", lazy_cellsize[X])
g.Set("cy", lazy_cellsize[Y])
g.Set("cz", lazy_cellsize[Z])
g.Set("px", lazy_pbc[X])
g.Set("py", lazy_pbc[Y])
g.Set("pz", lazy_pbc[Z])
g.Set("wx", printf(lazy_cellsize[X]*float64(lazy_gridsize[X])*1e9))
g.Set("wy", printf(lazy_cellsize[Y]*float64(lazy_gridsize[Y])*1e9))
g.Set("wz", printf(lazy_cellsize[Z]*float64(lazy_gridsize[Z])*1e9))
// solver
g.Set("nsteps", Solver.NSteps)
g.Set("time", fmt.Sprintf("%6e", Time))
g.Set("dt", fmt.Sprintf("%4e", Solver.Dt_si))
g.Set("lasterr", fmt.Sprintf("%3e", Solver.LastErr))
g.Set("maxerr", Solver.MaxErr)
g.Set("mindt", Solver.MinDt)
g.Set("maxdt", Solver.MaxDt)
g.Set("fixdt", Solver.FixDt)
g.Set("solvertype", solvernames[solvertype])
if pause {
g.Set("busy", "Paused")
} else {
g.Set("busy", "Running")
// Don't re-evaluate all the time if not running
g.Set("maxtorque", fmt.Sprintf("%6e T", MaxTorque.Get()))
}
// display
quant := g.StringValue("renderQuant")
comp := g.StringValue("renderComp")
cachebreaker := "?" + g.StringValue("nsteps") + "_" + fmt.Sprint(g.cacheBreaker())
g.Attr("renderLayer", "max", Mesh().Size()[Z]-1)
g.Set("display", "/render/"+quant+"/"+comp+cachebreaker)
// plot
gui_.Set("plot", "/plot/?"+cachebreaker)
// parameters
for _, p := range g.Params {
n := p.Name()
r := g.IntValue("region")
if r == -1 && !p.IsUniform() {
g.Set(n, "")
} else {
if r == -1 {
r = 0 // uniform, so pick one
}
v := p.getRegion(r)
if p.NComp() == 1 {
g.Set(n, float32(v[0]))
} else {
g.Set(n, fmt.Sprintf("(%v, %v, %v)", float32(v[X]), float32(v[Y]), float32(v[Z])))
}
}
}
// gpu
memfree, _ := cu.MemGetInfo()
memfree /= (1024 * 1024)
g.Set("memfree", memfree)
})
})
}
// Returns documentation string for quantity name. E.g.:
// "m" -> "Reduced magnetization"
func (g *guistate) Doc(quant string) string {
doc, ok := World.Doc[quant]
if !ok {
log.Println("no doc for", quant)
}
return doc
}
// Returns unit for quantity name. E.g.:
// "Msat" -> "A/m"
func (g *guistate) UnitOf(quant string) string {
p := g.Params[quant]
if p != nil {
return p.Unit()
} else {
return ""
}
}
// returns func that injects func that executes cmd(args),
// with args ids for GUI element values.
func (g *guistate) cmd(cmd string, args ...string) func() {
return func() {
Inject <- func() {
code := cmd + "("
if len(args) > 0 {
code += g.StringValue(args[0])
}
for i := 1; i < len(args); i++ {
code += ", " + g.StringValue(args[i])
}
code += ")"
g.EvalGUI(code)
}
}
}
// renders page title for PrepareServer
func (g *guistate) Title() string { return util.NoExt(path.Base(OD)) }
func (g *guistate) Version() string { return UNAME }
func (g *guistate) GPUInfo() string { return cuda.GPUInfo }
func (g *guistate) incCacheBreaker() {
g.mutex.Lock()
defer g.mutex.Unlock()
g._eventCacheBreaker++
}
func (g *guistate) cacheBreaker() int {
g.mutex.Lock()
defer g.mutex.Unlock()
return g._eventCacheBreaker
}
func (g *guistate) QuantNames() []string {
names := make([]string, 0, len(g.Quants))
for k, _ := range g.Quants {
names = append(names, k)
}
sortNoCase(names)
return names
}
// List all available shapes
func (g *guistate) Shapes() []string { return g.apifilter("Shape") }
func (g *guistate) Configs() []string { return g.apifilter("Config") }
// List all api functions that return outputtype (Shape, Config, ...)
func (g *guistate) apifilter(outputtype string) []string {
var match []string
for k, _ := range World.Doc {
v := World.Resolve(k)
t := v.Type()
if t.Kind() == reflect.Func && t.NumOut() == 1 && t.Out(0).Name() == outputtype {
match = append(match, k)
}
}
sortNoCase(match)
return match
}
func (g *guistate) Parameters() []string {
var params []string
for _, v := range g.Params {
params = append(params, v.Name())
}
sortNoCase(params)
return params
}
// renders a <div> that toggles visibility on click for PrepareServer
func (g *guistate) Div(heading string) string {
id := fmt.Sprint("div_", rand.Int())
return fmt.Sprintf(`<span title="Click to show/hide" style="cursor:pointer; font-size:1.2em; font-weight:bold; color:gray" onclick="toggle('%v')">▾ %v</span> <br/> <div id="%v">`, id, heading, id)
}
// Start web gui on given port, blocks.
func Serve(port string) {
gui_.PrepareServer()
util.LogErr(http.ListenAndServe(port, nil))
}
// Prog advances the GUI progress bar to fraction a/total and displays message.
func (g *guistate) Prog(a, total int, msg string) {
g.Set("progress", (a*100)/total)
g.Set("busy", msg)
}
func (g *guistate) disableControls(busy bool) {
g.Disable("cli", busy)
g.Disable("run", busy)
g.Disable("steps", busy)
g.Disable("break", busy)
}
// Eval code + update keepalive in case the code runs long
func (g *guistate) EvalGUI(code string) {
Eval(code)
g.UpdateKeepAlive()
}
func Eval(code string) {
tree, err := World.Compile(code)
if err == nil {
LogInput(rmln(tree.Format()))
tree.Eval()
} else {
LogOutput(code + "\n" + err.Error())
}
}
//
//// round duration to 1s accuracy
//func roundt(t time.Duration) time.Duration {
// return t - t%1e9
//}
//