/
util.go
66 lines (59 loc) · 1.77 KB
/
util.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
package engine
import (
"fmt"
"github.com/mumax/3/cuda"
"github.com/mumax/3/data"
"github.com/mumax/3/mag"
"github.com/mumax/3/util"
"log"
"math"
"os"
)
func init() {
DeclFunc("expect", Expect, "Used for automated tests: checks if a value is close enough to the expected value")
DeclFunc("fprintln", Fprintln, "Print to file")
DeclFunc("sign", sign, "Signum function")
DeclPure("vector", Vector, "Constructs a vector with given components")
DeclConst("mu0", mag.Mu0, "Permittivity of vaccum (Tm/A)")
//DeclFunc("LoadFile", LoadFile, "Read .dump file and return contents as array.")
}
// Constructs a vector
func Vector(x, y, z float64) [3]float64 {
return [3]float64{x, y, z}
}
// Test if have lies within want +/- maxError,
// and print suited message.
func Expect(msg string, have, want, maxError float64) {
if math.IsNaN(have) || math.IsNaN(want) || math.Abs(have-want) > maxError {
log.Fatal(msg, ":", " have: ", have, " want: ", want, "±", maxError)
} else {
log.Println(msg, ":", have, "OK")
}
// note: we also check "want" for NaN in case "have" and "want" are switched.
}
// Append msg to file. Used to write aggregated output of many simulations in one file.
func Fprintln(filename string, msg ...interface{}) {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
util.FatalErr(err)
defer f.Close()
_, err = fmt.Fprintln(f, msg...)
util.FatalErr(err)
}
// Read a magnetization state from .dump file.
func LoadFile(fname string) *data.Slice {
s, _ := data.MustReadFile(fname)
return s
}
// Download a quantity to host,
// or just return its data when already on host.
func Download(q Getter) *data.Slice {
buf, recycle := q.Get()
if recycle {
defer cuda.Recycle(buf)
}
if buf.CPUAccess() {
return buf
} else {
return buf.HostCopy()
}
}