-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
104 lines (89 loc) · 1.98 KB
/
table.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
package engine
import (
"bufio"
"fmt"
"github.com/mumax/3/util"
"os"
)
var Table = *newTable("table") // output handle for tabular data (average magnetization etc.)
func init() {
DeclFunc("TableAdd", TableAdd, "Add quantity as a column to the data table.")
DeclFunc("TableSave", TableSave, "Save the data table right now (appends one line).")
DeclFunc("TableAutoSave", TableAutoSave, "Auto-save the data table ever period (s).")
Table.Add(&M)
}
type DataTable struct {
*bufio.Writer
info
outputs []TableData
autosave
}
func newTable(name string) *DataTable {
t := new(DataTable)
t.name = name
return t
}
func TableAdd(col TableData) {
Table.Add(col)
}
func TableSave() {
Table.Save()
}
func TableAutoSave(period float64) {
Table.autosave = autosave{period, Time, 0, nil}
}
func (t *DataTable) Add(output TableData) {
if t.inited() {
util.Fatal("data table add ", output.Name(), ": need to add quantity before table is output the first time")
}
t.outputs = append(t.outputs, output)
}
func (t *DataTable) Save() {
t.init()
fmt.Fprint(t, Time)
for _, o := range t.outputs {
vec := o.average()
for _, v := range vec {
fmt.Fprint(t, "\t", v)
}
}
fmt.Fprintln(t)
t.Flush()
t.count++
}
// open writer and write header
func (t *DataTable) init() {
if !t.inited() {
f, err := os.OpenFile(OD+t.name+".txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
util.FatalErr(err)
t.Writer = bufio.NewWriter(f)
// write header
fmt.Fprint(t, "# t (s)")
for _, o := range t.outputs {
if o.NComp() == 1 {
fmt.Fprint(t, "\t", o.Name(), " (", o.Unit(), ")")
} else {
for c := 0; c < o.NComp(); c++ {
fmt.Fprint(t, "\t", o.Name()+string('x'+c), " (", o.Unit(), ")")
}
}
}
fmt.Fprintln(t)
t.Flush()
}
}
func (t *DataTable) inited() bool {
return t.Writer != nil
}
func (t *DataTable) flush() {
if t.Writer != nil {
t.Flush()
}
}
// can be saved in table
type TableData interface {
average() []float64
Name() string
Unit() string
NComp() int
}