This repository has been archived by the owner on Dec 9, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
unittype.go
349 lines (321 loc) · 8.91 KB
/
unittype.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
// Copyright ©2013 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 unit
import (
"bytes"
"fmt"
"sort"
)
// Uniter is an interface representing a type that can be converted
// to a unit.
type Uniter interface {
Unit() *Unit
}
// Dimension is a type representing an SI base dimension or other
// orthogonal dimension. If a new dimension is desired for a
// domain-specific problem, NewDimension should be used. Integers
// should never be cast as type dimension
// // Good: Create a package constant with an init function
// var MyDimension unit.Dimension
// init(){
// MyDimension = NewDimension("my")
// }
// main(){
// var := MyDimension(28.2)
// }
type Dimension int
func (d Dimension) String() string {
switch {
case d == reserved:
return "reserved"
case d < Dimension(len(symbols)):
return symbols[d]
default:
panic("unit: illegal dimension")
}
}
const (
// SI Base Units
reserved Dimension = iota
CurrentDim
LengthDim
LuminousIntensityDim
MassDim
TemperatureDim
TimeDim
// Other common SI Dimensions
AngleDim // e.g. radians
)
var (
symbols = []string{
CurrentDim: "A",
LengthDim: "m",
LuminousIntensityDim: "cd",
MassDim: "kg",
TemperatureDim: "K",
TimeDim: "s",
AngleDim: "rad",
}
// for guaranteeing there aren't two identical symbols
dimensions = map[string]Dimension{
"A": CurrentDim,
"m": LengthDim,
"cd": LuminousIntensityDim,
"kg": MassDim,
"K": TemperatureDim,
"s": TimeDim,
"rad": AngleDim,
// Reserve common SI symbols
// base units
"mol": reserved,
// prefixes
"Y": reserved,
"Z": reserved,
"E": reserved,
"P": reserved,
"T": reserved,
"G": reserved,
"M": reserved,
"k": reserved,
"h": reserved,
"da": reserved,
"d": reserved,
"c": reserved,
"μ": reserved,
"n": reserved,
"p": reserved,
"f": reserved,
"a": reserved,
"z": reserved,
"y": reserved,
// SI Derived units with special symbols
"sr": reserved,
"F": reserved,
"C": reserved,
"S": reserved,
"H": reserved,
"V": reserved,
"Ω": reserved,
"J": reserved,
"N": reserved,
"Hz": reserved,
"lx": reserved,
"lm": reserved,
"Wb": reserved,
"W": reserved,
"Pa": reserved,
"Bq": reserved,
"Gy": reserved,
"Sv": reserved,
"kat": reserved,
// Units in use with SI
"ha": reserved,
"L": reserved,
"l": reserved,
// Units in Use Temporarily with SI
"bar": reserved,
"b": reserved,
"Ci": reserved,
"R": reserved,
"rd": reserved,
"rem": reserved,
}
)
// TODO: Should we actually reserve "common" SI unit symbols ("N", "J", etc.) so there isn't confusion
// TODO: If we have a fancier ParseUnit, maybe the 'reserved' symbols should be a different map
// map[string]string which says how they go?
// Dimensions represent the dimensionality of the unit in powers
// of that dimension. If a key is not present, the power of that
// dimension is zero. Dimensions is used in conjuction with New.
type Dimensions map[Dimension]int
func (d Dimensions) String() string {
// Map iterates randomly, but print should be in a fixed order. Can't use
// dimension number, because for user-defined dimension that number may
// not be fixed from run to run.
atoms := make(unitPrinters, 0, len(d))
for dimension, power := range d {
if power != 0 {
atoms = append(atoms, atom{dimension, power})
}
}
sort.Sort(atoms)
var b bytes.Buffer
for i, a := range atoms {
if i > 0 {
b.WriteByte(' ')
}
fmt.Fprintf(&b, "%s", a.Dimension)
if a.pow != 1 {
fmt.Fprintf(&b, "^%d", a.pow)
}
}
return b.String()
}
type atom struct {
Dimension
pow int
}
type unitPrinters []atom
func (u unitPrinters) Len() int {
return len(u)
}
func (u unitPrinters) Less(i, j int) bool {
return (u[i].pow > 0 && u[j].pow < 0) || u[i].String() < u[j].String()
}
func (u unitPrinters) Swap(i, j int) {
u[i], u[j] = u[j], u[i]
}
// NewDimension returns a new dimension variable which will have a
// unique representation across packages to prevent accidental overlap.
// The input string represents a symbol name which will be used for printing
// Unit types. This symbol may not overlap with any of the SI base units
// or other symbols of common use in SI ("kg", "J", "μ", etc.). A list of
// such symbols can be found at http://lamar.colostate.edu/~hillger/basic.htm or
// by consulting the package source. Furthermore, the provided symbol is also
// forbidden from overlapping with other packages calling NewDimension. NewDimension
// is expecting to be used only during initialization, and as such it will panic
// if the symbol matching an existing symbol
// NewDimension should only be called for unit types that are actually orthogonal
// to the base dimensions defined in this package. Please see the package-level
// documentation for further explanation. Calls to NewDimension are not thread safe.
func NewDimension(symbol string) Dimension {
_, ok := dimensions[symbol]
if ok {
panic("unit: dimension string \"" + symbol + "\" already used")
}
symbols = append(symbols, symbol)
d := Dimension(len(symbols))
dimensions[symbol] = d
return d
}
// Unit is a type a value with generic SI units. Most useful for
// translating between dimensions, for example, by multiplying
// an acceleration with a mass to get a force. Please see the
// package documentation for further explanation.
type Unit struct {
dimensions Dimensions // Map for custom dimensions
formatted string
value float64
}
// New creates a new variable of type Unit which has the value
// specified by value and the dimensions specified by the
// base units struct. The value is always in SI Units.
//
// Example: To create an acceleration of 3 m/s^2, one could do
// myvar := CreateUnit(3.0, &Dimensions{unit.LengthDim: 1, unit.TimeDim: -2})
func New(value float64, d Dimensions) *Unit {
u := &Unit{
dimensions: make(map[Dimension]int),
value: value,
}
for key, val := range d {
if val != 0 {
u.dimensions[key] = val
}
}
return u
}
// DimensionsMatch checks if the dimensions of two Uniters are the same.
func DimensionsMatch(a, b Uniter) bool {
aUnit := a.Unit()
bUnit := b.Unit()
if len(aUnit.dimensions) != len(bUnit.dimensions) {
return false
}
for key, val := range aUnit.dimensions {
if bUnit.dimensions[key] != val {
return false
}
}
return true
}
// Add adds the function argument to the reciever. Panics if the units of
// the receiver and the argument don't match.
func (u *Unit) Add(uniter Uniter) *Unit {
a := uniter.Unit()
if !DimensionsMatch(u, a) {
panic("unit: mismatched dimensions in addition")
}
u.value += a.value
return u
}
// Unit implements the Uniter interface
func (u *Unit) Unit() *Unit {
return u
}
// Mul multiply the receiver by the input changing the dimensions
// of the receiver as appropriate. The input is not changed.
func (u *Unit) Mul(uniter Uniter) *Unit {
a := uniter.Unit()
for key, val := range a.dimensions {
if d := u.dimensions[key]; d == -val {
delete(u.dimensions, key)
} else {
u.dimensions[key] = d + val
}
}
u.formatted = ""
u.value *= a.value
return u
}
// Div divides the receiver by the argument changing the
// dimensions of the receiver as appropriate.
func (u *Unit) Div(uniter Uniter) *Unit {
a := uniter.Unit()
u.value /= a.value
for key, val := range a.dimensions {
if d := u.dimensions[key]; d == val {
delete(u.dimensions, key)
} else {
u.dimensions[key] = d - val
}
}
u.formatted = ""
return u
}
// Value return the raw value of the unit as a float64. Use of this
// method is, in general, not recommended, though it can be useful
// for printing. Instead, the From type of a specific dimension
// should be used to guarantee dimension consistency.
func (u *Unit) Value() float64 {
return u.value
}
// Format makes Unit satisfy the fmt.Formatter interface. The unit is formatted
// with dimensions appended. If the power if the dimension is not zero or one,
// symbol^power is appended, if the power is one, just the symbol is appended
// and if the power is zero, nothing is appended. Dimensions are appended
// in order by symbol name with positive powers ahead of negative powers.
func (u *Unit) Format(fs fmt.State, c rune) {
if u == nil {
fmt.Fprint(fs, "<nil>")
}
switch c {
case 'v':
if fs.Flag('#') {
fmt.Fprintf(fs, "&%#v", *u)
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, u.value)
case pOk:
fmt.Fprintf(fs, "%.*"+string(c), p, u.value)
case wOk:
fmt.Fprintf(fs, "%*"+string(c), w, u.value)
default:
fmt.Fprintf(fs, "%"+string(c), u.value)
}
default:
fmt.Fprintf(fs, "%%!%c(*Unit=%g)", c, u)
return
}
if u.formatted == "" && len(u.dimensions) > 0 {
u.formatted = u.dimensions.String()
}
fmt.Fprintf(fs, " %s", u.formatted)
}