-
Notifications
You must be signed in to change notification settings - Fork 0
/
quantiphy_eval.py
361 lines (289 loc) · 9.56 KB
/
quantiphy_eval.py
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
350
351
352
353
354
355
356
357
358
359
360
361
# QuantiPhy Eval — Evaluate expressions that contains physical quantities
# encoding: utf8
# Description {{{1
"""
*QuantiPhy_Eval* is a companion library to *QuantiPhy* that allows strings that
contain expressions to be evaluated. The expressions may contain physical
quantities.
"""
# MIT License {{{1
# Copyright (C) 2020-2021 Kenneth S. Kundert
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Imports {{{1
from inform import display, Error, full_stop, get_culprit
from quantiphy import Quantity
import operator
from sly import Lexer, Parser
# Globals {{{1
VARIABLES = {}
FUNCTIONS = {}
QUANTITY = Quantity
__version__ = '0.4.0'
__released__ = '2021-01-27'
__all__ = ['evaluate', 'initialize', 'rm_commas', 'Error']
# QELexer {{{1
class QELexer(Lexer):
tokens = (
NAME,
POW,
SIMPLE_NUMBER,
NUMBER_WITH_EXPONENT,
CURRENCY_WITH_SCALE_FACTOR,
CURRENCY_WITH_EXPONENT,
SIMPLE_CURRENCY,
UNITS,
)
literals = "=+-*/(),"
ignore = " \t"
POW = r'\*\*'
# numbers
_SCALE_FACTORS = 'kMGTPEZYmµμunpfazy'
_UNIT_SYMBOLS = '°ÅΩƱΩ℧'
_CURRENCY_SYMBOLS = '$€¥£₩₺₽₹ɃΞȄ'
_required_digits = r'([0-9][0-9_]*[0-9]|[0-9]+)' # allow interior underscores
_optional_digits = r'([0-9][0-9_]*[0-9]|[0-9]*)'
_mantissa = r'(({od}\.?{rd})|({rd}\.?{od}))'.format(
rd=_required_digits, od=_optional_digits
) # leading or trailing digits are optional, but not both
_exponent = '[eE][-+]?[0-9]+'
_scale_factor = f'[{_SCALE_FACTORS}]'
_units = f'[ ]?[a-zA-Z{_UNIT_SYMBOLS}]*' # examples: Ohms, Ω
_currency = f'[{_CURRENCY_SYMBOLS}]'
NUMBER_WITH_EXPONENT = f'{_mantissa}{_exponent}{_units}'
SIMPLE_NUMBER = f'{_mantissa}{_units}'
CURRENCY_WITH_EXPONENT = f'{_currency}{_mantissa}{_exponent}'
CURRENCY_WITH_SCALE_FACTOR = f'{_currency}{_mantissa}{_scale_factor}'
SIMPLE_CURRENCY = f'{_currency}{_mantissa}'
UNITS = f'"[^"]*"'
# names
_greek = "αβγδεζηθικλνξοπρςστµμυφχψω"
_Greek = "ΑΒΓΔΕΖΗΘΙΚΛΝΞΟΠΡΣΣΤΜΜΥΦΧΨΩ"
_special = "ħ"
NAME = f"[a-zA-Z_{_greek}{_Greek}{_special}][a-zA-Z0-9_]*[₀₁₂₃₄₅₆₇₈₉]?"
# special tokens
ignore_comment = r'\#.*'
@_(r"\n+")
def ignore_newline(self, t):
self.lineno += len(t.value)
def error(self, t):
raise Error(f"illegal character '{t.value[0]}'.", culprit=get_culprit())
# QEParser {{{1
class QEParser(Parser):
tokens = QELexer.tokens
# globals {{{2
precedence = (
("left", "+", "-"),
("left", "*", "/"),
("right", "POW"),
("right", "UMINUS"),
)
binary_operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
'**': operator.pow,
}
# rules {{{2
@_("NAME '=' expr")
def statement(self, p):
VARIABLES[p.NAME] = p.expr
return p.NAME, p.expr
@_("NAME '=' expr UNITS")
def statement(self, p):
VARIABLES[p.NAME] = p.expr
return p.NAME, QUANTITY(p.expr, p.UNITS[1:-1])
@_("expr")
def statement(self, p):
return None, p.expr
@_("expr UNITS")
def statement(self, p):
return None, QUANTITY(p.expr, p.UNITS[1:-1])
@_("expr '+' expr",
"expr '-' expr",
"expr '*' expr",
"expr '/' expr",
"expr POW expr"
)
def expr(self, p):
op = self.binary_operators[p[1]]
return op(p.expr0, p.expr1)
@_("'-' expr %prec UMINUS")
def expr(self, p):
return -p.expr
@_("'(' expr ')'")
def expr(self, p):
return p.expr
@_("SIMPLE_NUMBER",
"NUMBER_WITH_EXPONENT",
"CURRENCY_WITH_SCALE_FACTOR",
"CURRENCY_WITH_EXPONENT",
"SIMPLE_CURRENCY")
def expr(self, p):
return QUANTITY(p[0])
@_("NAME")
def expr(self, p):
try:
return VARIABLES[p.NAME]
except LookupError:
raise Error("variable unknown.", culprit=get_culprit(p.NAME))
@_("function")
def expr(self, p):
return p.function
@_("NAME '(' arg_list ')'")
def function(self, p):
try:
func = FUNCTIONS[p.NAME]
except LookupError:
raise Error("function unknown.", culprit=get_culprit(p.NAME))
try:
return func(*p.arg_list)
except Exception as e:
raise Error(full_stop(e), culprit=get_culprit(p.NAME))
@_("arg ',' arg_list")
def arg_list(self, p):
return [p.arg] + p.arg_list
@_("arg")
def arg_list(self, p):
return [p.arg]
@_("")
def arg_list(self, p):
return []
@_("expr")
def arg(self, p):
return p.expr
def error(self, p):
if p:
raise Error(f"syntax error at '{p.value}'.", culprit=get_culprit())
else:
raise Error("syntax error at EOF.", culprit=get_culprit())
# Build the parser {{{1
lexer = QELexer()
parser = QEParser()
# Public functions {{{1
# Initialize evaluator {{{2
def initialize(variables = None, functions = None, quantity = None):
"""
Initialize evaluator.
variables (dict):
Values you wish to pre-define.
functions (dict):
Functions you wish to pre-define.
"""
global VARIABLES, FUNCTIONS, QUANTITY
VARIABLES = {} if variables is None else variables
FUNCTIONS = {} if functions is None else functions
QUANTITY = Quantity if quantity is None else quantity
# Evaluate expression {{{2
def evaluate(expr, units = None):
"""
Evaulate an expression.
The expression may contain numbers with units and SI scale factors.
expr (str):
The expression to evaluate.
units (str):
The units of the final result.
"""
# # show output of lexer
# lex.lexer.input(expr)
# while True:
# tok = lexer.token()
# if not tok:
# break # No more input
# print(tok)
name, value = parser.parse(lexer.tokenize(expr))
return QUANTITY(value, model=units, name=name)
# Remove commas {{{2
def rm_commas(s):
"""
Remove commas
First removes any commas from the argument.
Then convert all semicolons to commas.
"""
return s.replace(',', '').replace(';', ',')
# Main {{{1
if __name__ == '__main__': # pragma: no cover
from math import pi, tau
variables = dict(
pi = pi,
π = pi,
tau = tau,
τ = tau,
)
for constant in 'h ħ k q c ε₀ eps0 μ₀ mu0'.split():
variables[constant] = QUANTITY(constant)
variables['T₀'] = Quantity('0°C')
def median(*args):
args = sorted(args)
n = len(args)
m = n//2
if n % 2:
return args[m]
return (args[m] + args[m-1])/2
# average {{{3
def average(*args):
return sum(args)/len(args)
functions = dict(
median = median,
average = average,
min = min,
max = max,
)
initialize(variables, functions)
cases = '''
1MHz ==> 1 MHz
1GiB ==> 1 GiB
1MHz + 1MHz, Hz ==> 2 MHz
$2.5M ==> $2.5M
$250k*1.025**15, $ ==> $362.07k
$1.3M + $1.2M, $ ==> $2.5M
($1.3M + $1.2M)/2, $ ==> $1.25M
($1.3M - $1.2M)/2, $ ==> $50k
($1.3M + -$1.2M)/2, $ ==> $50k
2*pi*1420.405751786MHz, rads/s ==> 8.9247 Grads/s
2*π*1420.405751786MHz, rads/s ==> 8.9247 Grads/s
($1_220_317 + $1_293_494)/2, $ ==> $1.2569M
($1_220_317 + $1_293_494)/2, $ ==> $1.2569M
T = T₀ + 25, K ==> T = 298.15 K
Vt = k*T/q, V ==> Vt = 25.693 mV
max($1.5M; $1.3M; $1.2M), $ ==> $1.5M
min($1.5M; $1.3M; $1.2M), $ ==> $1.2M
average($1.5M; $1.3M; $1.2M), $ ==> $1.3333M
median($1.5M; $1.3M; $1.2M), $ ==> $1.3M
1e-9, F ==> 1 nF
1 MHz ==> 1 MHz
'''
from inform import InformantFactory
succeeds = InformantFactory(clone=display, message_color = 'green')
fails = InformantFactory(clone=display, message_color = 'red')
Quantity.set_prefs(show_label='f', known_units='K')
for case in cases.splitlines():
given, _, expected = case.partition('==>')
expr, _, units = given.partition(',')
expr = rm_commas(expr.strip())
units = units.strip()
expected = expected.strip()
if expr:
try:
q = evaluate(expr, units)
report = succeeds if str(q) == expected else fails
report(f'{expr:>40} ==> {q}')
except Error as e:
e.report(codicil=f'Found on: {expr}.')