-
Notifications
You must be signed in to change notification settings - Fork 0
/
unit.go
342 lines (302 loc) · 7.6 KB
/
unit.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
package calcu
import (
"embed"
"encoding/csv"
"fmt"
"io"
"sort"
"github.com/shopspring/decimal"
)
type UnitManager interface {
// Peek check if start of s is a unit
// if it's a unit, return the unit len
Peek(s string) (int, bool)
// IsUnit check if the given s is a unit
IsUnit(s string) bool
GetByName(name string) (Unit, bool)
ListMetaUnitsByDims(dim ...Dimension) ([]*MetaUnit, error)
}
type Dimension int
const (
DimInvalid Dimension = iota
DimEnergy
DimMass
DimVolume
DimTime
DimLength
DimPopulation
)
func DimensionFromString(s string) Dimension {
d := DimInvalid
switch s {
case "Energy":
d = DimEnergy
case "Mass":
d = DimMass
case "Volume":
d = DimVolume
case "Time":
d = DimTime
case "Length":
d = DimLength
case "Population":
d = DimPopulation
}
return d
}
type Unit interface {
Name() string
Label() string
Dimension() Dimension
IsMeta() bool
SiName() string
SiFactors() (decimal.Decimal, decimal.Decimal)
}
type MetaUnit struct {
name string
label string
dimension Dimension
si string
siFactor decimal.Decimal
siOffset decimal.Decimal
}
func (u *MetaUnit) Name() string {
return u.name
}
func (u *MetaUnit) Label() string {
return u.label
}
func (u *MetaUnit) Dimension() Dimension {
return u.dimension
}
func (u *MetaUnit) IsMeta() bool {
return true
}
func (u *MetaUnit) SiName() string {
return u.si
}
func (u *MetaUnit) SiFactors() (decimal.Decimal, decimal.Decimal) {
return u.siFactor, u.siOffset
}
// CompoundUnit represent as Numerator/Denominator
// Numerator and Denominator should have different
// dimensions, for example: j/kg, Gg/Tj
type CompoundUnit struct {
Numerator *MetaUnit
Denominator *MetaUnit
SiFactor decimal.Decimal
}
func newCompoundUnit(num, den *MetaUnit) *CompoundUnit {
// num as Numerator, den as Denominator
// e.g: energy unit: Tj to J(SI) is 1,000,000,000,000
// mass unit: Gg to kg(SI) is 1,000,000, then SI of
// Tj/Gg is 1,000,000,000,000/1,000,000 i.e, 1,000,000
numFactor := num.siFactor
denFactor := den.siFactor
return &CompoundUnit{
Numerator: num,
Denominator: den,
SiFactor: numFactor.Div(denFactor),
}
}
func (u *CompoundUnit) Name() string {
return fmt.Sprintf("%s/%s", u.Numerator.name, u.Denominator.name)
}
func (u *CompoundUnit) Label() string {
return u.Name()
}
func (u *CompoundUnit) Dimension() Dimension {
return DimInvalid
}
func (u *CompoundUnit) IsMeta() bool {
return false
}
func (u *CompoundUnit) SiName() string {
if u.isNumDenSameDim() {
// if num & den belongs to same dimension try to simplify it
// e.g. 1kg/kg = 1
return ""
}
return fmt.Sprintf("%s/%s", u.Numerator.si, u.Denominator.si)
}
func (u *CompoundUnit) SiFactors() (decimal.Decimal, decimal.Decimal) {
return u.SiFactor, decimal.Zero
}
func (u *CompoundUnit) isNumDenSameDim() bool {
return u.Numerator.Dimension() == u.Denominator.Dimension()
}
func (u *CompoundUnit) IsMulCancelable(other *CompoundUnit) bool {
if u.isNumDenSameDim() && other.isNumDenSameDim() {
// if num & den are same dimension
// consider it as non-cancelable,
// e.g., 1kg/kg * 1kg/kg should result 1kg/kg(not 1kg^2/kg^2 in strict math)
return false
}
a := u.Numerator.Dimension() == other.Denominator.Dimension()
b := u.Denominator.Dimension() == other.Numerator.Dimension()
return a && b
}
func (u *CompoundUnit) IsDivCancelable(other *CompoundUnit) bool {
a := u.Numerator.Dimension() == other.Numerator.Dimension()
b := u.Denominator.Dimension() == other.Denominator.Dimension()
return a && b
}
func MaybeAmbiguousUnitName(name string) (string, bool) {
// if the first char of unit
// is a digit, we use brackets
// to remove ambiguity.
c := name[0]
if c >= 49 && c <= 57 {
return "(" + name + ")", true
}
return name, false
}
//go:embed unit.csv
var unitAsset embed.FS
type staticum struct {
m map[string]Unit
dimMUnits map[Dimension][]*MetaUnit
ulens []int
names []string
}
func newStaticUintManager() UnitManager {
m := make(map[string]Unit)
dimMUnits := make(map[Dimension][]*MetaUnit)
var names []string
f, _ := unitAsset.Open("unit.csv")
rd := csv.NewReader(f)
rowid := 0
for ; ; rowid++ {
record, err := rd.Read()
if err == io.EOF {
break
}
if rowid == 0 {
continue // skip header row
}
dimension := DimensionFromString(record[2])
siFactor, _ := decimal.NewFromString(record[4])
siOffset, _ := decimal.NewFromString(record[5])
u := MetaUnit{
name: record[0],
label: record[1],
dimension: dimension,
si: record[3],
siFactor: siFactor,
siOffset: siOffset,
}
m[u.name] = &u
dimMUnits[u.dimension] = append(dimMUnits[u.dimension], &u)
names = append(names, u.name)
if s, ok := MaybeAmbiguousUnitName(u.name); ok {
names = append(names, s)
}
}
// permutations for dimensions to build compound units
dims := []Dimension{DimEnergy, DimMass, DimVolume, DimTime, DimLength, DimPopulation}
var arr []Dimension
var permutations [][]Dimension
// we only need permutation with length of 2
// assuming the first is num, and the second is den
permute(arr, &permutations, dims, 2)
// generate all possible compound units
for _, p := range permutations {
num, den := p[0], p[1]
nums := dimMUnits[num]
dens := dimMUnits[den]
for i := 0; i < len(nums); i++ {
for j := 0; j < len(dens); j++ {
cu := newCompoundUnit(nums[i], dens[j])
names = append(names, cu.Name())
if s, ok := MaybeAmbiguousUnitName(cu.Name()); ok {
names = append(names, s)
}
m[cu.Name()] = cu
}
}
}
// order names by length for the peek operation
sort.Slice(names, func(i, j int) bool {
return len(names[i]) > len(names[j])
})
ulens := make([]int, len(names))
for i, name := range names {
ulens[i] = len(name)
}
return &staticum{names: names, ulens: ulens, m: m, dimMUnits: dimMUnits}
}
func permute(arr []Dimension, ans *[][]Dimension, dims []Dimension, depth int) {
if len(arr) == depth {
dst := make([]Dimension, len(arr))
copy(dst, arr)
*ans = append(*ans, dst)
return
}
for _, dim := range dims {
arr = append(arr, dim)
permute(arr, ans, dims, depth)
arr = arr[:len(arr)-1]
}
}
func (su *staticum) dimension(s string) (Dimension, bool) {
u, ok := su.m[s]
if !ok {
return DimInvalid, false
}
mu, ok := u.(*MetaUnit)
if ok {
return mu.dimension, true
}
return DimInvalid, false
}
func (su *staticum) Peek(s string) (int, bool) {
for i, name := range su.names {
n := su.ulens[i]
if len(s) < n {
continue
}
a, b := s[:n], ""
if len(s) > n {
b = s[n:]
}
// consider the following char to
// avoid mistake, i.e., the unit
// token should only appear before
// a separator char or end of line.
// not in front of a char. for example,
// consider unit Meter(m), without
// check the following char, we might
// treat the `m` in word `me` as a unit
// or the `m` in `m = 1` will be treated
// as a unit as well.
if a == name && startWithSeparator(b) {
return n, true
}
}
return 0, false
}
func (su *staticum) IsUnit(s string) bool {
_, ok := su.m[s]
return ok
}
func (su *staticum) GetByName(name string) (Unit, bool) {
u, ok := su.m[name]
return u, ok
}
func (su *staticum) ListMetaUnitsByDims(dims ...Dimension) ([]*MetaUnit, error) {
var ans []*MetaUnit
for _, dim := range dims {
ans = append(ans, su.dimMUnits[dim]...)
}
sort.SliceStable(ans, func(i, j int) bool {
return ans[i].label < ans[j].label
})
return ans, nil
}
// StdUm a builtin static unit manager
// it should be used as read only purpose
// otherwise, we might need consider make
// it thread safe. one can replace it with
// other implementation globally with an
// atomic store.
var StdUm = newStaticUintManager()