File: generate_constants.go

package info (click to toggle)
golang-gonum-v1-gonum 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,792 kB
  • sloc: asm: 6,252; fortran: 5,271; sh: 377; ruby: 211; makefile: 98
file content (333 lines) | stat: -rw-r--r-- 9,842 bytes parent folder | download
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
// Copyright ©2014 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build ignore
// +build ignore

package main

import (
	"bytes"
	"go/format"
	"log"
	"math"
	"os"
	"strings"
	"text/template"

	"gonum.org/v1/gonum/unit"
)

const (
	elementaryCharge = 1.602176634e-19
	fineStructure    = 7.2973525693e-3
	lightSpeed       = 2.99792458e8
	planck           = 6.62607015e-34
)

var constants = []Constant{
	{
		Name: "AtomicMass", Value: 1.66053906660e-27,
		Dimensions:  []Dimension{{massName, 1}},
		Comment:     "AtomicMass is the atomic mass constant (mᵤ), one twelfth of the mass of an unbound atom of carbon-12 at rest and in its ground state.",
		Uncertainty: 0.00000000050e-27,
	},
	{
		Name: "Avogadro", Value: 6.02214076e23,
		Dimensions: []Dimension{{moleName, -1}},
		Comment:    "Avogadro is the Avogadro constant (A), the number of constituent particles contained in one mole of a substance.",
	},
	{
		Name: "Boltzmann", Value: 1.380649e-23,
		Dimensions: []Dimension{{massName, 1}, {lengthName, 2}, {timeName, -2}, {temperatureName, -1}},
		Comment:    "Boltzmann is the Boltzmann constant (k), it relates the average relative kinetic energy of particles in a gas with the temperature of the gas.",
	},
	{
		Name: "ElectricConstant", Value: 1 / (4 * math.Pi * 1e-7 * lightSpeed * lightSpeed),
		Dimensions:  []Dimension{{currentName, 2}, {timeName, 4}, {massName, -1}, {lengthName, -3}},
		Comment:     "ElectricConstant is the electric constant (ε₀), the value of the absolute dielectric permittivity of classical vacuum.",
		Uncertainty: 0.0000000013e-12,
	},
	{
		Name: "ElementaryCharge", Value: elementaryCharge,
		Dimensions: []Dimension{{currentName, 1}, {timeName, 1}},
		Comment:    "ElementaryCharge, is the elementary charge constant (e), the magnitude of electric charge carried by a single proton or electron.",
	},
	{
		Name: "Faraday", Value: 96485.33212,
		Dimensions: []Dimension{{currentName, 1}, {timeName, 1}, {moleName, -1}},
		Comment:    "Faraday is the Faraday constant, the magnitude of electric charge per mole of electrons.",
	},
	{
		Name: "FineStructure", Value: fineStructure,
		Comment:     "FineStructure is the fine structure constant (α), it describes the strength of the electromagnetic interaction between elementary charged particles.",
		Uncertainty: 0.0000000011e-3,
	},
	{
		Name: "Gravitational", Value: 6.67430e-11,
		Dimensions:  []Dimension{{massName, -1}, {lengthName, 3}, {timeName, -2}},
		Comment:     "Gravitational is the universal gravitational constant (G), the proportionality constant connecting the gravitational force between two bodies.",
		Uncertainty: 0.00015e-11,
	},
	{
		Name: "LightSpeedInVacuum", Value: lightSpeed,
		Dimensions: []Dimension{{lengthName, 1}, {timeName, -1}},
		Comment:    "LightSpeedInVacuum is the c constant, the speed of light in a vacuum.",
	},
	{
		Name: "MagneticConstant", Value: 2 * fineStructure * planck / (elementaryCharge * elementaryCharge * lightSpeed),
		Dimensions:  []Dimension{{currentName, 2}, {timeName, 4}, {massName, -1}, {lengthName, -3}},
		Comment:     "MagneticConstant is the magnetic constant (μ₀), the magnetic permeability in a classical vacuum.",
		Uncertainty: 0.00000000019e-6,
	},
	{
		Name: "Planck", Value: planck,
		Dimensions: []Dimension{{massName, 1}, {lengthName, 2}, {timeName, -1}},
		Comment:    "Planck is the Planck constant (h), it relates the energy carried by a photon to its frequency.",
	},
	{
		Name: "StandardGravity", Value: 9.80665,
		Dimensions: []Dimension{{lengthName, 1}, {timeName, -2}},
		Comment:    "StandardGravity is the standard gravity constant (g₀), the nominal gravitational acceleration of an object in a vacuum near the surface of the Earth",
	},
}

const (
	angleName             = "AngleDim"
	currentName           = "CurrentDim"
	lengthName            = "LengthDim"
	luminousIntensityName = "LuminousIntensityDim"
	massName              = "MassDim"
	moleName              = "MoleDim"
	temperatureName       = "TemperatureDim"
	timeName              = "TimeDim"
)

var dimOf = map[string]unit.Dimension{
	"AngleDim":             unit.AngleDim,
	"CurrentDim":           unit.CurrentDim,
	"LengthDim":            unit.LengthDim,
	"LuminousIntensityDim": unit.LuminousIntensityDim,
	"MassDim":              unit.MassDim,
	"MoleDim":              unit.MoleDim,
	"TemperatureDim":       unit.TemperatureDim,
	"TimeDim":              unit.TimeDim,
}

type Constant struct {
	Name        string
	Value       float64
	Dimensions  []Dimension
	Comment     string
	Uncertainty float64
}

type Dimension struct {
	Name  string
	Power int
}

func (c Constant) IsDefined() bool {
	return definedEquivalentOf(unit.New(1, c.dimensions())) != ""
}

func (c Constant) Type() string {
	typ := definedEquivalentOf(unit.New(1, c.dimensions()))
	if typ == "" {
		return strings.ToLower(c.Name[:1]) + c.Name[1:] + "Units"
	}
	return typ
}

func (c Constant) Units() string {
	return c.dimensions().String()
}

func (c Constant) dimensions() unit.Dimensions {
	dims := make(unit.Dimensions)
	for _, d := range c.Dimensions {
		dims[dimOf[d.Name]] = d.Power
	}
	return dims
}

// Generate a file for each of the constants.
func main() {
	for _, c := range constants {
		generate(c)
		generateTest(c)
	}
}

const baseUnitTemplate = `// Code generated by "go generate gonum.org/v1/gonum/unit/constant”; DO NOT EDIT.

// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package constant

import "gonum.org/v1/gonum/unit"

// {{.Comment}}{{if .Dimensions}}
// {{$n := len .Dimensions}}The dimension{{if gt $n 1}}s{{end}} of {{.Name}} {{if eq $n 1}}is{{else}}are{{end}} {{.Units}}.{{end}} {{if not .Uncertainty}}The constant is exact.{{else}}The standard uncertainty of the constant is {{.Uncertainty}} {{.Units}}.{{end}}
const {{.Name}} = {{.Type}}({{.Value}})
`

var baseUnit = template.Must(template.New("base").Parse(baseUnitTemplate))

const methodTemplate = `// Code generated by "go generate gonum.org/v1/gonum/unit/constant”; DO NOT EDIT.

// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package constant

import (
	"fmt"

	"gonum.org/v1/gonum/unit"
)

// {{.Comment}}
// {{$n := len .Dimensions}}The dimension{{if gt $n 1}}s{{end}} of {{.Name}} {{if eq $n 1}}is{{else}}are{{end}} {{.Units}}. {{if not .Uncertainty}}The constant is exact.{{else}}The standard uncertainty of the constant is {{.Uncertainty}} {{.Units}}.{{end}}
const {{.Name}} = {{.Type}}({{.Value}})

type {{.Type}} float64

// Unit converts the {{.Type}} to a *unit.Unit
func (cnst {{.Type}}) Unit() *unit.Unit {
	return unit.New(float64(cnst), unit.Dimensions{
		{{range .Dimensions}} unit.{{.Name}}: {{.Power}},
		{{end}}
		})
}

func (cnst {{.Type}}) Format(fs fmt.State, c rune) {
	switch c {
	case 'v':
		if fs.Flag('#') {
			fmt.Fprintf(fs, "%T(%v)", cnst, float64(cnst))
			return
		}
		fallthrough
	case 'e', 'E', 'f', 'F', 'g', 'G':
		p, pOk := fs.Precision()
		w, wOk := fs.Width()
		switch {
		case pOk && wOk:
			fmt.Fprintf(fs, "%*.*"+string(c), w, p, cnst.Unit())
		case pOk:
			fmt.Fprintf(fs, "%.*"+string(c), p, cnst.Unit())
		case wOk:
			fmt.Fprintf(fs, "%*"+string(c), w, cnst.Unit())
		default:
			fmt.Fprintf(fs, "%"+string(c), cnst.Unit())
		}
	default:
		fmt.Fprintf(fs, "%%!"+string(c)+"(constant.{{.Type}}=%v {{.Units}})", float64(cnst))
	}
}
`

var methods = template.Must(template.New("methods").Parse(methodTemplate))

func generate(c Constant) {
	lowerName := strings.ToLower(c.Name)
	filename := lowerName + ".go"
	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	var buf bytes.Buffer

	if c.IsDefined() {
		err = baseUnit.Execute(&buf, c)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		err = methods.Execute(&buf, c)
		if err != nil {
			log.Fatal(err)
		}
	}

	b, err := format.Source(buf.Bytes())
	if err != nil {
		f.Write(buf.Bytes()) // This is here to debug bad format.
		log.Fatalf("error formatting %q: %s", c.Name, err)
	}

	f.Write(b)
}

const testTemplate = `// Code generated by "go generate gonum.org/v1/gonum/unit/constant”; DO NOT EDIT.

// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package constant

import (
	"fmt"
	"testing"
)

func Test{{.Name}}Format(t *testing.T) {
	t.Parallel()
	for _, test := range []struct{
		format string
		want   string
	}{
		{"%v", "{{.Value}} {{.Units}}"},
		{"%.1v", "{{printf "%.1v" .Value}} {{.Units}}"},
		{"%50.1v", "{{$s := printf "%.1v %s" .Value .Units}}{{printf "%50s" $s}}"},
		{"%50v", "{{$s := printf "%v %s" .Value .Units}}{{printf "%50s" $s}}"},
		{"%1v", "{{.Value}} {{.Units}}"},
		{"%#v", "constant.{{.Type}}({{.Value}})"},
		{"%s", "%!s(constant.{{.Type}}={{.Value}} {{.Units}})"},
	} {
		got := fmt.Sprintf(test.format, {{.Name}})
		if got != test.want {
			t.Errorf("Format %q: got: %q want: %q", test.format, got, test.want)
		}
	}
}
`

var tests = template.Must(template.New("test").Parse(testTemplate))

func generateTest(c Constant) {
	if c.IsDefined() {
		return
	}

	lowerName := strings.ToLower(c.Name)
	filename := lowerName + "_test.go"
	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	var buf bytes.Buffer

	err = tests.Execute(&buf, c)
	if err != nil {
		log.Fatal(err)
	}

	b, err := format.Source(buf.Bytes())
	if err != nil {
		f.Write(buf.Bytes()) // This is here to debug bad format.
		log.Fatalf("error formatting test for %q: %s", c.Name, err)
	}

	f.Write(b)
}