forked from inaos/iron-array-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.py
More file actions
838 lines (707 loc) · 24.7 KB
/
Copy pathexpression.py
File metadata and controls
838 lines (707 loc) · 24.7 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: AxiaCore S.A.S. http://axiacore.com
#
# Based on js-expression-eval, by Matthew Crumley ([email protected], http://silentmatt.com/)
# https://github.com/silentmatt/js-expression-eval
#
# Ported to Python and modified by Vera Mazhuga ([email protected], http://vero4ka.info/)
#
# You are free to use and modify this code in anyway you find useful. Please leave this comment in the code
# to acknowledge its original source. If you feel like it, I enjoy hearing about projects that use my code,
# but don't feel like you have to let me know or ask permission.
#
# This module has been modified to use numpy instead of the math module.
#
# This is interesting for testing purposes, but the simplify() method is also useful for supporting
# operations like "cos(1)", "atan(3)" which are not yet fully supported in the core.
from __future__ import division
import math
import random
import re
import numpy as np
TNUMBER = 0
TOP1 = 1
TOP2 = 2
TVAR = 3
TFUNCALL = 4
class Token():
def __init__(self, type_, index_, prio_, number_):
self.type_ = type_
self.index_ = index_ or 0
self.prio_ = prio_ or 0
self.number_ = number_ if number_ != None else 0
def toString(self):
if self.type_ == TNUMBER:
return self.number_
if self.type_ == TOP1 or self.type_ == TOP2 or self.type_ == TVAR:
return self.index_
elif self.type_ == TFUNCALL:
return 'CALL'
else:
return 'Invalid Token'
class Expression():
def __init__(self, tokens, ops1, ops2, functions):
self.tokens = tokens
self.ops1 = ops1
self.ops2 = ops2
self.functions = functions
def simplify(self, values):
values = values or {}
nstack = []
newexpression = []
L = len(self.tokens)
for i in range(0, L):
item = self.tokens[i]
type_ = item.type_
if type_ == TNUMBER:
nstack.append(item)
elif type_ == TVAR and item.index_ in values:
item = Token(TNUMBER, 0, 0, values[item.index_])
nstack.append(item)
elif type_ == TOP2 and len(nstack) > 1:
n2 = nstack.pop()
n1 = nstack.pop()
f = self.ops2[item.index_]
item = Token(TNUMBER, 0, 0, f(n1.number_, n2.number_))
nstack.append(item)
elif type_ == TOP1 and nstack:
n1 = nstack.pop()
f = self.ops1[item.index_]
item = Token(TNUMBER, 0, 0, f(n1.number_))
nstack.append(item)
else:
while len(nstack) > 0:
newexpression.append(nstack.pop(0))
newexpression.append(item)
while nstack:
newexpression.append(nstack.pop(0))
return Expression(newexpression, self.ops1, self.ops2, self.functions)
def substitute(self, variable, expr):
if not isinstance(expr, Expression):
expr = Parser().parse(str(expr))
newexpression = []
L = len(self.tokens)
for i in range(0, L):
item = self.tokens[i]
type_ = item.type_
if type_ == TVAR and item.index_ == variable:
for j in range(0, len(expr.tokens)):
expritem = expr.tokens[j]
replitem = Token(
expritem.type_,
expritem.index_,
expritem.prio_,
expritem.number_,
)
newexpression.append(replitem)
else:
newexpression.append(item)
ret = Expression(newexpression, self.ops1, self.ops2, self.functions)
return ret
def evaluate(self, values):
values = values or {}
nstack = []
L = len(self.tokens)
for item in self.tokens:
type_ = item.type_
if type_ == TNUMBER:
nstack.append(item.number_)
elif type_ == TOP2:
n2 = nstack.pop()
n1 = nstack.pop()
f = self.ops2[item.index_]
nstack.append(f(n1, n2))
elif type_ == TVAR:
if item.index_ in values:
nstack.append(values[item.index_])
elif item.index_ in self.functions:
nstack.append(self.functions[item.index_])
else:
raise Exception('undefined variable: ' + item.index_)
elif type_ == TOP1:
n1 = nstack.pop()
f = self.ops1[item.index_]
nstack.append(f(n1))
elif type_ == TFUNCALL:
n1 = nstack.pop()
f = nstack.pop()
if callable(f):
if type(n1) is list:
nstack.append(f(*n1))
else:
nstack.append(f(n1))
else:
raise Exception(f + ' is not a function')
else:
raise Exception('invalid Expression')
if len(nstack) > 1:
raise Exception('invalid Expression (parity)')
return nstack[0]
def toString(self, toJS=False):
nstack = []
L = len(self.tokens)
for i in range(0, L):
item = self.tokens[i]
type_ = item.type_
if type_ == TNUMBER:
if type(item.number_) == str:
nstack.append("'" + item.number_ + "'")
else:
nstack.append(item.number_)
elif type_ == TOP2:
n2 = nstack.pop()
n1 = nstack.pop()
f = item.index_
if toJS and f == '^':
nstack.append('np.power(' + n1 + ',' + n2 + ')')
else:
frm = '({n1}{f}{n2})'
if f == ',':
frm = '{n1}{f}{n2}'
nstack.append(frm.format(
n1=n1,
n2=n2,
f=f,
))
elif type_ == TVAR:
nstack.append(item.index_)
elif type_ == TOP1:
n1 = nstack.pop()
f = item.index_
if f == '-':
nstack.append('(' + f + str(n1) + ')')
else:
nstack.append(f + '(' + str(n1) + ')')
elif type_ == TFUNCALL:
n1 = nstack.pop()
f = nstack.pop()
nstack.append(f + '(' + n1 + ')')
else:
raise Exception('invalid Expression')
if len(nstack) > 1:
raise Exception('invalid Expression (parity)')
return nstack[0]
def __str__(self):
return self.toString()
def symbols(self):
vars = []
for i in range(0, len(self.tokens)):
item = self.tokens[i]
if item.type_ == TVAR and not item.index_ in vars:
vars.append(item.index_)
return vars
def variables(self):
return [
sym for sym in self.symbols()
if sym not in self.functions]
class Parser:
class Expression(Expression):
pass
PRIMARY = 1
OPERATOR = 2
FUNCTION = 4
LPAREN = 8
RPAREN = 16
COMMA = 32
SIGN = 64
CALL = 128
NULLARY_CALL = 256
def add(self, a, b):
return a + b
def sub(self, a, b):
return a - b
def mul(self, a, b):
return a * b
def div(self, a, b):
return a / b
def mod(self, a, b):
return a % b
def concat(self, a, b, *args):
result = u'{0}{1}'.format(a, b)
for arg in args:
result = u'{0}{1}'.format(result, arg)
return result
def equal(self, a, b):
return a == b
def notEqual(self, a, b):
return a != b
def greaterThan(self, a, b):
return a > b
def lessThan(self, a, b):
return a < b
def greaterThanEqual(self, a, b):
return a >= b
def lessThanEqual(self, a, b):
return a <= b
def andOperator(self, a, b):
return (a and b)
def orOperator(self, a, b):
return (a or b)
def neg(self, a):
return -a
def random(self, a):
return np.random.rand() * (a or 1)
def fac(self, a): # a!
return math.factorial(a)
def pyt(self, a, b):
return np.sqrt(a * a + b * b)
def roll(self, a, b):
rolls = []
for c in range(1, a):
roll = random.randint(1, b)
rolls.append(roll)
return rolls
def ifFunction(self, a, b, c):
return b if a else c
def append(self, a, b):
if type(a) != list:
return [a, b]
a.append(b)
return a
def __init__(self):
self.success = False
self.errormsg = ''
self.expression = ''
self.pos = 0
self.tokennumber = 0
self.tokenprio = 0
self.tokenindex = 0
self.tmpprio = 0
self.ops1 = {
'sin': np.sin,
'cos': np.cos,
'tan': np.tan,
'sinh': np.sinh,
'cosh': np.cosh,
'tanh': np.tanh,
'asin': np.arcsin,
'acos': np.arccos,
'atan': np.arctan,
'sqrt': np.sqrt,
'abs': abs,
'ceil': np.ceil,
'floor': np.floor,
'round': round,
'-': self.neg,
'exp': np.exp,
}
self.ops2 = {
'+': self.add,
'-': self.sub,
'*': self.mul,
'/': self.div,
'%': self.mod,
'^': np.power,
'**': np.power,
',': self.append,
'||': self.concat,
"==": self.equal,
"!=": self.notEqual,
">": self.greaterThan,
"<": self.lessThan,
">=": self.greaterThanEqual,
"<=": self.lessThanEqual,
"and": self.andOperator,
"or": self.orOperator,
"D": self.roll
}
self.functions = {
'random': random,
'fac': self.fac,
'log': np.log,
'log10': np.log10,
'min': min,
'max': max,
'pyt': self.pyt,
'pow': np.power,
'atan2': np.arctan2,
'concat': self.concat,
'if': self.ifFunction
}
self.consts = {
'e': np.e,
'pi': np.pi,
}
self.values = {
'sin': np.sin,
'cos': np.cos,
'tan': np.tan,
'sinh': np.sinh,
'cosh': np.cosh,
'tanh': np.tanh,
'asin': np.arcsin,
'acos': np.arccos,
'atan': np.arctan,
'sqrt': np.sqrt,
'log': np.log,
'log10': np.log10,
'abs': abs,
'ceil': np.ceil,
'floor': np.floor,
'round': round,
'random': self.random,
'fac': self.fac,
'exp': np.exp,
'min': min,
'max': max,
'pyt': self.pyt,
'pow': np.power,
'atan2': np.arctan2,
'e': np.e,
'pi': np.pi
}
def parse(self, expr):
self.errormsg = ''
self.success = True
operstack = []
tokenstack = []
self.tmpprio = 0
expected = self.PRIMARY | self.LPAREN | self.FUNCTION | self.SIGN
noperators = 0
self.expression = expr
self.pos = 0
while self.pos < len(self.expression):
if self.isOperator():
if self.isSign() and expected & self.SIGN:
if self.isNegativeSign():
self.tokenprio = 5
self.tokenindex = '-'
noperators += 1
self.addfunc(tokenstack, operstack, TOP1)
expected = \
self.PRIMARY | self.LPAREN | self.FUNCTION | self.SIGN
elif self.isComment():
pass
else:
if expected and self.OPERATOR == 0:
self.error_parsing(self.pos, 'unexpected operator')
noperators += 2
self.addfunc(tokenstack, operstack, TOP2)
expected = \
self.PRIMARY | self.LPAREN | self.FUNCTION | self.SIGN
elif self.isNumber():
if expected and self.PRIMARY == 0:
self.error_parsing(self.pos, 'unexpected number')
token = Token(TNUMBER, 0, 0, self.tokennumber)
tokenstack.append(token)
expected = self.OPERATOR | self.RPAREN | self.COMMA
elif self.isString():
if (expected & self.PRIMARY) == 0:
self.error_parsing(self.pos, 'unexpected string')
token = Token(TNUMBER, 0, 0, self.tokennumber)
tokenstack.append(token)
expected = self.OPERATOR | self.RPAREN | self.COMMA
elif self.isLeftParenth():
if (expected & self.LPAREN) == 0:
self.error_parsing(self.pos, 'unexpected \"(\"')
if expected & self.CALL:
noperators += 2
self.tokenprio = -2
self.tokenindex = -1
self.addfunc(tokenstack, operstack, TFUNCALL)
expected = \
self.PRIMARY | self.LPAREN | self.FUNCTION | \
self.SIGN | self.NULLARY_CALL
elif self.isRightParenth():
if expected & self.NULLARY_CALL:
token = Token(TNUMBER, 0, 0, [])
tokenstack.append(token)
elif (expected & self.RPAREN) == 0:
self.error_parsing(self.pos, 'unexpected \")\"')
expected = \
self.OPERATOR | self.RPAREN | self.COMMA | \
self.LPAREN | self.CALL
elif self.isComma():
if (expected & self.COMMA) == 0:
self.error_parsing(self.pos, 'unexpected \",\"')
self.addfunc(tokenstack, operstack, TOP2)
noperators += 2
expected = \
self.PRIMARY | self.LPAREN | self.FUNCTION | self.SIGN
elif self.isConst():
if (expected & self.PRIMARY) == 0:
self.error_parsing(self.pos, 'unexpected constant')
consttoken = Token(TNUMBER, 0, 0, self.tokennumber)
tokenstack.append(consttoken)
expected = self.OPERATOR | self.RPAREN | self.COMMA
elif self.isOp2():
if (expected & self.FUNCTION) == 0:
self.error_parsing(self.pos, 'unexpected function')
self.addfunc(tokenstack, operstack, TOP2)
noperators += 2
expected = self.LPAREN
elif self.isOp1():
if (expected & self.FUNCTION) == 0:
self.error_parsing(self.pos, 'unexpected function')
self.addfunc(tokenstack, operstack, TOP1)
noperators += 1
expected = self.LPAREN
elif self.isVar():
if (expected & self.PRIMARY) == 0:
self.error_parsing(self.pos, 'unexpected variable')
vartoken = Token(TVAR, self.tokenindex, 0, 0)
tokenstack.append(vartoken)
expected = \
self.OPERATOR | self.RPAREN | \
self.COMMA | self.LPAREN | self.CALL
elif self.isWhite():
pass
else:
if self.errormsg == '':
self.error_parsing(self.pos, 'unknown character')
else:
self.error_parsing(self.pos, self.errormsg)
if self.tmpprio < 0 or self.tmpprio >= 10:
self.error_parsing(self.pos, 'unmatched \"()\"')
while len(operstack) > 0:
tmp = operstack.pop()
tokenstack.append(tmp)
if (noperators + 1) != len(tokenstack):
self.error_parsing(self.pos, 'parity')
return Expression(tokenstack, self.ops1, self.ops2, self.functions)
def evaluate(self, expr, variables):
return self.parse(expr).evaluate(variables)
def error_parsing(self, column, msg):
self.success = False
self.errormsg = 'parse error [column ' + str(column) + ']: ' + msg
raise Exception(self.errormsg)
def addfunc(self, tokenstack, operstack, type_):
operator = Token(
type_,
self.tokenindex,
self.tokenprio + self.tmpprio,
0,
)
while len(operstack) > 0:
if operator.prio_ <= operstack[len(operstack) - 1].prio_:
tokenstack.append(operstack.pop())
else:
break
operstack.append(operator)
def isNumber(self):
r = False
if self.expression[self.pos] == 'E':
return False
# number in scientific notation
pattern = r'([-+]?([0-9]*\.?[0-9]*)[eE][-+]?[0-9]+).*'
match = re.match(pattern, self.expression[self.pos:])
if match:
self.pos += len(match.group(1))
self.tokennumber = float(match.group(1))
return True
# number in decimal
str = ''
while self.pos < len(self.expression):
code = self.expression[self.pos]
if (code >= '0' and code <= '9') or code == '.':
if (len(str) == 0 and code == '.'):
str = '0'
str += code
self.pos += 1
try:
self.tokennumber = int(str)
except ValueError:
self.tokennumber = float(str)
r = True
else:
break
return r
def unescape(self, v, pos):
buffer = []
escaping = False
for i in range(0, len(v)):
c = v[i]
if escaping:
if c == "'":
buffer.append("'")
break
elif c == '\\':
buffer.append('\\')
break
elif c == '/':
buffer.append('/')
break
elif c == 'b':
buffer.append('\b')
break
elif c == 'f':
buffer.append('\f')
break
elif c == 'n':
buffer.append('\n')
break
elif c == 'r':
buffer.append('\r')
break
elif c == 't':
buffer.append('\t')
break
elif c == 'u':
# interpret the following 4 characters
# as the hex of the unicode code point
codePoint = int(v[i + 1, i + 5], 16)
buffer.append(chr(codePoint))
i += 4
break
else:
raise self.error_parsing(
pos + i,
'Illegal escape sequence: \'\\' + c + '\'',
)
else:
if c == '\\':
escaping = True
else:
buffer.append(c)
return ''.join(buffer)
def isString(self):
r = False
str = ''
startpos = self.pos
if self.pos < len(self.expression) and self.expression[self.pos] in ("'", "\""):
quote_type = self.expression[self.pos]
self.pos += 1
while self.pos < len(self.expression):
code = self.expression[self.pos]
if code != quote_type or (str != '' and str[-1] == '\\'):
str += self.expression[self.pos]
self.pos += 1
else:
self.pos += 1
self.tokennumber = self.unescape(str, startpos)
r = True
break
return r
def isConst(self):
for i in self.consts:
L = len(i)
str = self.expression[self.pos:self.pos + L]
if i == str:
if len(self.expression) <= self.pos + L:
self.tokennumber = self.consts[i]
self.pos += L
return True
if not self.expression[self.pos + L].isalnum() and self.expression[self.pos + L] != "_":
self.tokennumber = self.consts[i]
self.pos += L
return True
return False
def isOperator(self):
ops = (
('+', 2, '+'),
('-', 2, '-'),
('**', 6, '**'),
('*', 3, '*'),
(u'\u2219', 3, '*'), # bullet operator
(u'\u2022', 3, '*'), # black small circle
('/', 4, '/'),
('%', 4, '%'),
('^', 6, '^'),
('||', 1, '||'),
('==', 1, '=='),
('!=', 1, '!='),
('<=', 1, '<='),
('>=', 1, '>='),
('<', 1, '<'),
('>', 1, '>'),
('and ', 0, 'and'),
('or ', 0, 'or'),
)
for token, priority, index in ops:
if self.expression.startswith(token, self.pos):
self.tokenprio = priority
self.tokenindex = index
self.pos += len(token)
return True
return False
def isSign(self):
code = self.expression[self.pos - 1]
return (code == '+') or (code == '-')
def isPositiveSign(self):
code = self.expression[self.pos - 1]
return code == '+'
def isNegativeSign(self):
code = self.expression[self.pos - 1]
return code == '-'
def isLeftParenth(self):
code = self.expression[self.pos]
if code == '(':
self.pos += 1
self.tmpprio += 10
return True
return False
def isRightParenth(self):
code = self.expression[self.pos]
if code == ')':
self.pos += 1
self.tmpprio -= 10
return True
return False
def isComma(self):
code = self.expression[self.pos]
if code == ',':
self.pos += 1
self.tokenprio = -1
self.tokenindex = ","
return True
return False
def isWhite(self):
code = self.expression[self.pos]
if code.isspace():
self.pos += 1
return True
return False
def isOp1(self):
str = ''
for i in range(self.pos, len(self.expression)):
c = self.expression[i]
if c.upper() == c.lower():
if i == self.pos or (c != '_' and (c < '0' or c > '9')):
break
str += c
if len(str) > 0 and str in self.ops1:
self.tokenindex = str
self.tokenprio = 7
self.pos += len(str)
return True
return False
def isOp2(self):
str = ''
for i in range(self.pos, len(self.expression)):
c = self.expression[i]
if c.upper() == c.lower():
if i == self.pos or (c != '_' and (c < '0' or c > '9')):
break
str += c
if len(str) > 0 and (str in self.ops2):
self.tokenindex = str
self.tokenprio = 7
self.pos += len(str)
return True
return False
def isVar(self):
str = ''
inQuotes = False
for i in range(self.pos, len(self.expression)):
c = self.expression[i]
if c.lower() == c.upper():
if ((i == self.pos and c != '"') or (not (c in '_."') and (c < '0' or c > '9'))) and not inQuotes:
break
if c == '"':
inQuotes = not inQuotes
str += c
if str:
self.tokenindex = str
self.tokenprio = 4
self.pos += len(str)
return True
return False
def isComment(self):
code = self.expression[self.pos - 1]
if code == '/' and self.expression[self.pos] == '*':
self.pos = self.expression.index('*/', self.pos) + 2
if self.pos == 1:
self.pos = len(self.expression)
return True
return False