mathjson-solver 2.2.1__py3-none-any.whl → 2.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mathjson_solver/__main__.py +899 -2483
- mathjson_solver/_arithmetic_constructs.py +219 -0
- mathjson_solver/_array_arithmetic_constructs.py +283 -0
- mathjson_solver/_array_helpers.py +55 -0
- mathjson_solver/_collection_constructs.py +819 -0
- mathjson_solver/_combinatorics.py +31 -0
- mathjson_solver/_combinatorics_constructs.py +87 -0
- mathjson_solver/_common.py +136 -0
- mathjson_solver/_comparison_constructs.py +114 -0
- mathjson_solver/_construct_shared.py +62 -0
- mathjson_solver/_control_flow_constructs.py +100 -0
- mathjson_solver/_core_constructs.py +64 -0
- mathjson_solver/_datetime_constructs.py +46 -0
- mathjson_solver/_exceptions.py +46 -0
- mathjson_solver/_functional_constructs.py +133 -0
- mathjson_solver/_interpolation.py +69 -0
- mathjson_solver/_number_theory.py +298 -0
- mathjson_solver/_number_theory_constructs.py +257 -0
- mathjson_solver/_special_function_constructs.py +166 -0
- mathjson_solver/_special_functions.py +157 -0
- mathjson_solver/_statistics_constructs.py +473 -0
- mathjson_solver/_string_constructs.py +364 -0
- mathjson_solver/_trig_constructs.py +34 -0
- {mathjson_solver-2.2.1.dist-info → mathjson_solver-2.3.0.dist-info}/METADATA +67 -45
- mathjson_solver-2.3.0.dist-info/RECORD +28 -0
- {mathjson_solver-2.2.1.dist-info → mathjson_solver-2.3.0.dist-info}/WHEEL +1 -1
- mathjson_solver-2.2.1.dist-info/RECORD +0 -6
- {mathjson_solver-2.2.1.dist-info → mathjson_solver-2.3.0.dist-info}/licenses/LICENSE +0 -0
mathjson_solver/__main__.py
CHANGED
|
@@ -1,197 +1,12 @@
|
|
|
1
1
|
import numbers
|
|
2
2
|
import sys
|
|
3
|
-
from typing import
|
|
3
|
+
from typing import Any as _Any
|
|
4
|
+
from collections.abc import Callable, Iterable
|
|
4
5
|
from functools import reduce
|
|
5
|
-
from fractions import Fraction
|
|
6
6
|
import math
|
|
7
|
-
from copy import deepcopy
|
|
8
|
-
from statistics import (
|
|
9
|
-
median,
|
|
10
|
-
variance,
|
|
11
|
-
stdev,
|
|
12
|
-
pvariance,
|
|
13
|
-
pstdev,
|
|
14
|
-
mode,
|
|
15
|
-
quantiles,
|
|
16
|
-
covariance,
|
|
17
|
-
correlation,
|
|
18
|
-
)
|
|
19
|
-
import datetime
|
|
20
|
-
|
|
21
|
-
NUMPY_AVAILABLE = False
|
|
22
|
-
try:
|
|
23
|
-
import numpy as np
|
|
24
|
-
|
|
25
|
-
NUMPY_AVAILABLE = True
|
|
26
|
-
except ImportError:
|
|
27
|
-
pass
|
|
28
|
-
|
|
29
|
-
RE2_AVAILABLE = False
|
|
30
|
-
try:
|
|
31
|
-
import re2
|
|
32
|
-
|
|
33
|
-
RE2_AVAILABLE = True
|
|
34
|
-
# No public "re2.Pattern" name is exported; derive the actual
|
|
35
|
-
# compiled-pattern type at import time rather than hardcoding
|
|
36
|
-
# re2's internal class path.
|
|
37
|
-
_RE2_PATTERN_TYPE = type(re2.compile(""))
|
|
38
|
-
except ImportError:
|
|
39
|
-
_RE2_PATTERN_TYPE = None
|
|
40
|
-
|
|
41
|
-
# Hard cap on the result length of string operations whose size is
|
|
42
|
-
# otherwise controlled directly by a user-supplied count/length
|
|
43
|
-
# argument (StringRepeat, PadStart, PadEnd) - closes the same
|
|
44
|
-
# memory/time exhaustion shape that Loop/Random/arbitrary-size Repeat
|
|
45
|
-
# are excluded for elsewhere in this solver, but here it's cheaply and
|
|
46
|
-
# exactly bounded by a single length check before any allocation.
|
|
47
|
-
_MAX_STRING_REPEAT_LENGTH = 100_000
|
|
48
|
-
|
|
49
|
-
NoneType = type(None)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def _try_parse_datetime(value):
|
|
53
|
-
"""Try to parse a string as datetime or date. Returns original value if not parseable."""
|
|
54
|
-
if isinstance(value, (datetime.datetime, datetime.date)):
|
|
55
|
-
return value
|
|
56
|
-
if isinstance(value, str):
|
|
57
|
-
try:
|
|
58
|
-
return datetime.datetime.fromisoformat(value)
|
|
59
|
-
except ValueError:
|
|
60
|
-
pass
|
|
61
|
-
try:
|
|
62
|
-
return datetime.date.fromisoformat(value)
|
|
63
|
-
except ValueError:
|
|
64
|
-
pass
|
|
65
|
-
return value
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
# def find_interpolation_bounds(
|
|
69
|
-
# l: list, target: int | float
|
|
70
|
-
# ) -> Union[Union[int, float], tuple[Union[int, float], Union[int, float]]]:
|
|
71
|
-
# for i, x in enumerate(l):
|
|
72
|
-
# if i == 0:
|
|
73
|
-
# continue
|
|
74
|
-
# if l[i - 1] <= target and target <= l[i]:
|
|
75
|
-
# if target == l[i - 1] or target == l[i]:
|
|
76
|
-
# return target
|
|
77
|
-
# else:
|
|
78
|
-
# return l[i - 1], l[i]
|
|
79
|
-
# else:
|
|
80
|
-
# raise ValueError("Target value is outside interpolation range.")
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def _MultiplyByScalar(l: list[numbers.Real], a: numbers.Real) -> list[numbers.Real]:
|
|
84
|
-
return [x * a for x in l]
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
def _MultiplyByArray(
|
|
88
|
-
l1: list[numbers.Real], l2: list[numbers.Real]
|
|
89
|
-
) -> list[numbers.Real]:
|
|
90
|
-
return [a * b for a, b in zip(l1, l2)]
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _AddScalar(l: list[numbers.Real], a: numbers.Real) -> list[numbers.Real]:
|
|
94
|
-
return [x + a for x in l]
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
def _SubtractScalar(l: list[numbers.Real], a: numbers.Real) -> list[numbers.Real]:
|
|
98
|
-
return [x - a for x in l]
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
def _AddArray(l1: list[numbers.Real], l2: list[numbers.Real]) -> list[numbers.Real]:
|
|
102
|
-
return [a + b for a, b in zip(l1, l2)]
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def _SubtractArray(
|
|
106
|
-
l1: list[numbers.Real], l2: list[numbers.Real]
|
|
107
|
-
) -> list[numbers.Real]:
|
|
108
|
-
return [a - b for a, b in zip(l1, l2)]
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def _CumulativeProduct(l: list) -> list:
|
|
112
|
-
res = []
|
|
113
|
-
for i, x in enumerate(l):
|
|
114
|
-
if i == 0:
|
|
115
|
-
res.append(x)
|
|
116
|
-
else:
|
|
117
|
-
res.append(reduce(lambda a, b: a * b, l[: i + 1]))
|
|
118
|
-
return res
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def _CumulativeSum(l: list) -> list:
|
|
122
|
-
res = []
|
|
123
|
-
for i, x in enumerate(l):
|
|
124
|
-
if i == 0:
|
|
125
|
-
res.append(x)
|
|
126
|
-
else:
|
|
127
|
-
res.append(reduce(lambda a, b: a + b, l[: i + 1]))
|
|
128
|
-
return res
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def find_interpolation_bounds_indexes(
|
|
132
|
-
l: list, target: int | float
|
|
133
|
-
) -> Union[Union[int, float], tuple[Union[int, float], Union[int, float]]]:
|
|
134
|
-
for i, x in enumerate(l):
|
|
135
|
-
if i == 0:
|
|
136
|
-
continue
|
|
137
|
-
if l[i - 1] <= target and target <= l[i]:
|
|
138
|
-
if target == l[i - 1]:
|
|
139
|
-
return i - 1
|
|
140
|
-
elif target == l[i]:
|
|
141
|
-
return i
|
|
142
|
-
else:
|
|
143
|
-
return i - 1, i
|
|
144
|
-
else:
|
|
145
|
-
raise ValueError("Target value is outside interpolation range.")
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
def find_interpolation_bounds_2indexes(
|
|
149
|
-
l: list, target: int | float
|
|
150
|
-
) -> Union[Union[int, float], tuple[Union[int, float], Union[int, float]]]:
|
|
151
|
-
for i, x in enumerate(l):
|
|
152
|
-
if i == len(l) - 1:
|
|
153
|
-
return i - 1, i
|
|
154
|
-
if l[i] <= target and target < l[i + 1]:
|
|
155
|
-
return i, i + 1
|
|
156
|
-
else:
|
|
157
|
-
raise ValueError("Target value is outside interpolation range.")
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
def linear_interpolate(x_array, y_array, target_x):
|
|
161
|
-
# Find the interval where target_x falls
|
|
162
|
-
# Handle edge cases (target_x outside range)
|
|
163
|
-
# Apply: y = y1 + (y2 - y1) * (target_x - x1) / (x2 - x1)
|
|
164
|
-
|
|
165
|
-
# first check if both arrays are the same length
|
|
166
|
-
if len(x_array) != len(y_array) or len(x_array) < 2:
|
|
167
|
-
raise ValueError(
|
|
168
|
-
"Both arrays need to be the same length and with at least 2 elements."
|
|
169
|
-
)
|
|
170
|
-
bounds_indexes = find_interpolation_bounds_indexes(x_array, target_x)
|
|
171
|
-
if isinstance(bounds_indexes, tuple):
|
|
172
|
-
x1, x2 = x_array[bounds_indexes[0]], x_array[bounds_indexes[1]]
|
|
173
|
-
y1, y2 = y_array[bounds_indexes[0]], y_array[bounds_indexes[1]]
|
|
174
|
-
return y1 + (y2 - y1) * (target_x - x1) / (x2 - x1)
|
|
175
|
-
else:
|
|
176
|
-
return y_array[bounds_indexes]
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
class MathJSONException(Exception):
|
|
180
|
-
"""Exception for MathJSON processing issues"""
|
|
181
|
-
|
|
182
|
-
def __init__(self, e, expr, *args, **kwargs):
|
|
183
|
-
super().__init__(args)
|
|
184
|
-
self.e = e
|
|
185
|
-
self.expr = expr
|
|
186
|
-
self.construct = kwargs.get("mathjson_construct", "MathJSON")
|
|
187
|
-
|
|
188
|
-
def __str__(self):
|
|
189
|
-
if hasattr(self.e, "message"):
|
|
190
|
-
m = self.e.message
|
|
191
|
-
else:
|
|
192
|
-
m = str(self.e)
|
|
193
|
-
return f"Problem in {self.construct}. {self.expr}. {m}"
|
|
194
7
|
|
|
8
|
+
from ._common import comparison_safe_converter
|
|
9
|
+
from ._exceptions import MathJSONExpression, MathJSONException
|
|
195
10
|
|
|
196
11
|
# def requires_array(func):
|
|
197
12
|
# def inner1(*args, **kwargs):
|
|
@@ -206,127 +21,7 @@ class MathJSONException(Exception):
|
|
|
206
21
|
# return inner1
|
|
207
22
|
|
|
208
23
|
|
|
209
|
-
def
|
|
210
|
-
try:
|
|
211
|
-
float(x)
|
|
212
|
-
except ValueError:
|
|
213
|
-
return False
|
|
214
|
-
except TypeError:
|
|
215
|
-
return False
|
|
216
|
-
else:
|
|
217
|
-
return True
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
def _is_prime(n) -> bool:
|
|
221
|
-
n = int(n)
|
|
222
|
-
if n < 2:
|
|
223
|
-
return False
|
|
224
|
-
if n == 2:
|
|
225
|
-
return True
|
|
226
|
-
if n % 2 == 0:
|
|
227
|
-
return False
|
|
228
|
-
return all(n % i for i in range(3, int(n**0.5) + 1, 2))
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
def has_matching_sublist(
|
|
232
|
-
*,
|
|
233
|
-
my_list: list,
|
|
234
|
-
required_match_count: int,
|
|
235
|
-
position: int,
|
|
236
|
-
contiguous: bool,
|
|
237
|
-
conditions: list[bool],
|
|
238
|
-
) -> bool:
|
|
239
|
-
if contiguous:
|
|
240
|
-
# Check for contiguous matches based on position
|
|
241
|
-
if position == 0:
|
|
242
|
-
# Check if the beginning of the list matches
|
|
243
|
-
count = sum(
|
|
244
|
-
1
|
|
245
|
-
for i in range(min(required_match_count, len(my_list)))
|
|
246
|
-
if conditions[i]
|
|
247
|
-
)
|
|
248
|
-
return count == required_match_count
|
|
249
|
-
elif position > 0:
|
|
250
|
-
# Skip the first `position` elements
|
|
251
|
-
count = sum(
|
|
252
|
-
1
|
|
253
|
-
for i in range(position, position + required_match_count)
|
|
254
|
-
if i < len(my_list) and conditions[i]
|
|
255
|
-
)
|
|
256
|
-
return count == required_match_count
|
|
257
|
-
elif position == -1:
|
|
258
|
-
# Check if the end of the list matches
|
|
259
|
-
count = sum(
|
|
260
|
-
1
|
|
261
|
-
for i in range(len(my_list) - required_match_count, len(my_list))
|
|
262
|
-
if conditions[i]
|
|
263
|
-
)
|
|
264
|
-
return count == required_match_count
|
|
265
|
-
elif position < -1:
|
|
266
|
-
# Skip the last `abs(position)` elements
|
|
267
|
-
count = sum(1 for i in range(len(my_list) + position) if conditions[i])
|
|
268
|
-
return count == required_match_count
|
|
269
|
-
else:
|
|
270
|
-
# Check for non-contiguous matches
|
|
271
|
-
count = sum(1 for i in range(len(my_list)) if conditions[i])
|
|
272
|
-
return count >= required_match_count
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
# def has_sublist2(
|
|
276
|
-
# *,
|
|
277
|
-
# my_list: list,
|
|
278
|
-
# required_match_count: int,
|
|
279
|
-
# position: int,
|
|
280
|
-
# contiguous: bool,
|
|
281
|
-
# condition: callable,
|
|
282
|
-
# ) -> bool:
|
|
283
|
-
# if contiguous:
|
|
284
|
-
# # Check for contiguous matches based on position
|
|
285
|
-
# if position == 0:
|
|
286
|
-
# # Check if the beginning of the list matches
|
|
287
|
-
# count = sum(1 for x in my_list[:required_match_count] if condition(x))
|
|
288
|
-
# return count == required_match_count
|
|
289
|
-
# elif position > 0:
|
|
290
|
-
# # Skip the first `position` elements
|
|
291
|
-
# count = sum(
|
|
292
|
-
# 1
|
|
293
|
-
# for x in my_list[position : position + required_match_count]
|
|
294
|
-
# if condition(x)
|
|
295
|
-
# )
|
|
296
|
-
# return count == required_match_count
|
|
297
|
-
# elif position == -1:
|
|
298
|
-
# # Check if the end of the list matches
|
|
299
|
-
# count = sum(1 for x in my_list[-required_match_count:] if condition(x))
|
|
300
|
-
# return count == required_match_count
|
|
301
|
-
# elif position < -1:
|
|
302
|
-
# # Skip the last `abs(position)` elements
|
|
303
|
-
# count = sum(1 for x in my_list[:position] if condition(x))
|
|
304
|
-
# return count == required_match_count
|
|
305
|
-
# else:
|
|
306
|
-
# # Check for non-contiguous matches
|
|
307
|
-
# count = sum(1 for x in my_list if condition(x))
|
|
308
|
-
# return count >= required_match_count
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
def comparison_safe_converter(x):
|
|
312
|
-
if type(x) in [bool, NoneType]: # bool before int (bool IS an int in Python)
|
|
313
|
-
return "1" if x else "0"
|
|
314
|
-
elif type(x) in [int, float, str]:
|
|
315
|
-
return f"{x}"
|
|
316
|
-
return x
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
def comparison_safe_converter_for_pairs(
|
|
320
|
-
v1, v2
|
|
321
|
-
) -> (Union[str, float], Union[str, float]):
|
|
322
|
-
if is_numeric(v1):
|
|
323
|
-
v1 = float(v1)
|
|
324
|
-
if is_numeric(v2):
|
|
325
|
-
v2 = float(v2)
|
|
326
|
-
return v1, v2
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
def translate_v1_mathjson(expr):
|
|
24
|
+
def translate_v1_mathjson(expr: MathJSONExpression) -> MathJSONExpression:
|
|
330
25
|
"""
|
|
331
26
|
Rewrite a MathJSON expression written for mathjson-solver < 2.0.0 so it
|
|
332
27
|
evaluates to the same result on >= 2.0.0.
|
|
@@ -348,13 +43,755 @@ def translate_v1_mathjson(expr):
|
|
|
348
43
|
return expr
|
|
349
44
|
|
|
350
45
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
46
|
+
from ._arithmetic_constructs import (
|
|
47
|
+
Add,
|
|
48
|
+
Sum,
|
|
49
|
+
Subtract,
|
|
50
|
+
Max,
|
|
51
|
+
Min,
|
|
52
|
+
Average,
|
|
53
|
+
Median,
|
|
54
|
+
Clamp,
|
|
55
|
+
Int,
|
|
56
|
+
Float,
|
|
57
|
+
Floor,
|
|
58
|
+
Ceil,
|
|
59
|
+
Numerator,
|
|
60
|
+
Denominator,
|
|
61
|
+
Rational,
|
|
62
|
+
Product,
|
|
63
|
+
)
|
|
64
|
+
from ._array_arithmetic_constructs import (
|
|
65
|
+
MultiplyByScalar,
|
|
66
|
+
MultiplyByArray,
|
|
67
|
+
AddScalar,
|
|
68
|
+
SubtractScalar,
|
|
69
|
+
AddArray,
|
|
70
|
+
SubtractArray,
|
|
71
|
+
GenerateRange,
|
|
72
|
+
AtIndex,
|
|
73
|
+
Slice,
|
|
74
|
+
CumulativeProduct,
|
|
75
|
+
CumulativeSum,
|
|
76
|
+
Interp,
|
|
77
|
+
FindIntervalIndex,
|
|
78
|
+
TrapezoidalIntegrate,
|
|
79
|
+
)
|
|
80
|
+
from ._collection_constructs import (
|
|
81
|
+
Arr,
|
|
82
|
+
Length,
|
|
83
|
+
First,
|
|
84
|
+
Second,
|
|
85
|
+
Third,
|
|
86
|
+
Last,
|
|
87
|
+
Rest,
|
|
88
|
+
Most,
|
|
89
|
+
Reverse,
|
|
90
|
+
Sort,
|
|
91
|
+
IsEmpty,
|
|
92
|
+
Range,
|
|
93
|
+
Join,
|
|
94
|
+
Unique,
|
|
95
|
+
Zip,
|
|
96
|
+
At,
|
|
97
|
+
Take,
|
|
98
|
+
Drop,
|
|
99
|
+
TakeWhile,
|
|
100
|
+
DropWhile,
|
|
101
|
+
Contains,
|
|
102
|
+
IndexOf,
|
|
103
|
+
IndexWhere,
|
|
104
|
+
Find,
|
|
105
|
+
CountIf,
|
|
106
|
+
Position,
|
|
107
|
+
RotateLeft,
|
|
108
|
+
RotateRight,
|
|
109
|
+
MaxBy,
|
|
110
|
+
MinBy,
|
|
111
|
+
ArgMax,
|
|
112
|
+
ArgMin,
|
|
113
|
+
Ordering,
|
|
114
|
+
FlatMap,
|
|
115
|
+
Scan,
|
|
116
|
+
Differences,
|
|
117
|
+
Dedup,
|
|
118
|
+
Insert,
|
|
119
|
+
DeleteAt,
|
|
120
|
+
ReplaceAt,
|
|
121
|
+
Partition,
|
|
122
|
+
Chunk,
|
|
123
|
+
GroupBy,
|
|
124
|
+
ChunkBy,
|
|
125
|
+
Tally,
|
|
126
|
+
Union,
|
|
127
|
+
Intersection,
|
|
128
|
+
SetMinus,
|
|
129
|
+
SymmetricDifference,
|
|
130
|
+
Subset,
|
|
131
|
+
SubsetEqual,
|
|
132
|
+
Superset,
|
|
133
|
+
SupersetEqual,
|
|
134
|
+
NotSubset,
|
|
135
|
+
NotSuperset,
|
|
136
|
+
Any,
|
|
137
|
+
All,
|
|
138
|
+
Interval,
|
|
139
|
+
Open,
|
|
140
|
+
In,
|
|
141
|
+
Not_in,
|
|
142
|
+
Contains_any_of,
|
|
143
|
+
Contains_all_of,
|
|
144
|
+
Contains_none_of,
|
|
145
|
+
HasMatchingSublist,
|
|
146
|
+
Appended,
|
|
147
|
+
)
|
|
148
|
+
from ._combinatorics_constructs import (
|
|
149
|
+
Fibonacci,
|
|
150
|
+
Multinomial,
|
|
151
|
+
Subfactorial,
|
|
152
|
+
BellNumber,
|
|
153
|
+
PowerSet,
|
|
154
|
+
Permutations,
|
|
155
|
+
Combinations,
|
|
156
|
+
CartesianProduct,
|
|
157
|
+
)
|
|
158
|
+
from ._comparison_constructs import (
|
|
159
|
+
Not,
|
|
160
|
+
IsDefined,
|
|
161
|
+
IsUndefined,
|
|
162
|
+
Greater,
|
|
163
|
+
GreaterEqual,
|
|
164
|
+
Less,
|
|
165
|
+
LessEqual,
|
|
166
|
+
IdenticallyEqual,
|
|
167
|
+
Congruent,
|
|
168
|
+
BooleanAnd,
|
|
169
|
+
BooleanOr,
|
|
170
|
+
)
|
|
171
|
+
from ._control_flow_constructs import (
|
|
172
|
+
Constants,
|
|
173
|
+
Switch,
|
|
174
|
+
StrictSwitch,
|
|
175
|
+
Which,
|
|
176
|
+
Variable,
|
|
177
|
+
Function,
|
|
178
|
+
)
|
|
179
|
+
from ._core_constructs import (
|
|
180
|
+
Head,
|
|
181
|
+
Tail,
|
|
182
|
+
Hold,
|
|
183
|
+
Type,
|
|
184
|
+
IsSame,
|
|
185
|
+
)
|
|
186
|
+
from ._datetime_constructs import (
|
|
187
|
+
Strptime,
|
|
188
|
+
Strftime,
|
|
189
|
+
Now,
|
|
190
|
+
Today,
|
|
191
|
+
TimeDeltaDays,
|
|
192
|
+
TimeDeltaMinutes,
|
|
193
|
+
TimeDeltaHours,
|
|
194
|
+
TimeDeltaWeeks,
|
|
195
|
+
)
|
|
196
|
+
from ._functional_constructs import (
|
|
197
|
+
Fold,
|
|
198
|
+
Map,
|
|
199
|
+
StrictMap,
|
|
200
|
+
Filter,
|
|
201
|
+
Reduce,
|
|
202
|
+
)
|
|
203
|
+
from ._number_theory_constructs import (
|
|
204
|
+
IsPrime,
|
|
205
|
+
FactorInteger,
|
|
206
|
+
PrimeFactors,
|
|
207
|
+
PrimeNu,
|
|
208
|
+
PrimeOmega,
|
|
209
|
+
Radical,
|
|
210
|
+
IsSquareFree,
|
|
211
|
+
Divisors,
|
|
212
|
+
Sigma0,
|
|
213
|
+
Sigma1,
|
|
214
|
+
SigmaMinus1,
|
|
215
|
+
DivisorSigma,
|
|
216
|
+
Totient,
|
|
217
|
+
IsPerfectPower,
|
|
218
|
+
NthPrime,
|
|
219
|
+
NextPrime,
|
|
220
|
+
PrimePi,
|
|
221
|
+
ExtendedGCD,
|
|
222
|
+
ChineseRemainder,
|
|
223
|
+
CarmichaelLambda,
|
|
224
|
+
JacobiSymbol,
|
|
225
|
+
MultiplicativeOrder,
|
|
226
|
+
PrimitiveRoot,
|
|
227
|
+
LucasL,
|
|
228
|
+
BernoulliB,
|
|
229
|
+
ContinuedFraction,
|
|
230
|
+
FromContinuedFraction,
|
|
231
|
+
IntegerDigits,
|
|
232
|
+
DigitCount,
|
|
233
|
+
DigitSum,
|
|
234
|
+
FromDigits,
|
|
235
|
+
IsSquare,
|
|
236
|
+
IsTriangular,
|
|
237
|
+
IsPentagonal,
|
|
238
|
+
IsOctahedral,
|
|
239
|
+
IsCenteredSquare,
|
|
240
|
+
IsPerfect,
|
|
241
|
+
IsAbundant,
|
|
242
|
+
IsHappy,
|
|
243
|
+
)
|
|
244
|
+
from ._special_function_constructs import (
|
|
245
|
+
Beta,
|
|
246
|
+
Factorial2,
|
|
247
|
+
ErfInv,
|
|
248
|
+
LambertW,
|
|
249
|
+
AGM,
|
|
250
|
+
EllipticK,
|
|
251
|
+
EllipticE,
|
|
252
|
+
Hypergeometric1F1,
|
|
253
|
+
Hypergeometric2F1,
|
|
254
|
+
BesselJ,
|
|
255
|
+
BesselY,
|
|
256
|
+
BesselI,
|
|
257
|
+
BesselK,
|
|
258
|
+
AiryAi,
|
|
259
|
+
AiryBi,
|
|
260
|
+
AiryAiPrime,
|
|
261
|
+
AiryBiPrime,
|
|
262
|
+
Zeta,
|
|
263
|
+
GammaRegularized,
|
|
264
|
+
BetaRegularized,
|
|
265
|
+
)
|
|
266
|
+
from ._statistics_constructs import (
|
|
267
|
+
Variance,
|
|
268
|
+
StandardDeviation,
|
|
269
|
+
PopulationVariance,
|
|
270
|
+
PopulationStandardDeviation,
|
|
271
|
+
Mode,
|
|
272
|
+
Quartiles,
|
|
273
|
+
InterquartileRange,
|
|
274
|
+
Covariance,
|
|
275
|
+
Correlation,
|
|
276
|
+
Skewness,
|
|
277
|
+
Kurtosis,
|
|
278
|
+
LinearRegression,
|
|
279
|
+
PolynomialFit,
|
|
280
|
+
NormalDistribution,
|
|
281
|
+
BinomialDistribution,
|
|
282
|
+
PoissonDistribution,
|
|
283
|
+
UniformDistribution,
|
|
284
|
+
ExponentialDistribution,
|
|
285
|
+
PDF,
|
|
286
|
+
CDF,
|
|
287
|
+
Quantile,
|
|
288
|
+
)
|
|
289
|
+
from ._string_constructs import (
|
|
290
|
+
Str,
|
|
291
|
+
String,
|
|
292
|
+
StringJoin,
|
|
293
|
+
Utf8,
|
|
294
|
+
Utf16,
|
|
295
|
+
UnicodeScalars,
|
|
296
|
+
StringFrom,
|
|
297
|
+
Characters,
|
|
298
|
+
StringSplit,
|
|
299
|
+
StringReplace,
|
|
300
|
+
StringCompare,
|
|
301
|
+
IntegerString,
|
|
302
|
+
DigitsFrom,
|
|
303
|
+
NumberFrom,
|
|
304
|
+
StringRepeat,
|
|
305
|
+
PadStart,
|
|
306
|
+
PadEnd,
|
|
307
|
+
RegExp,
|
|
308
|
+
IsMatch,
|
|
309
|
+
StringMatch,
|
|
310
|
+
StringMatchAll,
|
|
311
|
+
)
|
|
312
|
+
from ._trig_constructs import (
|
|
313
|
+
Sin,
|
|
314
|
+
Arcsin,
|
|
315
|
+
Cos,
|
|
316
|
+
Arccos,
|
|
317
|
+
Tan,
|
|
318
|
+
Arctan,
|
|
319
|
+
Pi,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def If(f, c, solver_parameters, s):
|
|
324
|
+
if len(s) < 3:
|
|
325
|
+
raise ValueError("Wrong parameters for 'If'")
|
|
326
|
+
|
|
327
|
+
# Detect the CortexJS flat form: ["If", cond, then] or
|
|
328
|
+
# ["If", cond, then, else]. In the Python pair-form below,
|
|
329
|
+
# s[1] is always a [condition, value] pair whose first
|
|
330
|
+
# element (the condition) is itself a MathJSON construct
|
|
331
|
+
# call, e.g. ["Equal", 1, 0]. A CortexJS flat condition is
|
|
332
|
+
# either not a list at all, or is itself such a construct
|
|
333
|
+
# call (its own first element is a *known construct name*).
|
|
334
|
+
# Requiring a known name - rather than any string - keeps a
|
|
335
|
+
# Python-form condition that is a bare parameter reference,
|
|
336
|
+
# e.g. ["If", ["my_flag", "yes"], "no"], from being
|
|
337
|
+
# misdetected as CortexJS form.
|
|
338
|
+
is_cortexjs_form = not isinstance(s[1], list) or (
|
|
339
|
+
bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
if is_cortexjs_form:
|
|
343
|
+
if len(s) not in (3, 4):
|
|
344
|
+
raise ValueError("Wrong parameters for 'If'")
|
|
345
|
+
if f(s[1], c):
|
|
346
|
+
return f(s[2], c)
|
|
347
|
+
elif len(s) == 4:
|
|
348
|
+
return f(s[3], c)
|
|
355
349
|
else:
|
|
356
|
-
|
|
357
|
-
|
|
350
|
+
return None # CortexJS: Nothing, no else and condition false
|
|
351
|
+
|
|
352
|
+
for x in s[1:-1]:
|
|
353
|
+
if len(x) != 2:
|
|
354
|
+
raise ValueError("Wrong if or elif in 'If'")
|
|
355
|
+
try:
|
|
356
|
+
if f(x[0], c):
|
|
357
|
+
try:
|
|
358
|
+
return f(x[1], c)
|
|
359
|
+
except MathJSONException:
|
|
360
|
+
# Branch failed, try next condition
|
|
361
|
+
continue
|
|
362
|
+
except MathJSONException:
|
|
363
|
+
return f(s[-1], c) # return default value (else)
|
|
364
|
+
|
|
365
|
+
return f(s[-1], c)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
constructs = {
|
|
369
|
+
"Sum": Sum,
|
|
370
|
+
"Add": Add,
|
|
371
|
+
"Subtract": Subtract,
|
|
372
|
+
"Constants": Constants,
|
|
373
|
+
"Switch": Switch,
|
|
374
|
+
"StrictSwitch": StrictSwitch,
|
|
375
|
+
"If": If,
|
|
376
|
+
"Multiply": lambda f, c, solver_parameters, s: reduce(
|
|
377
|
+
lambda a, b: float(a) * float(b), [f(x, c) for x in s[1:]]
|
|
378
|
+
),
|
|
379
|
+
"Divide": lambda f, c, solver_parameters, s: f(s[1], c) / f(s[2], c),
|
|
380
|
+
"Negate": lambda f, c, solver_parameters, s: -f(s[1], c),
|
|
381
|
+
"Power": lambda f, c, solver_parameters, s: pow(f(s[1], c), f(s[2], c)),
|
|
382
|
+
"Root": lambda f, c, solver_parameters, s: pow(f(s[1], c), 1.0 / f(s[2], c)),
|
|
383
|
+
"Sqrt": lambda f, c, solver_parameters, s: pow(f(s[1], c), 1.0 / 2),
|
|
384
|
+
"Square": lambda f, c, solver_parameters, s: pow(f(s[1], c), 2),
|
|
385
|
+
"Exp": lambda f, c, solver_parameters, s: math.exp(f(s[1], c)),
|
|
386
|
+
# CortexJS-compatible: ["Log", x] is log base 10; ["Log", x, b] is
|
|
387
|
+
# log base b. Use "Ln" for natural log. (BREAKING as of 2.0.0 -
|
|
388
|
+
# "Log" previously meant natural log.)
|
|
389
|
+
"Log": lambda f, c, solver_parameters, s: (
|
|
390
|
+
math.log10(f(s[1], c)) if len(s) == 2 else math.log(f(s[1], c), f(s[2], c))
|
|
391
|
+
),
|
|
392
|
+
"Log2": lambda f, c, solver_parameters, s: math.log2(f(s[1], c)),
|
|
393
|
+
"Log10": lambda f, c, solver_parameters, s: math.log10(f(s[1], c)),
|
|
394
|
+
"Ln": lambda f, c, solver_parameters, s: math.log(f(s[1], c)),
|
|
395
|
+
"Lb": lambda f, c, solver_parameters, s: math.log2(
|
|
396
|
+
f(s[1], c)
|
|
397
|
+
), # CortexJS name for Log2
|
|
398
|
+
"Lg": lambda f, c, solver_parameters, s: math.log10(
|
|
399
|
+
f(s[1], c)
|
|
400
|
+
), # CortexJS name for Log10
|
|
401
|
+
"LogOnePlus": lambda f, c, solver_parameters, s: math.log1p(f(s[1], c)),
|
|
402
|
+
# "Equal": lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
|
|
403
|
+
"Equal": lambda f, c, solver_parameters, s: comparison_safe_converter(f(s[1], c))
|
|
404
|
+
== comparison_safe_converter(f(s[2], c)),
|
|
405
|
+
"IsTrue": lambda f, c, solver_parameters, s: bool(f(s[1], c)),
|
|
406
|
+
"IsFalse": lambda f, c, solver_parameters, s: not bool(f(s[1], c)),
|
|
407
|
+
"StrictEqual": lambda f, c, solver_parameters, s: f(s[1], c) == f(s[2], c),
|
|
408
|
+
"IdenticallyEqual": IdenticallyEqual,
|
|
409
|
+
"Congruent": Congruent,
|
|
410
|
+
# "Greater": lambda s: f(s[1], c) > f(s[2], c),
|
|
411
|
+
"Greater": Greater,
|
|
412
|
+
# "GreaterEqual": lambda s: f(s[1], c) >= f(s[2], c),
|
|
413
|
+
"GreaterEqual": GreaterEqual,
|
|
414
|
+
# "Less": lambda s: f(s[1], c) < f(s[2], c),
|
|
415
|
+
"Less": Less,
|
|
416
|
+
# "LessEqual": lambda s: f(s[1], c) <= f(s[2], c),
|
|
417
|
+
"LessEqual": LessEqual,
|
|
418
|
+
# "NotEqual": lambda s: f(s[1], c) != f(s[2], c),
|
|
419
|
+
"NotEqual": lambda f, c, solver_parameters, s: comparison_safe_converter(f(s[1], c))
|
|
420
|
+
!= comparison_safe_converter(f(s[2], c)),
|
|
421
|
+
"And": BooleanAnd,
|
|
422
|
+
"Or": BooleanOr,
|
|
423
|
+
"Abs": lambda f, c, solver_parameters, s: abs(f(s[1], c)),
|
|
424
|
+
"Round": lambda f, c, solver_parameters, s: (
|
|
425
|
+
round(f(s[1], c), f(s[2], c)) if len(s) == 3 else int(round(f(s[1], c)))
|
|
426
|
+
),
|
|
427
|
+
"Max": Max,
|
|
428
|
+
"Min": Min,
|
|
429
|
+
"Average": Average,
|
|
430
|
+
"Mean": Average, # CortexJS name for Average
|
|
431
|
+
"Median": Median,
|
|
432
|
+
"Length": Length,
|
|
433
|
+
"Count": Length, # CortexJS name for Length
|
|
434
|
+
"Any": Any,
|
|
435
|
+
"All": All,
|
|
436
|
+
"Array": Arr,
|
|
437
|
+
"List": lambda f, c, solver_parameters, s: ["Array"]
|
|
438
|
+
+ [f(x, c) for x in s[1:]], # CortexJS name for Array
|
|
439
|
+
"In": In,
|
|
440
|
+
"Not_in": Not_in,
|
|
441
|
+
"Element": In, # CortexJS name for In - array, string, or Interval membership
|
|
442
|
+
"NotElement": Not_in, # CortexJS name for Not_in
|
|
443
|
+
"Contains_any_of": Contains_any_of,
|
|
444
|
+
"Contains_all_of": Contains_all_of,
|
|
445
|
+
"Contains_none_of": Contains_none_of,
|
|
446
|
+
"NotIn": Not_in,
|
|
447
|
+
"ContainsAnyOf": Contains_any_of,
|
|
448
|
+
"ContainsAllOf": Contains_all_of,
|
|
449
|
+
"ContainsNoneOf": Contains_none_of,
|
|
450
|
+
"Int": Int,
|
|
451
|
+
"Float": Float,
|
|
452
|
+
"Floor": Floor,
|
|
453
|
+
"Ceil": Ceil,
|
|
454
|
+
"Str": Str,
|
|
455
|
+
# --- Strings ---
|
|
456
|
+
"String": String,
|
|
457
|
+
"StringJoin": StringJoin,
|
|
458
|
+
"ToUpperCase": lambda f, c, solver_parameters, s: f(s[1], c).upper(),
|
|
459
|
+
"ToLowerCase": lambda f, c, solver_parameters, s: f(s[1], c).lower(),
|
|
460
|
+
"CaseFold": lambda f, c, solver_parameters, s: f(s[1], c).casefold(),
|
|
461
|
+
"Trim": lambda f, c, solver_parameters, s: f(s[1], c).strip(),
|
|
462
|
+
"TrimStart": lambda f, c, solver_parameters, s: f(s[1], c).lstrip(),
|
|
463
|
+
"TrimEnd": lambda f, c, solver_parameters, s: f(s[1], c).rstrip(),
|
|
464
|
+
"StringSplit": StringSplit,
|
|
465
|
+
"StringReplace": StringReplace,
|
|
466
|
+
"StringCompare": StringCompare,
|
|
467
|
+
"StringRepeat": StringRepeat,
|
|
468
|
+
"PadStart": PadStart,
|
|
469
|
+
"PadEnd": PadEnd,
|
|
470
|
+
"Characters": Characters,
|
|
471
|
+
"GraphemeClusters": Characters, # CortexJS synonym for Characters
|
|
472
|
+
"Utf8": Utf8,
|
|
473
|
+
"Utf16": Utf16,
|
|
474
|
+
"UnicodeScalars": UnicodeScalars,
|
|
475
|
+
"StringFrom": StringFrom,
|
|
476
|
+
"IntegerString": IntegerString,
|
|
477
|
+
"DigitsFrom": DigitsFrom,
|
|
478
|
+
"NumberFrom": NumberFrom,
|
|
479
|
+
"RegExp": RegExp,
|
|
480
|
+
"IsMatch": IsMatch,
|
|
481
|
+
"StringMatch": StringMatch,
|
|
482
|
+
"StringMatchAll": StringMatchAll,
|
|
483
|
+
"Not": Not,
|
|
484
|
+
# "IsDefined": lambda s: s[1] in c,
|
|
485
|
+
"IsDefined": IsDefined,
|
|
486
|
+
"IsUndefined": IsUndefined,
|
|
487
|
+
"Map": Map,
|
|
488
|
+
"StrictMap": StrictMap,
|
|
489
|
+
"Filter": Filter,
|
|
490
|
+
"HasMatchingSublist": HasMatchingSublist,
|
|
491
|
+
"Strptime": Strptime,
|
|
492
|
+
"Strftime": Strftime,
|
|
493
|
+
"Today": Today,
|
|
494
|
+
"Now": Now,
|
|
495
|
+
"TimeDeltaWeeks": TimeDeltaWeeks,
|
|
496
|
+
"TimeDeltaHours": TimeDeltaHours,
|
|
497
|
+
"TimeDeltaMinutes": TimeDeltaMinutes,
|
|
498
|
+
"TimeDeltaDays": TimeDeltaDays,
|
|
499
|
+
"Function": Function,
|
|
500
|
+
"Variable": Variable,
|
|
501
|
+
"MultiplyByScalar": MultiplyByScalar,
|
|
502
|
+
"MultiplyByArray": MultiplyByArray,
|
|
503
|
+
"AddScalar": AddScalar,
|
|
504
|
+
"SubtractScalar": SubtractScalar,
|
|
505
|
+
"AddArray": AddArray,
|
|
506
|
+
"SubtractArray": SubtractArray,
|
|
507
|
+
"GenerateRange": GenerateRange,
|
|
508
|
+
"AtIndex": AtIndex,
|
|
509
|
+
"Slice": Slice,
|
|
510
|
+
"CumulativeProduct": CumulativeProduct,
|
|
511
|
+
"CumulativeSum": CumulativeSum,
|
|
512
|
+
"Interp": Interp,
|
|
513
|
+
"FindIntervalIndex": FindIntervalIndex,
|
|
514
|
+
"TrapezoidalIntegrate": TrapezoidalIntegrate,
|
|
515
|
+
"Reduce": Reduce,
|
|
516
|
+
"Product": Product,
|
|
517
|
+
"Appended": Appended,
|
|
518
|
+
"Sin": Sin,
|
|
519
|
+
"Cos": Cos,
|
|
520
|
+
"Tan": Tan,
|
|
521
|
+
"Arcsin": Arcsin,
|
|
522
|
+
"Arccos": Arccos,
|
|
523
|
+
"Arctan": Arctan,
|
|
524
|
+
"Arctan2": lambda f, c, solver_parameters, s: math.atan2(f(s[1], c), f(s[2], c)),
|
|
525
|
+
"Pi": Pi,
|
|
526
|
+
"Which": Which, # CortexJS multi-branch conditional (not Switch - see Which's docstring)
|
|
527
|
+
# --- Trigonometric: reciprocal, hyperbolic, area-hyperbolic ---
|
|
528
|
+
"Cot": lambda f, c, solver_parameters, s: 1 / math.tan(f(s[1], c)),
|
|
529
|
+
"Sec": lambda f, c, solver_parameters, s: 1 / math.cos(f(s[1], c)),
|
|
530
|
+
"Csc": lambda f, c, solver_parameters, s: 1 / math.sin(f(s[1], c)),
|
|
531
|
+
"Arccot": lambda f, c, solver_parameters, s: math.atan(1 / f(s[1], c)),
|
|
532
|
+
"Arcsec": lambda f, c, solver_parameters, s: math.acos(1 / f(s[1], c)),
|
|
533
|
+
"Arccsc": lambda f, c, solver_parameters, s: math.asin(1 / f(s[1], c)),
|
|
534
|
+
"Sinh": lambda f, c, solver_parameters, s: math.sinh(f(s[1], c)),
|
|
535
|
+
"Cosh": lambda f, c, solver_parameters, s: math.cosh(f(s[1], c)),
|
|
536
|
+
"Tanh": lambda f, c, solver_parameters, s: math.tanh(f(s[1], c)),
|
|
537
|
+
"Coth": lambda f, c, solver_parameters, s: 1 / math.tanh(f(s[1], c)),
|
|
538
|
+
"Sech": lambda f, c, solver_parameters, s: 1 / math.cosh(f(s[1], c)),
|
|
539
|
+
"Csch": lambda f, c, solver_parameters, s: 1 / math.sinh(f(s[1], c)),
|
|
540
|
+
"Arsinh": lambda f, c, solver_parameters, s: math.asinh(f(s[1], c)),
|
|
541
|
+
"Arcosh": lambda f, c, solver_parameters, s: math.acosh(f(s[1], c)),
|
|
542
|
+
"Artanh": lambda f, c, solver_parameters, s: math.atanh(f(s[1], c)),
|
|
543
|
+
"Arcoth": lambda f, c, solver_parameters, s: math.atanh(1 / f(s[1], c)),
|
|
544
|
+
"Arsech": lambda f, c, solver_parameters, s: math.acosh(1 / f(s[1], c)),
|
|
545
|
+
"Arcsch": lambda f, c, solver_parameters, s: math.asinh(1 / f(s[1], c)),
|
|
546
|
+
"Hypot": lambda f, c, solver_parameters, s: math.hypot(f(s[1], c), f(s[2], c)),
|
|
547
|
+
"Sinc": lambda f, c, solver_parameters, s: (
|
|
548
|
+
1.0 if f(s[1], c) == 0 else math.sin(f(s[1], c)) / f(s[1], c)
|
|
549
|
+
),
|
|
550
|
+
# --- Constants ---
|
|
551
|
+
"Degrees": lambda f, c, solver_parameters, s: math.pi / 180,
|
|
552
|
+
"ExponentialE": lambda f, c, solver_parameters, s: math.e,
|
|
553
|
+
"GoldenRatio": lambda f, c, solver_parameters, s: (1 + math.sqrt(5)) / 2,
|
|
554
|
+
"MachineEpsilon": lambda f, c, solver_parameters, s: sys.float_info.epsilon,
|
|
555
|
+
"CatalanConstant": lambda f, c, solver_parameters, s: 0.915965594177219015054603514932384110774,
|
|
556
|
+
"EulerGamma": lambda f, c, solver_parameters, s: 0.5772156649015328606065120900824024310421,
|
|
557
|
+
"Rational": Rational,
|
|
558
|
+
"Numerator": Numerator,
|
|
559
|
+
"Denominator": Denominator,
|
|
560
|
+
# --- Number theory / special functions ---
|
|
561
|
+
"Chop": lambda f, c, solver_parameters, s: (
|
|
562
|
+
0 if abs(f(s[1], c)) < 1e-10 else f(s[1], c)
|
|
563
|
+
),
|
|
564
|
+
"Mod": lambda f, c, solver_parameters, s: f(s[1], c) % f(s[2], c),
|
|
565
|
+
"Clamp": Clamp,
|
|
566
|
+
"GCD": lambda f, c, solver_parameters, s: math.gcd(
|
|
567
|
+
int(f(s[1], c)), int(f(s[2], c))
|
|
568
|
+
),
|
|
569
|
+
"LCM": lambda f, c, solver_parameters, s: math.lcm(
|
|
570
|
+
int(f(s[1], c)), int(f(s[2], c))
|
|
571
|
+
),
|
|
572
|
+
"Factorial": lambda f, c, solver_parameters, s: math.factorial(int(f(s[1], c))),
|
|
573
|
+
"Binomial": lambda f, c, solver_parameters, s: math.comb(
|
|
574
|
+
int(f(s[1], c)), int(f(s[2], c))
|
|
575
|
+
),
|
|
576
|
+
"IsPrime": IsPrime,
|
|
577
|
+
"Erf": lambda f, c, solver_parameters, s: math.erf(f(s[1], c)),
|
|
578
|
+
"Erfc": lambda f, c, solver_parameters, s: math.erfc(f(s[1], c)),
|
|
579
|
+
# --- Number theory ---
|
|
580
|
+
"PowerMod": lambda f, c, solver_parameters, s: pow(
|
|
581
|
+
int(f(s[1], c)), int(f(s[2], c)), int(f(s[3], c))
|
|
582
|
+
),
|
|
583
|
+
"ModularInverse": lambda f, c, solver_parameters, s: pow(
|
|
584
|
+
int(f(s[1], c)), -1, int(f(s[2], c))
|
|
585
|
+
),
|
|
586
|
+
"IntegerSqrt": lambda f, c, solver_parameters, s: math.isqrt(int(f(s[1], c))),
|
|
587
|
+
"FactorInteger": FactorInteger,
|
|
588
|
+
"PrimeFactors": PrimeFactors,
|
|
589
|
+
"PrimeNu": PrimeNu,
|
|
590
|
+
"PrimeOmega": PrimeOmega,
|
|
591
|
+
"Radical": Radical,
|
|
592
|
+
"IsSquareFree": IsSquareFree,
|
|
593
|
+
"Divisors": Divisors,
|
|
594
|
+
"Sigma0": Sigma0,
|
|
595
|
+
"Sigma1": Sigma1,
|
|
596
|
+
"SigmaMinus1": SigmaMinus1,
|
|
597
|
+
"DivisorSigma": DivisorSigma,
|
|
598
|
+
"Divides": lambda f, c, solver_parameters, s: f(s[2], c) % f(s[1], c) == 0,
|
|
599
|
+
"Totient": Totient,
|
|
600
|
+
"IsPerfectPower": IsPerfectPower,
|
|
601
|
+
"NthPrime": NthPrime,
|
|
602
|
+
"NextPrime": NextPrime,
|
|
603
|
+
"PrimePi": PrimePi,
|
|
604
|
+
"ExtendedGCD": ExtendedGCD,
|
|
605
|
+
"ChineseRemainder": ChineseRemainder,
|
|
606
|
+
"CarmichaelLambda": CarmichaelLambda,
|
|
607
|
+
"JacobiSymbol": JacobiSymbol,
|
|
608
|
+
"LegendreSymbol": JacobiSymbol, # same algorithm when n is prime
|
|
609
|
+
"MultiplicativeOrder": MultiplicativeOrder,
|
|
610
|
+
"PrimitiveRoot": PrimitiveRoot,
|
|
611
|
+
"LucasL": LucasL,
|
|
612
|
+
"CatalanNumber": lambda f, c, solver_parameters, s: math.comb(
|
|
613
|
+
2 * int(f(s[1], c)), int(f(s[1], c))
|
|
614
|
+
)
|
|
615
|
+
// (int(f(s[1], c)) + 1),
|
|
616
|
+
"BernoulliB": BernoulliB,
|
|
617
|
+
"ContinuedFraction": ContinuedFraction,
|
|
618
|
+
"FromContinuedFraction": FromContinuedFraction,
|
|
619
|
+
"IntegerDigits": IntegerDigits,
|
|
620
|
+
"DigitCount": DigitCount,
|
|
621
|
+
"DigitSum": DigitSum,
|
|
622
|
+
"FromDigits": FromDigits,
|
|
623
|
+
"IsSquare": IsSquare,
|
|
624
|
+
"IsTriangular": IsTriangular,
|
|
625
|
+
"IsPentagonal": IsPentagonal,
|
|
626
|
+
"IsOctahedral": IsOctahedral,
|
|
627
|
+
"IsCenteredSquare": IsCenteredSquare,
|
|
628
|
+
"IsPerfect": IsPerfect,
|
|
629
|
+
"IsAbundant": IsAbundant,
|
|
630
|
+
"IsHappy": IsHappy,
|
|
631
|
+
# --- Special functions ---
|
|
632
|
+
"Gamma": lambda f, c, solver_parameters, s: math.gamma(f(s[1], c)),
|
|
633
|
+
"GammaLn": lambda f, c, solver_parameters, s: math.lgamma(f(s[1], c)),
|
|
634
|
+
"Beta": Beta,
|
|
635
|
+
"Factorial2": Factorial2,
|
|
636
|
+
"ErfInv": ErfInv,
|
|
637
|
+
"LambertW": LambertW,
|
|
638
|
+
"AGM": AGM,
|
|
639
|
+
"EllipticK": EllipticK,
|
|
640
|
+
"EllipticE": EllipticE,
|
|
641
|
+
"Hypergeometric1F1": Hypergeometric1F1,
|
|
642
|
+
"Hypergeometric2F1": Hypergeometric2F1,
|
|
643
|
+
"BesselJ": BesselJ,
|
|
644
|
+
"BesselY": BesselY,
|
|
645
|
+
"BesselI": BesselI,
|
|
646
|
+
"BesselK": BesselK,
|
|
647
|
+
"AiryAi": AiryAi,
|
|
648
|
+
"AiryBi": AiryBi,
|
|
649
|
+
"AiryAiPrime": AiryAiPrime,
|
|
650
|
+
"AiryBiPrime": AiryBiPrime,
|
|
651
|
+
"Zeta": Zeta,
|
|
652
|
+
"GammaRegularized": GammaRegularized,
|
|
653
|
+
"BetaRegularized": BetaRegularized,
|
|
654
|
+
# --- Combinatorics (trivial subset) ---
|
|
655
|
+
"Choose": lambda f, c, solver_parameters, s: math.comb(
|
|
656
|
+
int(f(s[1], c)), int(f(s[2], c))
|
|
657
|
+
),
|
|
658
|
+
"Fibonacci": Fibonacci,
|
|
659
|
+
"Multinomial": Multinomial,
|
|
660
|
+
"Subfactorial": Subfactorial,
|
|
661
|
+
"BellNumber": BellNumber,
|
|
662
|
+
"PowerSet": PowerSet,
|
|
663
|
+
"Permutations": Permutations,
|
|
664
|
+
"Combinations": Combinations,
|
|
665
|
+
"CartesianProduct": CartesianProduct,
|
|
666
|
+
# --- Core: structural introspection ---
|
|
667
|
+
"Head": Head,
|
|
668
|
+
"Tail": Tail,
|
|
669
|
+
"Hold": Hold,
|
|
670
|
+
"Identity": lambda f, c, solver_parameters, s: f(s[1], c),
|
|
671
|
+
"Type": Type,
|
|
672
|
+
"IsSame": IsSame,
|
|
673
|
+
"Same": IsSame, # see IsSame's docstring for the distinction CortexJS draws
|
|
674
|
+
# --- Boolean logic ---
|
|
675
|
+
"Xor": lambda f, c, solver_parameters, s: bool(f(s[1], c)) ^ bool(f(s[2], c)),
|
|
676
|
+
"Nand": lambda f, c, solver_parameters, s: not all(f(x, c) for x in s[1:]),
|
|
677
|
+
"Nor": lambda f, c, solver_parameters, s: not any(f(x, c) for x in s[1:]),
|
|
678
|
+
"Implies": lambda f, c, solver_parameters, s: (not f(s[1], c)) or bool(f(s[2], c)),
|
|
679
|
+
"Equivalent": lambda f, c, solver_parameters, s: bool(f(s[1], c))
|
|
680
|
+
== bool(f(s[2], c)),
|
|
681
|
+
# --- Statistics ---
|
|
682
|
+
"Variance": Variance,
|
|
683
|
+
"StandardDeviation": StandardDeviation,
|
|
684
|
+
"PopulationVariance": PopulationVariance,
|
|
685
|
+
"PopulationStandardDeviation": PopulationStandardDeviation,
|
|
686
|
+
"Mode": Mode,
|
|
687
|
+
"Quartiles": Quartiles,
|
|
688
|
+
"InterquartileRange": InterquartileRange,
|
|
689
|
+
"Covariance": Covariance,
|
|
690
|
+
"Correlation": Correlation,
|
|
691
|
+
"Skewness": Skewness,
|
|
692
|
+
"Kurtosis": Kurtosis,
|
|
693
|
+
"LinearRegression": LinearRegression,
|
|
694
|
+
"PolynomialFit": PolynomialFit,
|
|
695
|
+
"NormalDistribution": NormalDistribution,
|
|
696
|
+
"BinomialDistribution": BinomialDistribution,
|
|
697
|
+
"PoissonDistribution": PoissonDistribution,
|
|
698
|
+
"UniformDistribution": UniformDistribution,
|
|
699
|
+
"ExponentialDistribution": ExponentialDistribution,
|
|
700
|
+
"PDF": PDF,
|
|
701
|
+
"CDF": CDF,
|
|
702
|
+
"Quantile": Quantile,
|
|
703
|
+
# --- Collections ---
|
|
704
|
+
"First": First,
|
|
705
|
+
"Second": Second,
|
|
706
|
+
"Third": Third,
|
|
707
|
+
"Last": Last,
|
|
708
|
+
"Rest": Rest,
|
|
709
|
+
"Most": Most,
|
|
710
|
+
"Reverse": Reverse,
|
|
711
|
+
"Sort": Sort,
|
|
712
|
+
"IsEmpty": IsEmpty,
|
|
713
|
+
"Range": Range,
|
|
714
|
+
"Join": Join,
|
|
715
|
+
"Unique": Unique,
|
|
716
|
+
"Zip": Zip,
|
|
717
|
+
"At": At,
|
|
718
|
+
"Take": Take,
|
|
719
|
+
"Drop": Drop,
|
|
720
|
+
"TakeWhile": TakeWhile,
|
|
721
|
+
"DropWhile": DropWhile,
|
|
722
|
+
"Contains": Contains,
|
|
723
|
+
"IndexOf": IndexOf,
|
|
724
|
+
"IndexWhere": IndexWhere,
|
|
725
|
+
"Find": Find,
|
|
726
|
+
"CountIf": CountIf,
|
|
727
|
+
"Position": Position,
|
|
728
|
+
"RotateLeft": RotateLeft,
|
|
729
|
+
"RotateRight": RotateRight,
|
|
730
|
+
"MaxBy": MaxBy,
|
|
731
|
+
"MinBy": MinBy,
|
|
732
|
+
"ArgMax": ArgMax,
|
|
733
|
+
"ArgMin": ArgMin,
|
|
734
|
+
"Ordering": Ordering,
|
|
735
|
+
"FlatMap": FlatMap,
|
|
736
|
+
"Scan": Scan,
|
|
737
|
+
"Differences": Differences,
|
|
738
|
+
"Fold": Fold,
|
|
739
|
+
"Dedup": Dedup,
|
|
740
|
+
"Append": Appended, # CortexJS name for Appended
|
|
741
|
+
"Insert": Insert,
|
|
742
|
+
"DeleteAt": DeleteAt,
|
|
743
|
+
"ReplaceAt": ReplaceAt,
|
|
744
|
+
"Partition": Partition,
|
|
745
|
+
"Chunk": Chunk,
|
|
746
|
+
"GroupBy": GroupBy,
|
|
747
|
+
"ChunkBy": ChunkBy,
|
|
748
|
+
"Tally": Tally,
|
|
749
|
+
# --- Set algebra (over Array - no dedicated Set type) ---
|
|
750
|
+
"Union": Union,
|
|
751
|
+
"Intersection": Intersection,
|
|
752
|
+
"SetMinus": SetMinus,
|
|
753
|
+
"SymmetricDifference": SymmetricDifference,
|
|
754
|
+
"Subset": Subset,
|
|
755
|
+
"SubsetEqual": SubsetEqual,
|
|
756
|
+
"Superset": Superset,
|
|
757
|
+
"SupersetEqual": SupersetEqual,
|
|
758
|
+
"NotSubset": NotSubset,
|
|
759
|
+
"NotSuperset": NotSuperset,
|
|
760
|
+
"Interval": Interval,
|
|
761
|
+
"Open": Open,
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def create_mathjson_solver(
|
|
766
|
+
solver_parameters: dict[str, MathJSONExpression],
|
|
767
|
+
legacy_v1: bool = False,
|
|
768
|
+
blacklist: Iterable[str] | None = None,
|
|
769
|
+
) -> Callable[[MathJSONExpression], _Any]:
|
|
770
|
+
"""
|
|
771
|
+
`blacklist`, if given, is an iterable of construct names (e.g.
|
|
772
|
+
`["PowerSet", "Permutations"]`) that this solver instance refuses to
|
|
773
|
+
evaluate - deployments can disable individual constructs they don't
|
|
774
|
+
want available for their expression sources, independent of what
|
|
775
|
+
the library implements. Attempting to use a blacklisted construct
|
|
776
|
+
raises `MathJSONException` (wrapping `PermissionError`) rather than
|
|
777
|
+
evaluating it or silently ignoring it. A name that isn't an actual
|
|
778
|
+
construct has no effect (not validated against the known-construct
|
|
779
|
+
list - a deliberate simplicity trade-off, not an oversight).
|
|
780
|
+
|
|
781
|
+
This is a resource/access *policy* control, not a substitute for a
|
|
782
|
+
construct being safe to run at all - e.g. the combinatorial
|
|
783
|
+
enumeration functions (`PowerSet`, `Permutations`, `Combinations`,
|
|
784
|
+
`CartesianProduct`) have no built-in output-size limit, so a
|
|
785
|
+
deployment accepting untrusted expressions should blacklist them
|
|
786
|
+
(or any other construct it doesn't want exposed) rather than assume
|
|
787
|
+
every construct is safe by default for every threat model.
|
|
788
|
+
"""
|
|
789
|
+
blacklist = frozenset(blacklist) if blacklist else frozenset()
|
|
790
|
+
|
|
791
|
+
def f(s, *args):
|
|
792
|
+
# Leaf values never touch `c` at all - check them before doing
|
|
793
|
+
# anything with it, since leaves vastly outnumber interior nodes
|
|
794
|
+
# in any real expression tree.
|
|
358
795
|
if isinstance(s, numbers.Number):
|
|
359
796
|
return s
|
|
360
797
|
# CortexJS represents the boolean literals as the bare symbols
|
|
@@ -366,2173 +803,31 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
|
|
|
366
803
|
# solver parameter or local variable.
|
|
367
804
|
if s == "True" or s == "False":
|
|
368
805
|
return s == "True"
|
|
806
|
+
# `c` is passed through by reference, not copied, here or at any
|
|
807
|
+
# of the call sites below - almost every construct only reads
|
|
808
|
+
# it. The few constructs that introduce new bindings (Constants,
|
|
809
|
+
# Reduce's legacy accumulator form, TrapezoidalIntegrate) are
|
|
810
|
+
# responsible for making their own `c = dict(c)` copy before
|
|
811
|
+
# writing into it, the same way `_apply_fn` already does for
|
|
812
|
+
# `Function` - so a written binding is visible to whatever that
|
|
813
|
+
# construct evaluates internally, but never leaks back into the
|
|
814
|
+
# caller's scope once the construct returns.
|
|
815
|
+
c = args[0] if args else {}
|
|
369
816
|
if isinstance(s, list):
|
|
370
|
-
|
|
371
|
-
def Arr(s):
|
|
372
|
-
return s
|
|
373
|
-
|
|
374
|
-
def Add(s):
|
|
375
|
-
l_res = []
|
|
376
|
-
tmp = 0
|
|
377
|
-
for i, x in enumerate(s[1:]):
|
|
378
|
-
res = f(x, c)
|
|
379
|
-
if is_numeric(res):
|
|
380
|
-
res = float(res)
|
|
381
|
-
if i == 0:
|
|
382
|
-
tmp = res
|
|
383
|
-
else:
|
|
384
|
-
# Handle datetime string + timedelta
|
|
385
|
-
if isinstance(res, datetime.timedelta):
|
|
386
|
-
tmp = _try_parse_datetime(tmp)
|
|
387
|
-
elif isinstance(tmp, datetime.timedelta):
|
|
388
|
-
res = _try_parse_datetime(res)
|
|
389
|
-
try:
|
|
390
|
-
tmp = tmp + res
|
|
391
|
-
except TypeError:
|
|
392
|
-
pass
|
|
393
|
-
|
|
394
|
-
# Convert datetime result back to string
|
|
395
|
-
if isinstance(tmp, (datetime.datetime, datetime.date)):
|
|
396
|
-
return tmp.isoformat()
|
|
397
|
-
return tmp
|
|
398
|
-
|
|
399
|
-
# tmp = 0
|
|
400
|
-
# for i, x in enumerate(l):
|
|
401
|
-
# if i == 0:
|
|
402
|
-
# tmp = x
|
|
403
|
-
# else:
|
|
404
|
-
# tmp = tmp + x
|
|
405
|
-
# return tmp
|
|
406
|
-
|
|
407
|
-
# def Sum(s):
|
|
408
|
-
# l_res = []
|
|
409
|
-
# for x in s[1:]:
|
|
410
|
-
# res = f(x, c)
|
|
411
|
-
# if isinstance(res, list):
|
|
412
|
-
# l_res.append(sum([xx for xx in res[1:]]))
|
|
413
|
-
# else:
|
|
414
|
-
# l_res.append(res)
|
|
415
|
-
# return sum(l_res)
|
|
416
|
-
|
|
417
|
-
def Sum(s):
|
|
418
|
-
l_res = ["Array"]
|
|
419
|
-
for x in s[1:]:
|
|
420
|
-
res = f(x, c)
|
|
421
|
-
if isinstance(res, list):
|
|
422
|
-
l_res.append(Add(["Array"] + [xx for xx in res[1:]]))
|
|
423
|
-
else:
|
|
424
|
-
l_res.append(res)
|
|
425
|
-
return Add(l_res)
|
|
426
|
-
|
|
427
|
-
def Subtract(s):
|
|
428
|
-
values = [f(x, c) for x in s[1:]]
|
|
429
|
-
# Convert datetime strings if we're dealing with timedelta
|
|
430
|
-
converted = []
|
|
431
|
-
for i, v in enumerate(values):
|
|
432
|
-
if isinstance(v, datetime.timedelta):
|
|
433
|
-
converted.append(v)
|
|
434
|
-
elif any(isinstance(other, datetime.timedelta) for other in values):
|
|
435
|
-
converted.append(_try_parse_datetime(v))
|
|
436
|
-
else:
|
|
437
|
-
converted.append(v)
|
|
438
|
-
result = reduce(lambda a, b: a - b, converted)
|
|
439
|
-
if isinstance(result, (datetime.datetime, datetime.date)):
|
|
440
|
-
return result.isoformat()
|
|
441
|
-
return result
|
|
442
|
-
|
|
443
|
-
def Max(s):
|
|
444
|
-
args = s[1:]
|
|
445
|
-
if len(args) == 1:
|
|
446
|
-
if isinstance(args[0], str):
|
|
447
|
-
return max(
|
|
448
|
-
[f(x, c) for x in f(args[0], c) if is_numeric(f(x, c))]
|
|
449
|
-
)
|
|
450
|
-
else:
|
|
451
|
-
return max(
|
|
452
|
-
[f(x, c) for x in args[0][1:] if is_numeric(f(x, c))]
|
|
453
|
-
)
|
|
454
|
-
else:
|
|
455
|
-
# CortexJS-style variadic form: ["Max", a, b, c, ...]
|
|
456
|
-
return max([f(x, c) for x in args])
|
|
457
|
-
|
|
458
|
-
def Min(s):
|
|
459
|
-
args = s[1:]
|
|
460
|
-
if len(args) == 1:
|
|
461
|
-
if isinstance(args[0], str):
|
|
462
|
-
return min(
|
|
463
|
-
[f(x, c) for x in f(args[0], c) if is_numeric(f(x, c))]
|
|
464
|
-
)
|
|
465
|
-
else:
|
|
466
|
-
return min(
|
|
467
|
-
[f(x, c) for x in args[0][1:] if is_numeric(f(x, c))]
|
|
468
|
-
)
|
|
469
|
-
else:
|
|
470
|
-
# CortexJS-style variadic form: ["Min", a, b, c, ...]
|
|
471
|
-
return min([f(x, c) for x in args])
|
|
472
|
-
|
|
473
|
-
def Average(s):
|
|
474
|
-
if isinstance(s[1], str):
|
|
475
|
-
# A reference to "answer" has been passed
|
|
476
|
-
s_ = [float(f(x, c)) for x in f(s[1], c) if is_numeric(f(x, c))]
|
|
477
|
-
else:
|
|
478
|
-
s_ = [float(f(x, c)) for x in s[1][1:] if is_numeric(f(x, c))]
|
|
479
|
-
try:
|
|
480
|
-
return sum(s_) / len(s_)
|
|
481
|
-
except ZeroDivisionError:
|
|
482
|
-
return None
|
|
483
|
-
|
|
484
|
-
def Median(s):
|
|
485
|
-
if isinstance(s[1], str):
|
|
486
|
-
return median([f(x, c) for x in f(s[1], c) if is_numeric(f(x, c))])
|
|
487
|
-
else:
|
|
488
|
-
return median([f(x, c) for x in s[1][1:] if is_numeric(f(x, c))])
|
|
489
|
-
|
|
490
|
-
def Length(s):
|
|
491
|
-
if isinstance(s[1], str):
|
|
492
|
-
return len([x for x in f(s[1], c)][1:])
|
|
493
|
-
else:
|
|
494
|
-
return len([x for x in s[1][1:]])
|
|
495
|
-
|
|
496
|
-
def Clamp(s):
|
|
497
|
-
"""
|
|
498
|
-
["Clamp", value] or ["Clamp", value, lower, upper]
|
|
499
|
-
Bounds `value` between `lower` (default -1) and `upper` (default 1),
|
|
500
|
-
matching CortexJS `Clamp`.
|
|
501
|
-
"""
|
|
502
|
-
value = f(s[1], c)
|
|
503
|
-
lower = f(s[2], c) if len(s) > 2 else -1
|
|
504
|
-
upper = f(s[3], c) if len(s) > 3 else 1
|
|
505
|
-
return max(lower, min(upper, value))
|
|
506
|
-
|
|
507
|
-
def _arr_vals(s):
|
|
508
|
-
lst = f(s[1], c)
|
|
509
|
-
if not (isinstance(lst, list) and lst[0] == "Array"):
|
|
510
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
511
|
-
return [f(x, c) for x in lst[1:]]
|
|
512
|
-
|
|
513
|
-
def First(s):
|
|
514
|
-
return _arr_vals(s)[0]
|
|
515
|
-
|
|
516
|
-
def Second(s):
|
|
517
|
-
return _arr_vals(s)[1]
|
|
518
|
-
|
|
519
|
-
def Third(s):
|
|
520
|
-
return _arr_vals(s)[2]
|
|
521
|
-
|
|
522
|
-
def Last(s):
|
|
523
|
-
return _arr_vals(s)[-1]
|
|
524
|
-
|
|
525
|
-
def Rest(s):
|
|
526
|
-
return ["Array"] + _arr_vals(s)[1:]
|
|
527
|
-
|
|
528
|
-
def Most(s):
|
|
529
|
-
return ["Array"] + _arr_vals(s)[:-1]
|
|
530
|
-
|
|
531
|
-
def Reverse(s):
|
|
532
|
-
return ["Array"] + list(reversed(_arr_vals(s)))
|
|
533
|
-
|
|
534
|
-
def Sort(s):
|
|
535
|
-
return ["Array"] + sorted(_arr_vals(s))
|
|
536
|
-
|
|
537
|
-
def IsEmpty(s):
|
|
538
|
-
lst = f(s[1], c)
|
|
539
|
-
if not (isinstance(lst, list) and lst[0] == "Array"):
|
|
540
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
541
|
-
return len(lst) <= 1
|
|
542
|
-
|
|
543
|
-
def Range(s):
|
|
544
|
-
"""
|
|
545
|
-
CortexJS-compatible `Range`:
|
|
546
|
-
["Range", upper] -> 1..upper (inclusive)
|
|
547
|
-
["Range", lower, upper] -> lower..upper (inclusive)
|
|
548
|
-
["Range", lower, upper, step] -> lower..upper (inclusive), stepped
|
|
549
|
-
Distinct from `GenerateRange`, which is 0-indexed and exclusive at
|
|
550
|
-
the upper end.
|
|
551
|
-
"""
|
|
552
|
-
if len(s) == 2:
|
|
553
|
-
return ["Array"] + list(range(1, int(f(s[1], c)) + 1))
|
|
554
|
-
elif len(s) == 3:
|
|
555
|
-
lo, hi = int(f(s[1], c)), int(f(s[2], c))
|
|
556
|
-
return ["Array"] + list(range(lo, hi + 1))
|
|
557
|
-
else:
|
|
558
|
-
lo, hi, step = (
|
|
559
|
-
int(f(s[1], c)),
|
|
560
|
-
int(f(s[2], c)),
|
|
561
|
-
int(f(s[3], c)),
|
|
562
|
-
)
|
|
563
|
-
return ["Array"] + list(
|
|
564
|
-
range(lo, hi + 1 if step > 0 else hi - 1, step)
|
|
565
|
-
)
|
|
566
|
-
|
|
567
|
-
def Join(s):
|
|
568
|
-
"""
|
|
569
|
-
["Join", array1, array2, ...]
|
|
570
|
-
Concatenates the given arrays.
|
|
571
|
-
"""
|
|
572
|
-
result = ["Array"]
|
|
573
|
-
for arg in s[1:]:
|
|
574
|
-
lst = f(arg, c)
|
|
575
|
-
if not (isinstance(lst, list) and lst[0] == "Array"):
|
|
576
|
-
raise ValueError("All parameters must be arrays.")
|
|
577
|
-
result += [f(x, c) for x in lst[1:]]
|
|
578
|
-
return result
|
|
579
|
-
|
|
580
|
-
def Unique(s):
|
|
581
|
-
seen = []
|
|
582
|
-
for x in _arr_vals(s):
|
|
583
|
-
if x not in seen:
|
|
584
|
-
seen.append(x)
|
|
585
|
-
return ["Array"] + seen
|
|
586
|
-
|
|
587
|
-
def Zip(s):
|
|
588
|
-
lists = [[f(x, c) for x in f(arg, c)[1:]] for arg in s[1:]]
|
|
589
|
-
return ["Array"] + [["Array", a, b] for a, b in zip(*lists)]
|
|
590
|
-
|
|
591
|
-
def At(s):
|
|
592
|
-
"""
|
|
593
|
-
["At", array, index]
|
|
594
|
-
1-indexed element access (CortexJS `At`), with negative indexes
|
|
595
|
-
counting from the end.
|
|
596
|
-
"""
|
|
597
|
-
vals = _arr_vals(s)
|
|
598
|
-
idx = int(f(s[2], c))
|
|
599
|
-
if idx > 0:
|
|
600
|
-
return vals[idx - 1]
|
|
601
|
-
else:
|
|
602
|
-
return vals[idx]
|
|
603
|
-
|
|
604
|
-
def Take(s):
|
|
605
|
-
"""
|
|
606
|
-
["Take", array, n]
|
|
607
|
-
First `n` elements if n >= 0; last `n` elements if n < 0.
|
|
608
|
-
Distinct from `Slice`, which takes an explicit [start, end)
|
|
609
|
-
range instead of a count.
|
|
610
|
-
"""
|
|
611
|
-
vals = _arr_vals(s)
|
|
612
|
-
n = int(f(s[2], c))
|
|
613
|
-
if n >= 0:
|
|
614
|
-
return ["Array"] + vals[:n]
|
|
615
|
-
return ["Array"] + vals[n:]
|
|
616
|
-
|
|
617
|
-
def Drop(s):
|
|
618
|
-
"""
|
|
619
|
-
["Drop", array, n]
|
|
620
|
-
All elements except the first `n` if n >= 0; except the
|
|
621
|
-
last `n` if n < 0.
|
|
622
|
-
"""
|
|
623
|
-
vals = _arr_vals(s)
|
|
624
|
-
n = int(f(s[2], c))
|
|
625
|
-
if n >= 0:
|
|
626
|
-
return ["Array"] + vals[n:]
|
|
627
|
-
return ["Array"] + vals[:n]
|
|
628
|
-
|
|
629
|
-
def TakeWhile(s):
|
|
630
|
-
"""
|
|
631
|
-
["TakeWhile", array, predicate]
|
|
632
|
-
Elements from the start, up to (excluding) the first one
|
|
633
|
-
for which `predicate` is false.
|
|
634
|
-
"""
|
|
635
|
-
result = []
|
|
636
|
-
for v in _arr_vals(s):
|
|
637
|
-
if not _apply_fn(s[2], [v]):
|
|
638
|
-
break
|
|
639
|
-
result.append(v)
|
|
640
|
-
return ["Array"] + result
|
|
641
|
-
|
|
642
|
-
def DropWhile(s):
|
|
643
|
-
"""
|
|
644
|
-
["DropWhile", array, predicate]
|
|
645
|
-
Remaining elements from (and including) the first one for
|
|
646
|
-
which `predicate` is false.
|
|
647
|
-
"""
|
|
648
|
-
vals = _arr_vals(s)
|
|
649
|
-
i = 0
|
|
650
|
-
while i < len(vals) and _apply_fn(s[2], [vals[i]]):
|
|
651
|
-
i += 1
|
|
652
|
-
return ["Array"] + vals[i:]
|
|
653
|
-
|
|
654
|
-
def Contains(s):
|
|
655
|
-
"""
|
|
656
|
-
["Contains", array, value]
|
|
657
|
-
Whether `value` occurs in `array`. CortexJS argument order
|
|
658
|
-
(collection first) - the existing `In` takes them the
|
|
659
|
-
other way round (`["In", value, collection]`).
|
|
660
|
-
"""
|
|
661
|
-
return f(s[2], c) in _arr_vals(s)
|
|
662
|
-
|
|
663
|
-
def IndexOf(s):
|
|
664
|
-
"""
|
|
665
|
-
["IndexOf", array, value]
|
|
666
|
-
1-indexed position of the first occurrence of `value`, or
|
|
667
|
-
None if it doesn't occur.
|
|
668
|
-
"""
|
|
669
|
-
vals = _arr_vals(s)
|
|
670
|
-
value = f(s[2], c)
|
|
671
|
-
try:
|
|
672
|
-
return vals.index(value) + 1
|
|
673
|
-
except ValueError:
|
|
674
|
-
return None
|
|
675
|
-
|
|
676
|
-
def IndexWhere(s):
|
|
677
|
-
"""
|
|
678
|
-
["IndexWhere", array, predicate]
|
|
679
|
-
1-indexed position of the first element for which
|
|
680
|
-
`predicate` is true, or None if none match.
|
|
681
|
-
"""
|
|
682
|
-
for i, v in enumerate(_arr_vals(s)):
|
|
683
|
-
if _apply_fn(s[2], [v]):
|
|
684
|
-
return i + 1
|
|
685
|
-
return None
|
|
686
|
-
|
|
687
|
-
def Find(s):
|
|
688
|
-
"""
|
|
689
|
-
["Find", array, predicate]
|
|
690
|
-
The first element for which `predicate` is true, or None
|
|
691
|
-
if none match.
|
|
692
|
-
"""
|
|
693
|
-
for v in _arr_vals(s):
|
|
694
|
-
if _apply_fn(s[2], [v]):
|
|
695
|
-
return v
|
|
696
|
-
return None
|
|
697
|
-
|
|
698
|
-
def CountIf(s):
|
|
699
|
-
"""
|
|
700
|
-
["CountIf", array, predicate]
|
|
701
|
-
Count of elements for which `predicate` is true.
|
|
702
|
-
"""
|
|
703
|
-
return sum(1 for v in _arr_vals(s) if _apply_fn(s[2], [v]))
|
|
704
|
-
|
|
705
|
-
def Position(s):
|
|
706
|
-
"""
|
|
707
|
-
["Position", array, predicate]
|
|
708
|
-
Array of the 1-indexed positions of every element for
|
|
709
|
-
which `predicate` is true.
|
|
710
|
-
"""
|
|
711
|
-
return ["Array"] + [
|
|
712
|
-
i + 1
|
|
713
|
-
for i, v in enumerate(_arr_vals(s))
|
|
714
|
-
if _apply_fn(s[2], [v])
|
|
715
|
-
]
|
|
716
|
-
|
|
717
|
-
def RotateLeft(s):
|
|
718
|
-
"""
|
|
719
|
-
["RotateLeft", array, n]
|
|
720
|
-
Circularly shifts `array` left by `n` positions.
|
|
721
|
-
"""
|
|
722
|
-
vals = _arr_vals(s)
|
|
723
|
-
if not vals:
|
|
724
|
-
return ["Array"]
|
|
725
|
-
n = int(f(s[2], c)) % len(vals)
|
|
726
|
-
return ["Array"] + vals[n:] + vals[:n]
|
|
727
|
-
|
|
728
|
-
def RotateRight(s):
|
|
729
|
-
"""
|
|
730
|
-
["RotateRight", array, n]
|
|
731
|
-
Circularly shifts `array` right by `n` positions.
|
|
732
|
-
"""
|
|
733
|
-
vals = _arr_vals(s)
|
|
734
|
-
if not vals:
|
|
735
|
-
return ["Array"]
|
|
736
|
-
n = int(f(s[2], c)) % len(vals)
|
|
737
|
-
if n == 0:
|
|
738
|
-
return ["Array"] + vals
|
|
739
|
-
return ["Array"] + vals[-n:] + vals[:-n]
|
|
740
|
-
|
|
741
|
-
def MaxBy(s):
|
|
742
|
-
"""
|
|
743
|
-
["MaxBy", array, function]
|
|
744
|
-
The element of `array` for which `function(element)` is
|
|
745
|
-
largest.
|
|
746
|
-
"""
|
|
747
|
-
return max(_arr_vals(s), key=lambda v: _apply_fn(s[2], [v]))
|
|
748
|
-
|
|
749
|
-
def MinBy(s):
|
|
750
|
-
"""
|
|
751
|
-
["MinBy", array, function]
|
|
752
|
-
The element of `array` for which `function(element)` is
|
|
753
|
-
smallest.
|
|
754
|
-
"""
|
|
755
|
-
return min(_arr_vals(s), key=lambda v: _apply_fn(s[2], [v]))
|
|
756
|
-
|
|
757
|
-
def ArgMax(s):
|
|
758
|
-
"""
|
|
759
|
-
["ArgMax", array]
|
|
760
|
-
1-indexed position of the largest element.
|
|
761
|
-
"""
|
|
762
|
-
vals = _arr_vals(s)
|
|
763
|
-
return max(range(len(vals)), key=lambda i: vals[i]) + 1
|
|
764
|
-
|
|
765
|
-
def ArgMin(s):
|
|
766
|
-
"""
|
|
767
|
-
["ArgMin", array]
|
|
768
|
-
1-indexed position of the smallest element.
|
|
769
|
-
"""
|
|
770
|
-
vals = _arr_vals(s)
|
|
771
|
-
return min(range(len(vals)), key=lambda i: vals[i]) + 1
|
|
772
|
-
|
|
773
|
-
def Ordering(s):
|
|
774
|
-
"""
|
|
775
|
-
["Ordering", array]
|
|
776
|
-
Array of the 1-indexed positions that would put `array`
|
|
777
|
-
in ascending order.
|
|
778
|
-
"""
|
|
779
|
-
vals = _arr_vals(s)
|
|
780
|
-
return ["Array"] + [
|
|
781
|
-
i + 1 for i in sorted(range(len(vals)), key=lambda i: vals[i])
|
|
782
|
-
]
|
|
783
|
-
|
|
784
|
-
def FlatMap(s):
|
|
785
|
-
"""
|
|
786
|
-
["FlatMap", array, function]
|
|
787
|
-
Applies `function` to each element (as with `Map`) and
|
|
788
|
-
flattens one level of the results - each result that is
|
|
789
|
-
itself an array is spliced in, others are kept as-is -
|
|
790
|
-
into a single array.
|
|
791
|
-
"""
|
|
792
|
-
result = ["Array"]
|
|
793
|
-
for v in _arr_vals(s):
|
|
794
|
-
mapped = _apply_fn(s[2], [v])
|
|
795
|
-
if isinstance(mapped, list) and mapped and mapped[0] == "Array":
|
|
796
|
-
result += mapped[1:]
|
|
797
|
-
else:
|
|
798
|
-
result.append(mapped)
|
|
799
|
-
return result
|
|
800
|
-
|
|
801
|
-
def Scan(s):
|
|
802
|
-
"""
|
|
803
|
-
["Scan", array, function] or ["Scan", array, function, initial]
|
|
804
|
-
Like `Reduce`'s CortexJS form (`function` applied as
|
|
805
|
-
`function(accumulator, current)`), but returns an array of
|
|
806
|
-
every intermediate accumulator value, including the seed,
|
|
807
|
-
instead of just the final one.
|
|
808
|
-
"""
|
|
809
|
-
vals = _arr_vals(s)
|
|
810
|
-
fn_expr = s[2]
|
|
811
|
-
if len(s) == 4:
|
|
812
|
-
acc = f(s[3], c)
|
|
813
|
-
remaining = vals
|
|
814
|
-
else:
|
|
815
|
-
if not vals:
|
|
816
|
-
raise ValueError(
|
|
817
|
-
"'Scan' on an empty collection requires an initial value."
|
|
818
|
-
)
|
|
819
|
-
acc = vals[0]
|
|
820
|
-
remaining = vals[1:]
|
|
821
|
-
result = ["Array", acc]
|
|
822
|
-
for v in remaining:
|
|
823
|
-
acc = _apply_fn(fn_expr, [acc, v])
|
|
824
|
-
result.append(acc)
|
|
825
|
-
return result
|
|
826
|
-
|
|
827
|
-
def Differences(s):
|
|
828
|
-
"""
|
|
829
|
-
["Differences", array]
|
|
830
|
-
Array of successive differences: element[i+1] - element[i].
|
|
831
|
-
"""
|
|
832
|
-
vals = _arr_vals(s)
|
|
833
|
-
return ["Array"] + [b - a for a, b in zip(vals, vals[1:])]
|
|
834
|
-
|
|
835
|
-
def Fold(s):
|
|
836
|
-
"""
|
|
837
|
-
["Fold", function, array] or ["Fold", function, array, initial]
|
|
838
|
-
The function-first form of `Reduce`'s CortexJS calling
|
|
839
|
-
convention (`["Reduce", array, function, ...]`) - same
|
|
840
|
-
behaviour, arguments swapped.
|
|
841
|
-
"""
|
|
842
|
-
if len(s) == 3:
|
|
843
|
-
return Reduce(["Reduce", s[2], s[1]])
|
|
844
|
-
return Reduce(["Reduce", s[2], s[1], s[3]])
|
|
845
|
-
|
|
846
|
-
def Dedup(s):
|
|
847
|
-
"""
|
|
848
|
-
["Dedup", array]
|
|
849
|
-
Removes only *consecutive* duplicate elements - distinct
|
|
850
|
-
from `Unique`, which removes every duplicate regardless of
|
|
851
|
-
position.
|
|
852
|
-
"""
|
|
853
|
-
result = []
|
|
854
|
-
for v in _arr_vals(s):
|
|
855
|
-
if not result or result[-1] != v:
|
|
856
|
-
result.append(v)
|
|
857
|
-
return ["Array"] + result
|
|
858
|
-
|
|
859
|
-
def Insert(s):
|
|
860
|
-
"""
|
|
861
|
-
["Insert", array, index, value]
|
|
862
|
-
Inserts `value` at the 1-indexed `index` (CortexJS
|
|
863
|
-
convention, matching `At`); negative indexes count from
|
|
864
|
-
the end.
|
|
865
|
-
"""
|
|
866
|
-
vals = _arr_vals(s)
|
|
867
|
-
idx = int(f(s[2], c))
|
|
868
|
-
value = f(s[3], c)
|
|
869
|
-
vals.insert(idx - 1 if idx > 0 else idx, value)
|
|
870
|
-
return ["Array"] + vals
|
|
871
|
-
|
|
872
|
-
def DeleteAt(s):
|
|
873
|
-
"""
|
|
874
|
-
["DeleteAt", array, index]
|
|
875
|
-
Removes the element at the 1-indexed `index`; negative
|
|
876
|
-
indexes count from the end.
|
|
877
|
-
"""
|
|
878
|
-
vals = _arr_vals(s)
|
|
879
|
-
idx = int(f(s[2], c))
|
|
880
|
-
del vals[idx - 1 if idx > 0 else idx]
|
|
881
|
-
return ["Array"] + vals
|
|
882
|
-
|
|
883
|
-
def ReplaceAt(s):
|
|
884
|
-
"""
|
|
885
|
-
["ReplaceAt", array, index, value]
|
|
886
|
-
Replaces the element at the 1-indexed `index` with
|
|
887
|
-
`value`; negative indexes count from the end.
|
|
888
|
-
"""
|
|
889
|
-
vals = _arr_vals(s)
|
|
890
|
-
idx = int(f(s[2], c))
|
|
891
|
-
value = f(s[3], c)
|
|
892
|
-
vals[idx - 1 if idx > 0 else idx] = value
|
|
893
|
-
return ["Array"] + vals
|
|
894
|
-
|
|
895
|
-
def Partition(s):
|
|
896
|
-
"""
|
|
897
|
-
["Partition", array, size]
|
|
898
|
-
Splits `array` into consecutive chunks of length `size`
|
|
899
|
-
(the last chunk may be shorter). Distinct from `Chunk`,
|
|
900
|
-
which instead takes the number of groups to split into.
|
|
901
|
-
"""
|
|
902
|
-
vals = _arr_vals(s)
|
|
903
|
-
size = int(f(s[2], c))
|
|
904
|
-
if size <= 0:
|
|
905
|
-
raise ValueError("'Partition' size must be a positive integer.")
|
|
906
|
-
return ["Array"] + [
|
|
907
|
-
["Array"] + vals[i : i + size] for i in range(0, len(vals), size)
|
|
908
|
-
]
|
|
909
|
-
|
|
910
|
-
def Chunk(s):
|
|
911
|
-
"""
|
|
912
|
-
["Chunk", array, n]
|
|
913
|
-
Splits `array` into `n` roughly equal-sized consecutive
|
|
914
|
-
groups.
|
|
915
|
-
"""
|
|
916
|
-
vals = _arr_vals(s)
|
|
917
|
-
n = int(f(s[2], c))
|
|
918
|
-
if n <= 0:
|
|
919
|
-
raise ValueError("'Chunk' group count must be a positive integer.")
|
|
920
|
-
base, extra = divmod(len(vals), n)
|
|
921
|
-
result, start = [], 0
|
|
922
|
-
for i in range(n):
|
|
923
|
-
size = base + (1 if i < extra else 0)
|
|
924
|
-
result.append(["Array"] + vals[start : start + size])
|
|
925
|
-
start += size
|
|
926
|
-
return ["Array"] + result
|
|
927
|
-
|
|
928
|
-
def GroupBy(s):
|
|
929
|
-
"""
|
|
930
|
-
["GroupBy", array, function]
|
|
931
|
-
Groups elements of `array` by `function(element)`, in
|
|
932
|
-
order of first appearance of each key. Returns an array of
|
|
933
|
-
[key, group] pairs - there's no dedicated `Dictionary`
|
|
934
|
-
type in this solver.
|
|
935
|
-
"""
|
|
936
|
-
order = []
|
|
937
|
-
groups = {}
|
|
938
|
-
for v in _arr_vals(s):
|
|
939
|
-
k = _apply_fn(s[2], [v])
|
|
940
|
-
hk = tuple(k) if isinstance(k, list) else k
|
|
941
|
-
if hk not in groups:
|
|
942
|
-
order.append((hk, k))
|
|
943
|
-
groups[hk] = []
|
|
944
|
-
groups[hk].append(v)
|
|
945
|
-
return ["Array"] + [
|
|
946
|
-
["Array", k, ["Array"] + groups[hk]] for hk, k in order
|
|
947
|
-
]
|
|
948
|
-
|
|
949
|
-
def ChunkBy(s):
|
|
950
|
-
"""
|
|
951
|
-
["ChunkBy", array, function]
|
|
952
|
-
Splits `array` into consecutive runs sharing the same
|
|
953
|
-
`function(element)` key - unlike `GroupBy`, runs are not
|
|
954
|
-
merged across non-adjacent occurrences of the same key.
|
|
955
|
-
"""
|
|
956
|
-
vals = _arr_vals(s)
|
|
957
|
-
if not vals:
|
|
958
|
-
return ["Array"]
|
|
959
|
-
result = []
|
|
960
|
-
current = [vals[0]]
|
|
961
|
-
current_key = _apply_fn(s[2], [vals[0]])
|
|
962
|
-
for v in vals[1:]:
|
|
963
|
-
k = _apply_fn(s[2], [v])
|
|
964
|
-
if k == current_key:
|
|
965
|
-
current.append(v)
|
|
966
|
-
else:
|
|
967
|
-
result.append(["Array"] + current)
|
|
968
|
-
current, current_key = [v], k
|
|
969
|
-
result.append(["Array"] + current)
|
|
970
|
-
return ["Array"] + result
|
|
971
|
-
|
|
972
|
-
def Tally(s):
|
|
973
|
-
"""
|
|
974
|
-
["Tally", array]
|
|
975
|
-
Counts occurrences of each distinct element, in order of
|
|
976
|
-
first appearance. Returns an array of [value, count]
|
|
977
|
-
pairs.
|
|
978
|
-
"""
|
|
979
|
-
order = []
|
|
980
|
-
counts = {}
|
|
981
|
-
for v in _arr_vals(s):
|
|
982
|
-
hv = tuple(v) if isinstance(v, list) else v
|
|
983
|
-
if hv not in counts:
|
|
984
|
-
order.append((hv, v))
|
|
985
|
-
counts[hv] = 0
|
|
986
|
-
counts[hv] += 1
|
|
987
|
-
return ["Array"] + [["Array", v, counts[hv]] for hv, v in order]
|
|
988
|
-
|
|
989
|
-
def _arr_vals_of(expr):
|
|
990
|
-
"""
|
|
991
|
-
Like `_arr_vals`, but for an arbitrary expression instead
|
|
992
|
-
of assuming the array is at `s[1]` - needed by the
|
|
993
|
-
variadic set operations below.
|
|
994
|
-
"""
|
|
995
|
-
lst = f(expr, c)
|
|
996
|
-
if not (isinstance(lst, list) and lst[0] == "Array"):
|
|
997
|
-
raise ValueError("Parameter must be an array.")
|
|
998
|
-
return [f(x, c) for x in lst[1:]]
|
|
999
|
-
|
|
1000
|
-
def Union(s):
|
|
1001
|
-
"""
|
|
1002
|
-
["Union", array1, array2, ...]
|
|
1003
|
-
Distinct elements appearing in any of the given arrays, in
|
|
1004
|
-
order of first appearance across the arguments
|
|
1005
|
-
(left to right). Arrays stand in for CortexJS's `Set`
|
|
1006
|
-
here - there's no dedicated set type in this solver.
|
|
1007
|
-
"""
|
|
1008
|
-
result = []
|
|
1009
|
-
for arg in s[1:]:
|
|
1010
|
-
for v in _arr_vals_of(arg):
|
|
1011
|
-
if v not in result:
|
|
1012
|
-
result.append(v)
|
|
1013
|
-
return ["Array"] + result
|
|
1014
|
-
|
|
1015
|
-
def Intersection(s):
|
|
1016
|
-
"""
|
|
1017
|
-
["Intersection", array1, array2, ...]
|
|
1018
|
-
Distinct elements common to every given array, in the
|
|
1019
|
-
order they first appear in `array1`.
|
|
1020
|
-
"""
|
|
1021
|
-
arrays = [_arr_vals_of(arg) for arg in s[1:]]
|
|
1022
|
-
if not arrays:
|
|
1023
|
-
return ["Array"]
|
|
1024
|
-
result = []
|
|
1025
|
-
for v in arrays[0]:
|
|
1026
|
-
if v not in result and all(v in arr for arr in arrays[1:]):
|
|
1027
|
-
result.append(v)
|
|
1028
|
-
return ["Array"] + result
|
|
1029
|
-
|
|
1030
|
-
def SetMinus(s):
|
|
1031
|
-
"""
|
|
1032
|
-
["SetMinus", array1, array2]
|
|
1033
|
-
Distinct elements of `array1` that don't occur in
|
|
1034
|
-
`array2`.
|
|
1035
|
-
"""
|
|
1036
|
-
a = _arr_vals_of(s[1])
|
|
1037
|
-
b = _arr_vals_of(s[2])
|
|
1038
|
-
result = []
|
|
1039
|
-
for v in a:
|
|
1040
|
-
if v not in b and v not in result:
|
|
1041
|
-
result.append(v)
|
|
1042
|
-
return ["Array"] + result
|
|
1043
|
-
|
|
1044
|
-
def SymmetricDifference(s):
|
|
1045
|
-
"""
|
|
1046
|
-
["SymmetricDifference", array1, array2]
|
|
1047
|
-
Distinct elements that occur in exactly one of
|
|
1048
|
-
`array1`/`array2`: `array1`'s exclusive elements first
|
|
1049
|
-
(in `array1`'s order), then `array2`'s (in `array2`'s
|
|
1050
|
-
order).
|
|
1051
|
-
"""
|
|
1052
|
-
a = _arr_vals_of(s[1])
|
|
1053
|
-
b = _arr_vals_of(s[2])
|
|
1054
|
-
result = []
|
|
1055
|
-
for v in a:
|
|
1056
|
-
if v not in b and v not in result:
|
|
1057
|
-
result.append(v)
|
|
1058
|
-
for v in b:
|
|
1059
|
-
if v not in a and v not in result:
|
|
1060
|
-
result.append(v)
|
|
1061
|
-
return ["Array"] + result
|
|
1062
|
-
|
|
1063
|
-
def IsPrime(s):
|
|
1064
|
-
return _is_prime(f(s[1], c))
|
|
1065
|
-
|
|
1066
|
-
def Variance(s):
|
|
1067
|
-
return variance(_arr_vals(s))
|
|
1068
|
-
|
|
1069
|
-
def StandardDeviation(s):
|
|
1070
|
-
return stdev(_arr_vals(s))
|
|
1071
|
-
|
|
1072
|
-
def PopulationVariance(s):
|
|
1073
|
-
return pvariance(_arr_vals(s))
|
|
1074
|
-
|
|
1075
|
-
def PopulationStandardDeviation(s):
|
|
1076
|
-
return pstdev(_arr_vals(s))
|
|
1077
|
-
|
|
1078
|
-
def Mode(s):
|
|
1079
|
-
"""
|
|
1080
|
-
["Mode", array]
|
|
1081
|
-
The most frequently occurring value. Ties go to whichever
|
|
1082
|
-
value appears first in `array` (matching Python's
|
|
1083
|
-
`statistics.mode`).
|
|
1084
|
-
"""
|
|
1085
|
-
return mode(_arr_vals(s))
|
|
1086
|
-
|
|
1087
|
-
def Quartiles(s):
|
|
1088
|
-
"""
|
|
1089
|
-
["Quartiles", array]
|
|
1090
|
-
The three points (Q1, Q2/median, Q3) that divide `array`
|
|
1091
|
-
into four equal-sized groups, using
|
|
1092
|
-
`statistics.quantiles`' default ("exclusive") method.
|
|
1093
|
-
"""
|
|
1094
|
-
return ["Array"] + quantiles(_arr_vals(s), n=4)
|
|
1095
|
-
|
|
1096
|
-
def InterquartileRange(s):
|
|
1097
|
-
"""
|
|
1098
|
-
["InterquartileRange", array]
|
|
1099
|
-
Q3 - Q1.
|
|
1100
|
-
"""
|
|
1101
|
-
q1, _, q3 = quantiles(_arr_vals(s), n=4)
|
|
1102
|
-
return q3 - q1
|
|
1103
|
-
|
|
1104
|
-
def Covariance(s):
|
|
1105
|
-
"""
|
|
1106
|
-
["Covariance", array1, array2]
|
|
1107
|
-
Sample covariance of two equal-length collections.
|
|
1108
|
-
"""
|
|
1109
|
-
return covariance(_arr_vals_of(s[1]), _arr_vals_of(s[2]))
|
|
1110
|
-
|
|
1111
|
-
def Correlation(s):
|
|
1112
|
-
"""
|
|
1113
|
-
["Correlation", array1, array2]
|
|
1114
|
-
The Pearson correlation coefficient of two equal-length
|
|
1115
|
-
collections.
|
|
1116
|
-
"""
|
|
1117
|
-
return correlation(_arr_vals_of(s[1]), _arr_vals_of(s[2]))
|
|
1118
|
-
|
|
1119
|
-
def Any(s):
|
|
1120
|
-
evaluated = f(s[1], c)
|
|
1121
|
-
if isinstance(evaluated, list) and evaluated[0] == "Array":
|
|
1122
|
-
return any([f(x, c) for x in evaluated[1:]])
|
|
1123
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1124
|
-
|
|
1125
|
-
def All(s):
|
|
1126
|
-
evaluated = f(s[1], c)
|
|
1127
|
-
if isinstance(evaluated, list) and evaluated[0] == "Array":
|
|
1128
|
-
return all([f(x, c) for x in evaluated[1:]])
|
|
1129
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1130
|
-
|
|
1131
|
-
def Int(s):
|
|
1132
|
-
try:
|
|
1133
|
-
return int(f(s[1], c))
|
|
1134
|
-
except ValueError:
|
|
1135
|
-
return int(float(f(s[1], c)))
|
|
1136
|
-
|
|
1137
|
-
def Float(s):
|
|
1138
|
-
return float(f(s[1], c))
|
|
1139
|
-
|
|
1140
|
-
def Floor(s):
|
|
1141
|
-
return math.floor(f(s[1], c))
|
|
1142
|
-
|
|
1143
|
-
def Ceil(s):
|
|
1144
|
-
return math.ceil(f(s[1], c))
|
|
1145
|
-
|
|
1146
|
-
def Constants(s):
|
|
1147
|
-
for x in s[1:-1]:
|
|
1148
|
-
try:
|
|
1149
|
-
c[x[0]] = f(x[1], c)
|
|
1150
|
-
except Exception:
|
|
1151
|
-
c[x[0]] = None
|
|
1152
|
-
return f(s[-1], c)
|
|
1153
|
-
|
|
1154
|
-
def Switch(s):
|
|
1155
|
-
expression = f(s[1], c)
|
|
1156
|
-
for x in s[3:]:
|
|
1157
|
-
if len(x) != 2:
|
|
1158
|
-
raise ValueError(
|
|
1159
|
-
"Case of 'Switch' should have exactly two parameters"
|
|
1160
|
-
)
|
|
1161
|
-
if comparison_safe_converter(
|
|
1162
|
-
expression
|
|
1163
|
-
) == comparison_safe_converter(f(x[0], c)):
|
|
1164
|
-
return f(x[1], c)
|
|
1165
|
-
else:
|
|
1166
|
-
return f(s[2], c)
|
|
1167
|
-
|
|
1168
|
-
def StrictSwitch(s):
|
|
1169
|
-
expression = f(s[1], c)
|
|
1170
|
-
for x in s[3:]:
|
|
1171
|
-
if len(x) != 2:
|
|
1172
|
-
raise ValueError(
|
|
1173
|
-
"Case of 'StrictSwitch' should have exactly two parameters"
|
|
1174
|
-
)
|
|
1175
|
-
if expression == f(x[0], c):
|
|
1176
|
-
return f(x[1], c)
|
|
1177
|
-
else:
|
|
1178
|
-
return f(s[2], c)
|
|
1179
|
-
|
|
1180
|
-
def If(s):
|
|
1181
|
-
if len(s) < 3:
|
|
1182
|
-
raise ValueError("Wrong parameters for 'If'")
|
|
1183
|
-
|
|
1184
|
-
# Detect the CortexJS flat form: ["If", cond, then] or
|
|
1185
|
-
# ["If", cond, then, else]. In the Python pair-form below,
|
|
1186
|
-
# s[1] is always a [condition, value] pair whose first
|
|
1187
|
-
# element (the condition) is itself a MathJSON construct
|
|
1188
|
-
# call, e.g. ["Equal", 1, 0]. A CortexJS flat condition is
|
|
1189
|
-
# either not a list at all, or is itself such a construct
|
|
1190
|
-
# call (its own first element is a *known construct name*).
|
|
1191
|
-
# Requiring a known name - rather than any string - keeps a
|
|
1192
|
-
# Python-form condition that is a bare parameter reference,
|
|
1193
|
-
# e.g. ["If", ["my_flag", "yes"], "no"], from being
|
|
1194
|
-
# misdetected as CortexJS form.
|
|
1195
|
-
is_cortexjs_form = not isinstance(s[1], list) or (
|
|
1196
|
-
bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs
|
|
1197
|
-
)
|
|
1198
|
-
|
|
1199
|
-
if is_cortexjs_form:
|
|
1200
|
-
if len(s) not in (3, 4):
|
|
1201
|
-
raise ValueError("Wrong parameters for 'If'")
|
|
1202
|
-
if f(s[1], c):
|
|
1203
|
-
return f(s[2], c)
|
|
1204
|
-
elif len(s) == 4:
|
|
1205
|
-
return f(s[3], c)
|
|
1206
|
-
else:
|
|
1207
|
-
return None # CortexJS: Nothing, no else and condition false
|
|
1208
|
-
|
|
1209
|
-
for x in s[1:-1]:
|
|
1210
|
-
if len(x) != 2:
|
|
1211
|
-
raise ValueError("Wrong if or elif in 'If'")
|
|
1212
|
-
try:
|
|
1213
|
-
if f(x[0], c):
|
|
1214
|
-
try:
|
|
1215
|
-
return f(x[1], c)
|
|
1216
|
-
except MathJSONException:
|
|
1217
|
-
# Branch failed, try next condition
|
|
1218
|
-
continue
|
|
1219
|
-
except MathJSONException:
|
|
1220
|
-
return f(s[-1], c) # return default value (else)
|
|
1221
|
-
|
|
1222
|
-
return f(s[-1], c)
|
|
1223
|
-
|
|
1224
|
-
def Which(s):
|
|
1225
|
-
"""
|
|
1226
|
-
["Which", cond1, expr1, cond2, expr2, ..., condN, exprN]
|
|
1227
|
-
CortexJS multi-branch conditional: evaluates each `cond` in
|
|
1228
|
-
order and returns the `expr` paired with the first truthy
|
|
1229
|
-
one. Unlike 'Switch' (Python's value-equality dispatch),
|
|
1230
|
-
each `cond` here is itself a boolean expression, not a
|
|
1231
|
-
value to compare against - and unlike `If`'s pair form,
|
|
1232
|
-
the pairs are flat (cond, expr as separate arguments, not
|
|
1233
|
-
nested as [cond, expr]). Returns None (CortexJS `Nothing`)
|
|
1234
|
-
if no condition matches.
|
|
1235
|
-
"""
|
|
1236
|
-
args = s[1:]
|
|
1237
|
-
if len(args) % 2 != 0:
|
|
1238
|
-
raise ValueError(
|
|
1239
|
-
"'Which' requires an even number of parameters "
|
|
1240
|
-
"(condition, value, ...)"
|
|
1241
|
-
)
|
|
1242
|
-
for i in range(0, len(args), 2):
|
|
1243
|
-
if f(args[i], c):
|
|
1244
|
-
return f(args[i + 1], c)
|
|
1245
|
-
return None
|
|
1246
|
-
|
|
1247
|
-
def In(s):
|
|
1248
|
-
if len(s) != 3:
|
|
1249
|
-
raise ValueError("Wrong parameters for 'In'")
|
|
1250
|
-
if isinstance(s[2], list) and s[2][0] == "Array":
|
|
1251
|
-
return f(s[1], c) in [f(x, c) for x in s[2][1:]]
|
|
1252
|
-
|
|
1253
|
-
elif isinstance(s[2], str):
|
|
1254
|
-
return f(s[1], c) in f(s[2], c)
|
|
1255
|
-
else:
|
|
1256
|
-
raise ValueError(
|
|
1257
|
-
"Wrong parameters for 'In'. Parameter 2 must be a list."
|
|
1258
|
-
)
|
|
1259
|
-
|
|
1260
|
-
def Not_in(s):
|
|
1261
|
-
return not In(s)
|
|
1262
|
-
|
|
1263
|
-
def Contains_any_of(s):
|
|
1264
|
-
if isinstance(s[1], list) and s[1][0] == "Array":
|
|
1265
|
-
list1 = [f(x, c) for x in s[1][1:]]
|
|
1266
|
-
elif isinstance(s[1], str):
|
|
1267
|
-
list1 = f(s[1], c)
|
|
1268
|
-
|
|
1269
|
-
if isinstance(s[2], list) and s[2][0] == "Array":
|
|
1270
|
-
list2 = [f(x, c) for x in s[2][1:]]
|
|
1271
|
-
elif isinstance(s[2], str):
|
|
1272
|
-
list2 = f(s[2], c)
|
|
1273
|
-
|
|
1274
|
-
if any(x in list1 for x in list2):
|
|
1275
|
-
return True
|
|
1276
|
-
return False
|
|
1277
|
-
|
|
1278
|
-
def Contains_all_of(s):
|
|
1279
|
-
if isinstance(s[1], list) and s[1][0] == "Array":
|
|
1280
|
-
list1 = [f(x, c) for x in s[1][1:]]
|
|
1281
|
-
elif isinstance(s[1], str):
|
|
1282
|
-
list1 = f(s[1], c)
|
|
1283
|
-
|
|
1284
|
-
if isinstance(s[2], list) and s[2][0] == "Array":
|
|
1285
|
-
list2 = [f(x, c) for x in s[2][1:]]
|
|
1286
|
-
elif isinstance(s[2], str):
|
|
1287
|
-
list2 = f(s[2], c)
|
|
1288
|
-
|
|
1289
|
-
if all(x in list1 for x in list2):
|
|
1290
|
-
return True
|
|
1291
|
-
return False
|
|
1292
|
-
|
|
1293
|
-
def Contains_none_of(s):
|
|
1294
|
-
return not Contains_any_of(s)
|
|
1295
|
-
|
|
1296
|
-
def Str(s):
|
|
1297
|
-
if len(s) < 2:
|
|
1298
|
-
raise ValueError("Wrong parameters for 'Str'")
|
|
1299
|
-
return f"{f(s[1])}"
|
|
1300
|
-
|
|
1301
|
-
def String(s):
|
|
1302
|
-
"""
|
|
1303
|
-
["String", value1, value2, ...]
|
|
1304
|
-
Concatenates the default string representation of each
|
|
1305
|
-
argument. Distinct from `Str` (single argument) and from
|
|
1306
|
-
`StringJoin` (joins the elements of a single array).
|
|
1307
|
-
"""
|
|
1308
|
-
return "".join(str(f(x, c)) for x in s[1:])
|
|
1309
|
-
|
|
1310
|
-
def StringJoin(s):
|
|
1311
|
-
"""
|
|
1312
|
-
["StringJoin", array] or ["StringJoin", array, separator]
|
|
1313
|
-
Joins the (stringified) elements of `array` with
|
|
1314
|
-
`separator` (default ""). Distinct from `Join`, which
|
|
1315
|
-
concatenates multiple arrays together.
|
|
1316
|
-
"""
|
|
1317
|
-
values = [str(v) for v in _arr_vals(s)]
|
|
1318
|
-
separator = f(s[2], c) if len(s) > 2 else ""
|
|
1319
|
-
return separator.join(values)
|
|
1320
|
-
|
|
1321
|
-
def Utf8(s):
|
|
1322
|
-
"""
|
|
1323
|
-
["Utf8", string]
|
|
1324
|
-
List of UTF-8 byte values representing `string`.
|
|
1325
|
-
"""
|
|
1326
|
-
return ["Array"] + list(f(s[1], c).encode("utf-8"))
|
|
1327
|
-
|
|
1328
|
-
def Utf16(s):
|
|
1329
|
-
"""
|
|
1330
|
-
["Utf16", string]
|
|
1331
|
-
List of UTF-16 code units representing `string` (one
|
|
1332
|
-
array element per 16-bit code unit, matching how
|
|
1333
|
-
JavaScript/CortexJS model a string).
|
|
1334
|
-
"""
|
|
1335
|
-
encoded = f(s[1], c).encode("utf-16-le")
|
|
1336
|
-
return ["Array"] + [
|
|
1337
|
-
encoded[i] | (encoded[i + 1] << 8)
|
|
1338
|
-
for i in range(0, len(encoded), 2)
|
|
1339
|
-
]
|
|
1340
|
-
|
|
1341
|
-
def UnicodeScalars(s):
|
|
1342
|
-
"""
|
|
1343
|
-
["UnicodeScalars", string]
|
|
1344
|
-
List of Unicode scalar (code point) values in `string`.
|
|
1345
|
-
"""
|
|
1346
|
-
return ["Array"] + [ord(ch) for ch in f(s[1], c)]
|
|
1347
|
-
|
|
1348
|
-
def StringFrom(s):
|
|
1349
|
-
"""
|
|
1350
|
-
["StringFrom", array, encoding]
|
|
1351
|
-
Converts `array` (a list of code units, as produced by
|
|
1352
|
-
`Utf8`/`Utf16`/`UnicodeScalars`) back into a string.
|
|
1353
|
-
`encoding` is one of "utf-8", "utf-16", "unicode-scalars".
|
|
1354
|
-
"""
|
|
1355
|
-
values = _arr_vals(s)
|
|
1356
|
-
encoding = f(s[2], c)
|
|
1357
|
-
if encoding == "utf-8":
|
|
1358
|
-
return bytes(int(v) for v in values).decode("utf-8")
|
|
1359
|
-
elif encoding == "utf-16":
|
|
1360
|
-
raw = b"".join(int(v).to_bytes(2, "little") for v in values)
|
|
1361
|
-
return raw.decode("utf-16-le")
|
|
1362
|
-
elif encoding == "unicode-scalars":
|
|
1363
|
-
return "".join(chr(int(v)) for v in values)
|
|
1364
|
-
else:
|
|
1365
|
-
raise ValueError(f"Unknown encoding: {encoding!r}")
|
|
1366
|
-
|
|
1367
|
-
def Characters(s):
|
|
1368
|
-
"""
|
|
1369
|
-
["Characters", string]
|
|
1370
|
-
Splits `string` into a list of its characters. Approximated
|
|
1371
|
-
at the Unicode code-point level (Python `str` iteration)
|
|
1372
|
-
rather than true extended grapheme clusters (Unicode
|
|
1373
|
-
Annex #29), which would need a dependency this solver
|
|
1374
|
-
doesn't otherwise require - a multi-codepoint grapheme
|
|
1375
|
-
(e.g. an emoji with a modifier) is split into its
|
|
1376
|
-
constituent code points rather than kept whole.
|
|
1377
|
-
"""
|
|
1378
|
-
return ["Array"] + list(f(s[1], c))
|
|
1379
|
-
|
|
1380
|
-
def StringSplit(s):
|
|
1381
|
-
"""
|
|
1382
|
-
["StringSplit", string] or ["StringSplit", string, separator]
|
|
1383
|
-
Splits on whitespace if no `separator` is given, else on
|
|
1384
|
-
the literal `separator` string.
|
|
1385
|
-
"""
|
|
1386
|
-
string = f(s[1], c)
|
|
1387
|
-
if len(s) > 2:
|
|
1388
|
-
return ["Array"] + string.split(f(s[2], c))
|
|
1389
|
-
return ["Array"] + string.split()
|
|
1390
|
-
|
|
1391
|
-
def StringReplace(s):
|
|
1392
|
-
"""
|
|
1393
|
-
["StringReplace", string, target, replacement]
|
|
1394
|
-
Replaces every occurrence of the literal substring
|
|
1395
|
-
`target` with `replacement` (not pattern-based - see
|
|
1396
|
-
`IsMatch`/`StringMatch` for pattern matching).
|
|
1397
|
-
"""
|
|
1398
|
-
return f(s[1], c).replace(f(s[2], c), f(s[3], c))
|
|
1399
|
-
|
|
1400
|
-
def StringCompare(s):
|
|
1401
|
-
"""
|
|
1402
|
-
["StringCompare", string1, string2]
|
|
1403
|
-
-1, 0, or 1 depending on whether `string1` sorts before,
|
|
1404
|
-
equal to, or after `string2` by code-point sequence.
|
|
1405
|
-
"""
|
|
1406
|
-
a, b = f(s[1], c), f(s[2], c)
|
|
1407
|
-
return (a > b) - (a < b)
|
|
1408
|
-
|
|
1409
|
-
def IntegerString(s):
|
|
1410
|
-
"""
|
|
1411
|
-
["IntegerString", integer] or ["IntegerString", integer, base]
|
|
1412
|
-
String representation of `integer` in `base` (default 10,
|
|
1413
|
-
2-36).
|
|
1414
|
-
"""
|
|
1415
|
-
value = int(f(s[1], c))
|
|
1416
|
-
base = int(f(s[2], c)) if len(s) > 2 else 10
|
|
1417
|
-
if base == 10:
|
|
1418
|
-
return str(value)
|
|
1419
|
-
if not (2 <= base <= 36):
|
|
1420
|
-
raise ValueError(
|
|
1421
|
-
"'IntegerString' base must be between 2 and 36."
|
|
1422
|
-
)
|
|
1423
|
-
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
|
|
1424
|
-
negative = value < 0
|
|
1425
|
-
value = abs(value)
|
|
1426
|
-
if value == 0:
|
|
1427
|
-
digits_out = "0"
|
|
1428
|
-
else:
|
|
1429
|
-
digits_out = ""
|
|
1430
|
-
while value:
|
|
1431
|
-
value, rem = divmod(value, base)
|
|
1432
|
-
digits_out = digits[rem] + digits_out
|
|
1433
|
-
return ("-" if negative else "") + digits_out
|
|
1434
|
-
|
|
1435
|
-
def DigitsFrom(s):
|
|
1436
|
-
"""
|
|
1437
|
-
["DigitsFrom", string] or ["DigitsFrom", string, base]
|
|
1438
|
-
Parses `string` as an integer in `base` (default 10).
|
|
1439
|
-
"""
|
|
1440
|
-
string = f(s[1], c)
|
|
1441
|
-
base = int(f(s[2], c)) if len(s) > 2 else 10
|
|
1442
|
-
return int(string, base)
|
|
1443
|
-
|
|
1444
|
-
def NumberFrom(s):
|
|
1445
|
-
"""
|
|
1446
|
-
["NumberFrom", string]
|
|
1447
|
-
Parses `string` as a number - integer, decimal, or
|
|
1448
|
-
scientific notation.
|
|
1449
|
-
"""
|
|
1450
|
-
string = f(s[1], c).strip()
|
|
1451
|
-
try:
|
|
1452
|
-
return int(string)
|
|
1453
|
-
except ValueError:
|
|
1454
|
-
return float(string)
|
|
1455
|
-
|
|
1456
|
-
def StringRepeat(s):
|
|
1457
|
-
"""
|
|
1458
|
-
["StringRepeat", string, n]
|
|
1459
|
-
Concatenates `n` copies of `string`. Capped at
|
|
1460
|
-
`_MAX_STRING_REPEAT_LENGTH` characters, since `n` is a
|
|
1461
|
-
user-controlled value that would otherwise make this an
|
|
1462
|
-
unbounded memory-exhaustion primitive.
|
|
1463
|
-
"""
|
|
1464
|
-
string = f(s[1], c)
|
|
1465
|
-
n = int(f(s[2], c))
|
|
1466
|
-
if n < 0:
|
|
1467
|
-
raise ValueError("'StringRepeat' count must be non-negative.")
|
|
1468
|
-
if len(string) * n > _MAX_STRING_REPEAT_LENGTH:
|
|
1469
|
-
raise ValueError(
|
|
1470
|
-
f"'StringRepeat' result would exceed the "
|
|
1471
|
-
f"{_MAX_STRING_REPEAT_LENGTH}-character limit."
|
|
1472
|
-
)
|
|
1473
|
-
return string * n
|
|
1474
|
-
|
|
1475
|
-
def _pad(string, length, pad, prepend):
|
|
1476
|
-
if length > _MAX_STRING_REPEAT_LENGTH:
|
|
1477
|
-
raise ValueError(
|
|
1478
|
-
f"Pad length must not exceed "
|
|
1479
|
-
f"{_MAX_STRING_REPEAT_LENGTH} characters."
|
|
1480
|
-
)
|
|
1481
|
-
if len(string) >= length or not pad:
|
|
1482
|
-
return string
|
|
1483
|
-
needed = length - len(string)
|
|
1484
|
-
full_pad = (pad * (needed // len(pad) + 1))[:needed]
|
|
1485
|
-
return full_pad + string if prepend else string + full_pad
|
|
1486
|
-
|
|
1487
|
-
def PadStart(s):
|
|
1488
|
-
"""
|
|
1489
|
-
["PadStart", string, length] or
|
|
1490
|
-
["PadStart", string, length, pad]
|
|
1491
|
-
Pads `string` on the left to `length` characters using
|
|
1492
|
-
`pad` (default a single space), truncating `pad` as
|
|
1493
|
-
needed to fit exactly.
|
|
1494
|
-
"""
|
|
1495
|
-
pad = f(s[3], c) if len(s) > 3 else " "
|
|
1496
|
-
return _pad(f(s[1], c), int(f(s[2], c)), pad, prepend=True)
|
|
1497
|
-
|
|
1498
|
-
def PadEnd(s):
|
|
1499
|
-
"""
|
|
1500
|
-
["PadEnd", string, length] or ["PadEnd", string, length, pad]
|
|
1501
|
-
Pads `string` on the right to `length` characters using
|
|
1502
|
-
`pad` (default a single space), truncating `pad` as
|
|
1503
|
-
needed to fit exactly.
|
|
1504
|
-
"""
|
|
1505
|
-
pad = f(s[3], c) if len(s) > 3 else " "
|
|
1506
|
-
return _pad(f(s[1], c), int(f(s[2], c)), pad, prepend=False)
|
|
1507
|
-
|
|
1508
|
-
_VALID_REGEX_FLAGS = set("ims")
|
|
1509
|
-
|
|
1510
|
-
def _require_re2():
|
|
1511
|
-
if not RE2_AVAILABLE:
|
|
1512
|
-
raise ImportError(
|
|
1513
|
-
"RegExp/IsMatch/StringMatch/StringMatchAll require "
|
|
1514
|
-
"'google-re2'. Install with "
|
|
1515
|
-
"'pip install mathjson-solver[regex]' "
|
|
1516
|
-
"(or 'pip install google-re2')."
|
|
1517
|
-
)
|
|
1518
|
-
|
|
1519
|
-
def _compile_regex(pattern_str, flags_str=""):
|
|
1520
|
-
if not set(flags_str) <= _VALID_REGEX_FLAGS:
|
|
1521
|
-
raise ValueError(
|
|
1522
|
-
f"Unsupported regex flag(s) in {flags_str!r}; only "
|
|
1523
|
-
f"'i', 'm', 's' are supported."
|
|
1524
|
-
)
|
|
1525
|
-
prefixed = f"(?{flags_str})" + pattern_str if flags_str else pattern_str
|
|
1526
|
-
try:
|
|
1527
|
-
return re2.compile(prefixed)
|
|
1528
|
-
except re2.error as e:
|
|
1529
|
-
raise ValueError(f"Invalid pattern {pattern_str!r}: {e}") from e
|
|
1530
|
-
|
|
1531
|
-
def _resolve_pattern(expr):
|
|
1532
|
-
"""
|
|
1533
|
-
Evaluates `expr` and returns a compiled RE2 pattern -
|
|
1534
|
-
unchanged if it's already one (e.g. produced by a nested
|
|
1535
|
-
`RegExp` call), else compiled fresh (no flags) if it's a
|
|
1536
|
-
plain string.
|
|
1537
|
-
|
|
1538
|
-
Uses RE2 rather than Python's `re`: RE2 guarantees
|
|
1539
|
-
linear-time matching (no catastrophic backtracking is
|
|
1540
|
-
possible, by construction of the engine), at the cost of
|
|
1541
|
-
not supporting backreferences or lookaround - a
|
|
1542
|
-
deliberate trade-off for a solver that evaluates
|
|
1543
|
-
untrusted expressions with no execution budget of its own.
|
|
1544
|
-
"""
|
|
1545
|
-
_require_re2()
|
|
1546
|
-
value = f(expr, c)
|
|
1547
|
-
if isinstance(value, _RE2_PATTERN_TYPE):
|
|
1548
|
-
return value
|
|
1549
|
-
if isinstance(value, str):
|
|
1550
|
-
return _compile_regex(value)
|
|
1551
|
-
raise ValueError(
|
|
1552
|
-
"Expected a pattern string or a RegExp value."
|
|
1553
|
-
)
|
|
1554
|
-
|
|
1555
|
-
def RegExp(s):
|
|
1556
|
-
"""
|
|
1557
|
-
["RegExp", pattern] or ["RegExp", pattern, flags]
|
|
1558
|
-
Compiles `pattern` (RE2 syntax - see `_resolve_pattern`)
|
|
1559
|
-
into a reusable pattern value, for passing to
|
|
1560
|
-
`IsMatch`/`StringMatch`/`StringMatchAll`. `flags` is a
|
|
1561
|
-
string made up of "i" (case-insensitive), "m" (multiline
|
|
1562
|
-
anchors), "s" (dot matches newline).
|
|
1563
|
-
"""
|
|
1564
|
-
_require_re2()
|
|
1565
|
-
pattern_str = f(s[1], c)
|
|
1566
|
-
flags_str = f(s[2], c) if len(s) > 2 else ""
|
|
1567
|
-
return _compile_regex(pattern_str, flags_str)
|
|
1568
|
-
|
|
1569
|
-
def IsMatch(s):
|
|
1570
|
-
"""
|
|
1571
|
-
["IsMatch", string, pattern]
|
|
1572
|
-
Whether `string` contains a match for `pattern` (a plain
|
|
1573
|
-
pattern string, or a `RegExp` value) anywhere within it.
|
|
1574
|
-
"""
|
|
1575
|
-
pattern = _resolve_pattern(s[2])
|
|
1576
|
-
return pattern.search(f(s[1], c)) is not None
|
|
1577
|
-
|
|
1578
|
-
def _match_record(m):
|
|
1579
|
-
return [
|
|
1580
|
-
"Array",
|
|
1581
|
-
m.group(0),
|
|
1582
|
-
m.start() + 1, # 1-indexed, matching this solver's
|
|
1583
|
-
m.end(), # other CortexJS-compat index
|
|
1584
|
-
# conventions (At, Range, ...)
|
|
1585
|
-
["Array"] + list(m.groups()),
|
|
1586
|
-
]
|
|
1587
|
-
|
|
1588
|
-
def StringMatch(s):
|
|
1589
|
-
"""
|
|
1590
|
-
["StringMatch", string, pattern]
|
|
1591
|
-
The first match of `pattern` in `string`, as
|
|
1592
|
-
["Array", matched_text, start, end, ["Array", group1, ...]]
|
|
1593
|
-
(1-indexed `start`, exclusive `end`), or None if there's
|
|
1594
|
-
no match.
|
|
1595
|
-
"""
|
|
1596
|
-
pattern = _resolve_pattern(s[2])
|
|
1597
|
-
m = pattern.search(f(s[1], c))
|
|
1598
|
-
return _match_record(m) if m else None
|
|
1599
|
-
|
|
1600
|
-
def StringMatchAll(s):
|
|
1601
|
-
"""
|
|
1602
|
-
["StringMatchAll", string, pattern]
|
|
1603
|
-
All non-overlapping matches of `pattern` in `string`,
|
|
1604
|
-
each in the same shape as `StringMatch`.
|
|
1605
|
-
"""
|
|
1606
|
-
pattern = _resolve_pattern(s[2])
|
|
1607
|
-
return ["Array"] + [
|
|
1608
|
-
_match_record(m) for m in pattern.finditer(f(s[1], c))
|
|
1609
|
-
]
|
|
1610
|
-
|
|
1611
|
-
def Not(s):
|
|
1612
|
-
return not f(s[1])
|
|
1613
|
-
|
|
1614
|
-
def _apply_fn(fn_expr, args):
|
|
1615
|
-
"""
|
|
1616
|
-
Apply a "function" argument (as used by Map, Filter, and the
|
|
1617
|
-
CortexJS form of Reduce) to positional `args`. Supports two
|
|
1618
|
-
conventions:
|
|
1619
|
-
|
|
1620
|
-
- CortexJS `["Function", body, param1, param2, ...]`. If no
|
|
1621
|
-
parameter names are given, `args` are bound to the
|
|
1622
|
-
anonymous placeholders "_" (only when there is a single
|
|
1623
|
-
argument) and "_1", "_2", ... (always), for use inside
|
|
1624
|
-
`body`.
|
|
1625
|
-
- The existing "call template" convention:
|
|
1626
|
-
`[function_name, ...]`, applied as
|
|
1627
|
-
`f([function_name] + args, c)`.
|
|
1628
|
-
"""
|
|
1629
|
-
if isinstance(fn_expr, list) and fn_expr and fn_expr[0] == "Function":
|
|
1630
|
-
body = fn_expr[1]
|
|
1631
|
-
params = fn_expr[2:]
|
|
1632
|
-
local_c = dict(c)
|
|
1633
|
-
if params:
|
|
1634
|
-
for name, value in zip(params, args):
|
|
1635
|
-
local_c[name] = value
|
|
1636
|
-
else:
|
|
1637
|
-
if len(args) == 1:
|
|
1638
|
-
local_c["_"] = args[0]
|
|
1639
|
-
for i, value in enumerate(args, start=1):
|
|
1640
|
-
local_c[f"_{i}"] = value
|
|
1641
|
-
return f(body, local_c)
|
|
1642
|
-
elif isinstance(fn_expr, list) and fn_expr:
|
|
1643
|
-
function_name = fn_expr[0]
|
|
1644
|
-
return f([function_name] + list(args), c)
|
|
1645
|
-
else:
|
|
1646
|
-
raise ValueError(
|
|
1647
|
-
"Wrong function parameter: expected a call template "
|
|
1648
|
-
"(e.g. ['Square']) or a ['Function', body, ...] expression."
|
|
1649
|
-
)
|
|
1650
|
-
|
|
1651
|
-
def Map(s):
|
|
1652
|
-
"""
|
|
1653
|
-
["Map", list, function, more parameters]
|
|
1654
|
-
The `function` must accept at least one parameter. That is for the current loop element.
|
|
1655
|
-
The `more parameters` are for any additional parameters that function might have.
|
|
1656
|
-
`function` can also be a CortexJS ["Function", body, ...params] expression.
|
|
1657
|
-
"""
|
|
1658
|
-
z = f(s[1], c)
|
|
1659
|
-
if isinstance(z, list):
|
|
1660
|
-
retlist = ["Array"]
|
|
1661
|
-
for x in z[1:]:
|
|
1662
|
-
try:
|
|
1663
|
-
retlist.append(_apply_fn(s[2], [x] + s[3:]))
|
|
1664
|
-
except MathJSONException:
|
|
1665
|
-
retlist.append(x)
|
|
1666
|
-
return retlist
|
|
1667
|
-
|
|
1668
|
-
def StrictMap(s):
|
|
1669
|
-
"""
|
|
1670
|
-
["Map", list, function, more parameters]
|
|
1671
|
-
The `function` must accept at least one parameter. That is for the current loop element.
|
|
1672
|
-
The `more parameters` are for any additional parameters that function might have.
|
|
1673
|
-
`function` can also be a CortexJS ["Function", body, ...params] expression.
|
|
1674
|
-
"""
|
|
1675
|
-
z = f(s[1], c)
|
|
1676
|
-
if isinstance(z, list):
|
|
1677
|
-
retlist = ["Array"]
|
|
1678
|
-
for x in z[1:]:
|
|
1679
|
-
retlist.append(_apply_fn(s[2], [x] + s[3:]))
|
|
1680
|
-
return retlist
|
|
1681
|
-
|
|
1682
|
-
def Filter(s):
|
|
1683
|
-
"""
|
|
1684
|
-
["Filter", list, function, more parameters]
|
|
1685
|
-
The `function` must accept at least one parameter. That is for the current loop element.
|
|
1686
|
-
The `more parameters` are for any additional parameters that function might have.
|
|
1687
|
-
`function` can also be a CortexJS ["Function", body, ...params] expression.
|
|
1688
|
-
"""
|
|
1689
|
-
z = f(s[1], c)
|
|
1690
|
-
if isinstance(z, list):
|
|
1691
|
-
retlist = ["Array"]
|
|
1692
|
-
for x in z[1:]:
|
|
1693
|
-
if _apply_fn(s[2], [x] + s[3:]):
|
|
1694
|
-
retlist.append(x)
|
|
1695
|
-
return retlist
|
|
1696
|
-
|
|
1697
|
-
def HasMatchingSublist(s):
|
|
1698
|
-
"""
|
|
1699
|
-
["HasMatchingSublist", list, required_match_count, position, contiguous, function, more parameters]
|
|
1700
|
-
"""
|
|
1701
|
-
the_list = f(s[1], c)[1:]
|
|
1702
|
-
required_match_count = f(s[2], c)
|
|
1703
|
-
position = f(s[3], c)
|
|
1704
|
-
contiguous = f(s[4], c)
|
|
1705
|
-
conditions = []
|
|
1706
|
-
|
|
1707
|
-
for i, x in enumerate(the_list):
|
|
1708
|
-
the_function_name = s[5][0]
|
|
1709
|
-
ss = [the_function_name, x] + s[6:]
|
|
1710
|
-
conditions.append(f(ss, c))
|
|
1711
|
-
pass
|
|
1712
|
-
|
|
1713
|
-
return has_matching_sublist(
|
|
1714
|
-
my_list=the_list,
|
|
1715
|
-
required_match_count=required_match_count,
|
|
1716
|
-
position=position,
|
|
1717
|
-
contiguous=contiguous,
|
|
1718
|
-
conditions=conditions,
|
|
1719
|
-
)
|
|
1720
|
-
|
|
1721
|
-
def Strptime(s):
|
|
1722
|
-
datetime_str = f(s[1], c)
|
|
1723
|
-
parameters = f(s[2], c)
|
|
1724
|
-
return datetime.datetime.strptime(datetime_str, parameters).isoformat()
|
|
1725
|
-
|
|
1726
|
-
def Strftime(s):
|
|
1727
|
-
dt = _try_parse_datetime(f(s[1], c))
|
|
1728
|
-
if not isinstance(dt, (datetime.datetime, datetime.date)):
|
|
1729
|
-
raise ValueError(f"Strftime: could not parse input as datetime: {dt!r}")
|
|
1730
|
-
parameters = f(s[2], c)
|
|
1731
|
-
return dt.strftime(parameters)
|
|
1732
|
-
|
|
1733
|
-
def Now(s):
|
|
1734
|
-
return datetime.datetime.now().isoformat()
|
|
1735
|
-
|
|
1736
|
-
def Today(s):
|
|
1737
|
-
return datetime.date.today().isoformat()
|
|
1738
|
-
|
|
1739
|
-
def TimeDeltaDays(s):
|
|
1740
|
-
return datetime.timedelta(days=f(s[1], c))
|
|
1741
|
-
|
|
1742
|
-
def TimeDeltaMinutes(s):
|
|
1743
|
-
return datetime.timedelta(minutes=f(s[1], c))
|
|
1744
|
-
|
|
1745
|
-
def TimeDeltaHours(s):
|
|
1746
|
-
return datetime.timedelta(hours=f(s[1], c))
|
|
1747
|
-
|
|
1748
|
-
def TimeDeltaWeeks(s):
|
|
1749
|
-
return datetime.timedelta(weeks=f(s[1], c))
|
|
1750
|
-
|
|
1751
|
-
# def Equal(s):
|
|
1752
|
-
# a = comparison_safe_converter(f(s[1], c))
|
|
1753
|
-
# b = comparison_safe_converter(f(s[2], c))
|
|
1754
|
-
# return a == b
|
|
1755
|
-
# if type(a) in [int, float, str]:
|
|
1756
|
-
# a = f"{a}"
|
|
1757
|
-
# elif type(a) in [bool, NoneType]:
|
|
1758
|
-
# if a:
|
|
1759
|
-
# a = True
|
|
1760
|
-
# else:
|
|
1761
|
-
# a = None
|
|
1762
|
-
|
|
1763
|
-
# if is_numeric(a):
|
|
1764
|
-
|
|
1765
|
-
# lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
|
|
1766
|
-
|
|
1767
|
-
def IsDefined(s):
|
|
1768
|
-
return s[1] in solver_parameters or s[1] in c
|
|
1769
|
-
|
|
1770
|
-
def IsUndefined(s):
|
|
1771
|
-
return not IsDefined(s)
|
|
1772
|
-
|
|
1773
|
-
def Greater(s):
|
|
1774
|
-
v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
|
|
1775
|
-
try:
|
|
1776
|
-
return v1 > v2
|
|
1777
|
-
except TypeError:
|
|
1778
|
-
return False
|
|
1779
|
-
|
|
1780
|
-
def GreaterEqual(s):
|
|
1781
|
-
v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
|
|
1782
|
-
try:
|
|
1783
|
-
return v1 >= v2
|
|
1784
|
-
except TypeError:
|
|
1785
|
-
return False
|
|
1786
|
-
|
|
1787
|
-
def Less(s):
|
|
1788
|
-
v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
|
|
1789
|
-
try:
|
|
1790
|
-
return v1 < v2
|
|
1791
|
-
except TypeError:
|
|
1792
|
-
return False
|
|
1793
|
-
|
|
1794
|
-
def LessEqual(s):
|
|
1795
|
-
v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
|
|
1796
|
-
try:
|
|
1797
|
-
return v1 <= v2
|
|
1798
|
-
except TypeError:
|
|
1799
|
-
return False
|
|
1800
|
-
|
|
1801
|
-
def IdenticallyEqual(s):
|
|
1802
|
-
"""
|
|
1803
|
-
["IdenticallyEqual", a, b]
|
|
1804
|
-
Stricter than `StrictEqual`: true only if `a` and `b` have
|
|
1805
|
-
the same Python type *and* are equal - e.g. `1` and `1.0`
|
|
1806
|
-
are `StrictEqual` but not `IdenticallyEqual`.
|
|
1807
|
-
"""
|
|
1808
|
-
a = f(s[1], c)
|
|
1809
|
-
b = f(s[2], c)
|
|
1810
|
-
return type(a) == type(b) and a == b
|
|
1811
|
-
|
|
1812
|
-
def Congruent(s):
|
|
1813
|
-
"""
|
|
1814
|
-
["Congruent", a, b, modulus]
|
|
1815
|
-
Whether `a` and `b` are congruent modulo `modulus`, i.e.
|
|
1816
|
-
`(a - b) % modulus == 0`.
|
|
1817
|
-
"""
|
|
1818
|
-
a = f(s[1], c)
|
|
1819
|
-
b = f(s[2], c)
|
|
1820
|
-
modulus = f(s[3], c)
|
|
1821
|
-
return (a - b) % modulus == 0
|
|
1822
|
-
|
|
1823
|
-
def _rational_parts(s):
|
|
1824
|
-
"""
|
|
1825
|
-
Numerator/denominator pair for `s[1]`. If `s[1]` is itself
|
|
1826
|
-
an unevaluated `["Rational", n, d]` expression, its
|
|
1827
|
-
declared `n`/`d` are used exactly. Otherwise, the
|
|
1828
|
-
evaluated value is reconstructed as the closest fraction
|
|
1829
|
-
with a bounded denominator - a best-effort approximation,
|
|
1830
|
-
not exact/symbolic, since this solver has no dedicated
|
|
1831
|
-
rational-number type carried through arithmetic (see
|
|
1832
|
-
`Rational`'s docstring).
|
|
1833
|
-
"""
|
|
1834
|
-
expr = s[1]
|
|
1835
|
-
if (
|
|
1836
|
-
isinstance(expr, list)
|
|
1837
|
-
and len(expr) == 3
|
|
1838
|
-
and expr[0] == "Rational"
|
|
1839
|
-
):
|
|
1840
|
-
return int(f(expr[1], c)), int(f(expr[2], c))
|
|
1841
|
-
value = f(expr, c)
|
|
1842
|
-
if isinstance(value, int):
|
|
1843
|
-
return value, 1
|
|
1844
|
-
frac = Fraction(value).limit_denominator(10**6)
|
|
1845
|
-
return frac.numerator, frac.denominator
|
|
1846
|
-
|
|
1847
|
-
def Numerator(s):
|
|
1848
|
-
return _rational_parts(s)[0]
|
|
1849
|
-
|
|
1850
|
-
def Denominator(s):
|
|
1851
|
-
return _rational_parts(s)[1]
|
|
1852
|
-
|
|
1853
|
-
def Rational(s):
|
|
1854
|
-
"""
|
|
1855
|
-
["Rational", numerator, denominator]
|
|
1856
|
-
Evaluates to `numerator / denominator` as a plain float -
|
|
1857
|
-
there's no exact rational-number type carried through
|
|
1858
|
-
arithmetic in this solver, so precision beyond a float is
|
|
1859
|
-
only preserved when `Numerator`/`Denominator` read this
|
|
1860
|
-
expression directly, rather than its evaluated value.
|
|
1861
|
-
"""
|
|
1862
|
-
return f(s[1], c) / f(s[2], c)
|
|
1863
|
-
|
|
1864
|
-
def BooleanAnd(s):
|
|
1865
|
-
"""
|
|
1866
|
-
Boolean AND operation.
|
|
1867
|
-
["And", condition1, condition2, ...]
|
|
1868
|
-
"""
|
|
1869
|
-
for x in s[1:]:
|
|
1870
|
-
if not f(x, c):
|
|
1871
|
-
return False
|
|
1872
|
-
return True
|
|
1873
|
-
|
|
1874
|
-
def BooleanOr(s):
|
|
1875
|
-
"""
|
|
1876
|
-
Boolean OR operation.
|
|
1877
|
-
["Or", condition1, condition2, ...]
|
|
1878
|
-
"""
|
|
1879
|
-
for x in s[1:]:
|
|
1880
|
-
if f(x, c):
|
|
1881
|
-
return True
|
|
1882
|
-
return False
|
|
1883
|
-
|
|
1884
|
-
# sin, cos, tan, arcsin, arccos, arctan
|
|
1885
|
-
def Sin(s):
|
|
1886
|
-
return math.sin(f(s[1], c))
|
|
1887
|
-
|
|
1888
|
-
def Arcsin(s):
|
|
1889
|
-
return math.asin(f(s[1], c))
|
|
1890
|
-
|
|
1891
|
-
def Cos(s):
|
|
1892
|
-
return math.cos(f(s[1], c))
|
|
1893
|
-
|
|
1894
|
-
def Arccos(s):
|
|
1895
|
-
return math.acos(f(s[1], c))
|
|
1896
|
-
|
|
1897
|
-
def Tan(s):
|
|
1898
|
-
return math.tan(f(s[1], c))
|
|
1899
|
-
|
|
1900
|
-
def Arctan(s):
|
|
1901
|
-
return math.atan(f(s[1], c))
|
|
1902
|
-
|
|
1903
|
-
def Pi(s):
|
|
1904
|
-
return math.pi
|
|
1905
|
-
|
|
1906
|
-
def Variable(s):
|
|
1907
|
-
"""
|
|
1908
|
-
["Variable", variable_name]
|
|
1909
|
-
The `variable_name` must be a string.
|
|
1910
|
-
"""
|
|
1911
|
-
variable_name = s[1]
|
|
1912
|
-
if variable_name in c:
|
|
1913
|
-
return f(c[variable_name], c)
|
|
1914
|
-
else:
|
|
1915
|
-
raise KeyError(f"Variable '{variable_name}' is not defined")
|
|
1916
|
-
|
|
1917
|
-
def Function(s):
|
|
1918
|
-
"""
|
|
1919
|
-
["Function", body_expression, param_name1, param_name2, ...]
|
|
1920
|
-
Defines a CortexJS-style lambda: `body_expression` is evaluated
|
|
1921
|
-
with the given parameter names bound to whatever arguments it
|
|
1922
|
-
is called with. `Function` expressions are meant to be passed
|
|
1923
|
-
as the `function` argument of Map, Filter, and Reduce; if no
|
|
1924
|
-
parameter names are given, the anonymous placeholders "_",
|
|
1925
|
-
"_1", "_2", ... are used instead (see those functions).
|
|
1926
|
-
Evaluating a ["Function", ...] expression outside of such a
|
|
1927
|
-
context just returns it unevaluated.
|
|
1928
|
-
"""
|
|
1929
|
-
return s
|
|
1930
|
-
|
|
1931
|
-
def MultiplyByScalar(s):
|
|
1932
|
-
"""
|
|
1933
|
-
["MultiplyByScalar", array, scalar]
|
|
1934
|
-
The `array` must be an array of numeric values.
|
|
1935
|
-
The `scalar` is the number to multiply each element by.
|
|
1936
|
-
"""
|
|
1937
|
-
array = f(s[1], c)
|
|
1938
|
-
scalar = f(s[2], c)
|
|
1939
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
1940
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1941
|
-
array = [f(x, c) for x in array[1:]]
|
|
1942
|
-
return ["Array"] + _MultiplyByScalar(array, scalar)
|
|
1943
|
-
|
|
1944
|
-
def MultiplyByArray(s):
|
|
1945
|
-
"""
|
|
1946
|
-
["MultiplyByArray", array1, array2]
|
|
1947
|
-
The `array1` and `array2` must be arrays of the same length.
|
|
1948
|
-
"""
|
|
1949
|
-
array1 = f(s[1], c)
|
|
1950
|
-
array2 = f(s[2], c)
|
|
1951
|
-
if not (isinstance(array1, list) and array1[0] == "Array"):
|
|
1952
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1953
|
-
if not (isinstance(array2, list) and array2[0] == "Array"):
|
|
1954
|
-
raise ValueError("Parameter 2 must be an array.")
|
|
1955
|
-
array1 = [f(x, c) for x in array1[1:]]
|
|
1956
|
-
array2 = [f(x, c) for x in array2[1:]]
|
|
1957
|
-
if len(array1) != len(array2):
|
|
1958
|
-
raise ValueError("Both arrays must be of the same length.")
|
|
1959
|
-
return ["Array"] + _MultiplyByArray(array1, array2)
|
|
1960
|
-
|
|
1961
|
-
def AddScalar(s):
|
|
1962
|
-
"""
|
|
1963
|
-
["AddScalar", array, scalar]
|
|
1964
|
-
The `array` must be an array of numeric values.
|
|
1965
|
-
The `scalar` is the number to add to each element.
|
|
1966
|
-
"""
|
|
1967
|
-
array = f(s[1], c)
|
|
1968
|
-
scalar = f(s[2], c)
|
|
1969
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
1970
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1971
|
-
array = [f(x, c) for x in array[1:]]
|
|
1972
|
-
return ["Array"] + _AddScalar(array, scalar)
|
|
1973
|
-
|
|
1974
|
-
def SubtractScalar(s):
|
|
1975
|
-
"""
|
|
1976
|
-
["SubtractScalar", array, scalar]
|
|
1977
|
-
The `array` must be an array of numeric values.
|
|
1978
|
-
The `scalar` is the number to subtract from each element.
|
|
1979
|
-
"""
|
|
1980
|
-
array = f(s[1], c)
|
|
1981
|
-
scalar = f(s[2], c)
|
|
1982
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
1983
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1984
|
-
array = [f(x, c) for x in array[1:]]
|
|
1985
|
-
return ["Array"] + _SubtractScalar(array, scalar)
|
|
1986
|
-
|
|
1987
|
-
def AddArray(s):
|
|
1988
|
-
"""
|
|
1989
|
-
["AddArray", array1, array2]
|
|
1990
|
-
The `array1` and `array2` must be arrays of the same length.
|
|
1991
|
-
"""
|
|
1992
|
-
array1 = f(s[1], c)
|
|
1993
|
-
array2 = f(s[2], c)
|
|
1994
|
-
if not (isinstance(array1, list) and array1[0] == "Array"):
|
|
1995
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
1996
|
-
if not (isinstance(array2, list) and array2[0] == "Array"):
|
|
1997
|
-
raise ValueError("Parameter 2 must be an array.")
|
|
1998
|
-
array1 = [f(x, c) for x in array1[1:]]
|
|
1999
|
-
array2 = [f(x, c) for x in array2[1:]]
|
|
2000
|
-
if len(array1) != len(array2):
|
|
2001
|
-
raise ValueError("Both arrays must be of the same length.")
|
|
2002
|
-
return ["Array"] + _AddArray(array1, array2)
|
|
2003
|
-
|
|
2004
|
-
def SubtractArray(s):
|
|
2005
|
-
"""
|
|
2006
|
-
["SubtractArray", array1, array2]
|
|
2007
|
-
The `array1` and `array2` must be arrays of the same length.
|
|
2008
|
-
"""
|
|
2009
|
-
array1 = f(s[1], c)
|
|
2010
|
-
array2 = f(s[2], c)
|
|
2011
|
-
if not (isinstance(array1, list) and array1[0] == "Array"):
|
|
2012
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2013
|
-
if not (isinstance(array2, list) and array2[0] == "Array"):
|
|
2014
|
-
raise ValueError("Parameter 2 must be an array.")
|
|
2015
|
-
array1 = [f(x, c) for x in array1[1:]]
|
|
2016
|
-
array2 = [f(x, c) for x in array2[1:]]
|
|
2017
|
-
if len(array1) != len(array2):
|
|
2018
|
-
raise ValueError("Both arrays must be of the same length.")
|
|
2019
|
-
return ["Array"] + _SubtractArray(array1, array2)
|
|
2020
|
-
|
|
2021
|
-
def GenerateRange(s):
|
|
2022
|
-
"""
|
|
2023
|
-
["GenerateRange", end]
|
|
2024
|
-
or
|
|
2025
|
-
["GenerateRange", start, end, step]
|
|
2026
|
-
The `start`, `end`, and `step` are numeric values.
|
|
2027
|
-
"""
|
|
2028
|
-
if len(s) == 2:
|
|
2029
|
-
end = f(s[1], c)
|
|
2030
|
-
start = 0
|
|
2031
|
-
step = 1
|
|
2032
|
-
elif len(s) == 4:
|
|
2033
|
-
start = f(s[1], c)
|
|
2034
|
-
end = f(s[2], c)
|
|
2035
|
-
step = f(s[3], c)
|
|
2036
|
-
else:
|
|
2037
|
-
raise ValueError(
|
|
2038
|
-
"GenerateRange requires either 1 or 3 parameters (end or start, end, step)."
|
|
2039
|
-
)
|
|
2040
|
-
if step == 0:
|
|
2041
|
-
raise ValueError("Step cannot be zero.")
|
|
2042
|
-
if (start < end and step < 0) or (start > end and step > 0):
|
|
2043
|
-
raise ValueError("Step direction is incorrect for the given range.")
|
|
2044
|
-
result = ["Array"]
|
|
2045
|
-
if start < end:
|
|
2046
|
-
current = start
|
|
2047
|
-
while current < end:
|
|
2048
|
-
result.append(current)
|
|
2049
|
-
current += step
|
|
2050
|
-
else:
|
|
2051
|
-
current = start
|
|
2052
|
-
while current > end:
|
|
2053
|
-
result.append(current)
|
|
2054
|
-
current += step
|
|
2055
|
-
return result
|
|
2056
|
-
|
|
2057
|
-
def AtIndex(s):
|
|
2058
|
-
"""
|
|
2059
|
-
["AtIndex", array, index]
|
|
2060
|
-
The `array` must be an array of values.
|
|
2061
|
-
The `index` is the index of the element to retrieve.
|
|
2062
|
-
"""
|
|
2063
|
-
array = f(s[1], c)
|
|
2064
|
-
index = f(s[2], c)
|
|
2065
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
2066
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2067
|
-
# array = [f(x, c) for x in array[1:]]
|
|
2068
|
-
# return array[index]
|
|
2069
|
-
array = [x for x in array[1:]]
|
|
2070
|
-
return f(array[index], c)
|
|
2071
|
-
|
|
2072
|
-
def Slice(s):
|
|
2073
|
-
"""
|
|
2074
|
-
["Slice", array, start, end]
|
|
2075
|
-
The `array` must be an array of values.
|
|
2076
|
-
The `start` and `end` are the slice indices.
|
|
2077
|
-
"""
|
|
2078
|
-
array = f(s[1], c)
|
|
2079
|
-
start = f(s[2], c)
|
|
2080
|
-
end = f(s[3], c)
|
|
2081
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
2082
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2083
|
-
array = [f(x, c) for x in array[1:]]
|
|
2084
|
-
return ["Array"] + array[start:end]
|
|
2085
|
-
|
|
2086
|
-
def CumulativeProduct(s):
|
|
2087
|
-
"""
|
|
2088
|
-
["CumulativeProduct", array]
|
|
2089
|
-
The `array` must be an array of numeric values.
|
|
2090
|
-
"""
|
|
2091
|
-
array = f(s[1], c)
|
|
2092
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
2093
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2094
|
-
array = [f(x, c) for x in array[1:]]
|
|
2095
|
-
return ["Array"] + _CumulativeProduct(array)
|
|
2096
|
-
# return _CumulativeProduct(array)
|
|
2097
|
-
|
|
2098
|
-
def CumulativeSum(s):
|
|
2099
|
-
"""
|
|
2100
|
-
["CumulativeSum", array]
|
|
2101
|
-
The `array` must be an array of numeric values.
|
|
2102
|
-
"""
|
|
2103
|
-
array = f(s[1], c)
|
|
2104
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
2105
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2106
|
-
array = [f(x, c) for x in array[1:]]
|
|
2107
|
-
return ["Array"] + _CumulativeSum(array)
|
|
2108
|
-
# return
|
|
2109
|
-
|
|
2110
|
-
def Interp(s):
|
|
2111
|
-
"""
|
|
2112
|
-
["Interp", x_array, y_array, target_x]
|
|
2113
|
-
The `x_array` and `y_array` must be arrays of the same length.
|
|
2114
|
-
The `target_x` is the x value to interpolate for.
|
|
2115
|
-
"""
|
|
2116
|
-
x_array = f(s[1], c)
|
|
2117
|
-
y_array = f(s[2], c)
|
|
2118
|
-
target_x = f(s[3], c)
|
|
2119
|
-
if not (isinstance(x_array, list) and x_array[0] == "Array"):
|
|
2120
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2121
|
-
if not (isinstance(y_array, list) and y_array[0] == "Array"):
|
|
2122
|
-
raise ValueError("Parameter 2 must be an array.")
|
|
2123
|
-
x_array = [f(x, c) for x in x_array[1:]]
|
|
2124
|
-
y_array = [f(y, c) for y in y_array[1:]]
|
|
2125
|
-
return linear_interpolate(x_array, y_array, target_x)
|
|
2126
|
-
|
|
2127
|
-
def FindIntervalIndex(s):
|
|
2128
|
-
"""
|
|
2129
|
-
["FindIntervalIndex", array, target_value]
|
|
2130
|
-
The `array` must be an array of numeric values.
|
|
2131
|
-
The `target_value` is the value to find the interval index for.
|
|
2132
|
-
"""
|
|
2133
|
-
array = f(s[1], c)
|
|
2134
|
-
target_value = f(s[2], c)
|
|
2135
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
2136
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2137
|
-
array = [f(x, c) for x in array[1:]]
|
|
2138
|
-
zz = find_interpolation_bounds_2indexes(array, target_value)
|
|
2139
|
-
return zz[0]
|
|
2140
|
-
|
|
2141
|
-
def TrapezoidalIntegrate(s):
|
|
2142
|
-
"""
|
|
2143
|
-
["TrapezoidalIntegrate", function_expression, start, end, n, variable]
|
|
2144
|
-
"""
|
|
2145
|
-
if not NUMPY_AVAILABLE:
|
|
2146
|
-
raise ImportError(
|
|
2147
|
-
"TrapezoidalIntegrate requires 'numpy'. Install with 'pip install numpy'."
|
|
2148
|
-
)
|
|
2149
|
-
function_expression = s[1]
|
|
2150
|
-
start = f(s[2], c)
|
|
2151
|
-
end = f(s[3], c)
|
|
2152
|
-
n = f(s[4], c)
|
|
2153
|
-
variable = s[5]
|
|
2154
|
-
|
|
2155
|
-
t = np.linspace(start, end, n + 1)
|
|
2156
|
-
|
|
2157
|
-
# Calculate the integral using the trapezoidal rule
|
|
2158
|
-
|
|
2159
|
-
values = []
|
|
2160
|
-
for x in t:
|
|
2161
|
-
variable_name = variable[1]
|
|
2162
|
-
variable_value = x
|
|
2163
|
-
c[variable_name] = variable_value
|
|
2164
|
-
values.append(f(function_expression, c))
|
|
2165
|
-
h = (end - start) / n
|
|
2166
|
-
return h * (0.5 * values[0] + np.sum(values[1:-1]) + 0.5 * values[-1])
|
|
2167
|
-
|
|
2168
|
-
# return total_area
|
|
2169
|
-
|
|
2170
|
-
def Reduce(s):
|
|
2171
|
-
"""
|
|
2172
|
-
Two calling conventions, disambiguated by argument count:
|
|
2173
|
-
|
|
2174
|
-
CortexJS form (3 or 4 arguments):
|
|
2175
|
-
["Reduce", list, function]
|
|
2176
|
-
["Reduce", list, function, initial_value]
|
|
2177
|
-
`function` is applied as `function(accumulator, current_item)`
|
|
2178
|
-
on each element; without `initial_value`, the first element
|
|
2179
|
-
seeds the accumulator. `function` can be a call template
|
|
2180
|
-
(e.g. ["Add"]) or a ["Function", body, ...params] expression
|
|
2181
|
-
(see `_apply_fn`).
|
|
2182
|
-
|
|
2183
|
-
Original Python form (6 arguments):
|
|
2184
|
-
["Reduce", list, initial_value, function, str_name_of_accumulator, str_name_of_current, str_name_of_index]
|
|
2185
|
-
"""
|
|
2186
|
-
if len(s) <= 4:
|
|
2187
|
-
the_list = f(s[1], c)
|
|
2188
|
-
if not (isinstance(the_list, list) and the_list[0] == "Array"):
|
|
2189
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2190
|
-
elements = the_list[1:]
|
|
2191
|
-
fn_expr = s[2]
|
|
2192
|
-
|
|
2193
|
-
if len(s) == 4:
|
|
2194
|
-
accumulator = f(s[3], c)
|
|
2195
|
-
remaining = elements
|
|
2196
|
-
else:
|
|
2197
|
-
if not elements:
|
|
2198
|
-
raise ValueError(
|
|
2199
|
-
"'Reduce' on an empty collection requires an initial value."
|
|
2200
|
-
)
|
|
2201
|
-
accumulator = f(elements[0], c)
|
|
2202
|
-
remaining = elements[1:]
|
|
2203
|
-
|
|
2204
|
-
for x in remaining:
|
|
2205
|
-
accumulator = _apply_fn(fn_expr, [accumulator, x])
|
|
2206
|
-
return accumulator
|
|
2207
|
-
|
|
2208
|
-
the_list = f(s[1], c)[1:]
|
|
2209
|
-
initial_value = f(s[2], c)
|
|
2210
|
-
function_expression = s[3]
|
|
2211
|
-
|
|
2212
|
-
_accumulator = s[4]
|
|
2213
|
-
name_accumulator = _accumulator[1]
|
|
2214
|
-
|
|
2215
|
-
_current = s[5]
|
|
2216
|
-
name_current = _current[1]
|
|
2217
|
-
|
|
2218
|
-
_index = s[6]
|
|
2219
|
-
name_index = _index[1]
|
|
2220
|
-
|
|
2221
|
-
c[name_accumulator] = initial_value
|
|
2222
|
-
|
|
2223
|
-
for i, x in enumerate(the_list):
|
|
2224
|
-
c[name_current] = x
|
|
2225
|
-
c[name_index] = i
|
|
2226
|
-
c[name_accumulator] = f(function_expression, c)
|
|
2227
|
-
|
|
2228
|
-
return c[name_accumulator]
|
|
2229
|
-
|
|
2230
|
-
def Product(s):
|
|
2231
|
-
"""
|
|
2232
|
-
["Product", array]
|
|
2233
|
-
Multiplies together the numeric elements of `array`.
|
|
2234
|
-
"""
|
|
2235
|
-
the_list = f(s[1], c)
|
|
2236
|
-
if not (isinstance(the_list, list) and the_list[0] == "Array"):
|
|
2237
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2238
|
-
result = 1
|
|
2239
|
-
for x in the_list[1:]:
|
|
2240
|
-
result *= f(x, c)
|
|
2241
|
-
return result
|
|
2242
|
-
|
|
2243
|
-
def Appended(s):
|
|
2244
|
-
"""
|
|
2245
|
-
["Appended", array, value]
|
|
2246
|
-
The `array` must be an array of values.
|
|
2247
|
-
The `value` is the value to append to the array.
|
|
2248
|
-
"""
|
|
2249
|
-
array = f(s[1], c)
|
|
2250
|
-
|
|
2251
|
-
if not (isinstance(array, list) and array[0] == "Array"):
|
|
2252
|
-
raise ValueError("Parameter 1 must be an array.")
|
|
2253
|
-
|
|
2254
|
-
value = f(s[2], c)
|
|
2255
|
-
|
|
2256
|
-
array = [x for x in array[1:]]
|
|
2257
|
-
array.append(value)
|
|
2258
|
-
return ["Array"] + array
|
|
2259
|
-
|
|
2260
|
-
constructs = {
|
|
2261
|
-
"Sum": Sum,
|
|
2262
|
-
"Add": Add,
|
|
2263
|
-
"Subtract": Subtract,
|
|
2264
|
-
"Constants": Constants,
|
|
2265
|
-
"Switch": Switch,
|
|
2266
|
-
"StrictSwitch": StrictSwitch,
|
|
2267
|
-
"If": If,
|
|
2268
|
-
"Multiply": lambda s: reduce(
|
|
2269
|
-
lambda a, b: float(a) * float(b), [f(x, c) for x in s[1:]]
|
|
2270
|
-
),
|
|
2271
|
-
"Divide": lambda s: f(s[1], c) / f(s[2], c),
|
|
2272
|
-
"Negate": lambda s: -f(s[1], c),
|
|
2273
|
-
"Power": lambda s: pow(f(s[1], c), f(s[2], c)),
|
|
2274
|
-
"Root": lambda s: pow(f(s[1], c), 1.0 / f(s[2], c)),
|
|
2275
|
-
"Sqrt": lambda s: pow(f(s[1], c), 1.0 / 2),
|
|
2276
|
-
"Square": lambda s: pow(f(s[1], c), 2),
|
|
2277
|
-
"Exp": lambda s: math.exp(f(s[1], c)),
|
|
2278
|
-
# CortexJS-compatible: ["Log", x] is log base 10; ["Log", x, b] is
|
|
2279
|
-
# log base b. Use "Ln" for natural log. (BREAKING as of 2.0.0 -
|
|
2280
|
-
# "Log" previously meant natural log.)
|
|
2281
|
-
"Log": lambda s: (
|
|
2282
|
-
math.log10(f(s[1], c))
|
|
2283
|
-
if len(s) == 2
|
|
2284
|
-
else math.log(f(s[1], c), f(s[2], c))
|
|
2285
|
-
),
|
|
2286
|
-
"Log2": lambda s: math.log2(f(s[1], c)),
|
|
2287
|
-
"Log10": lambda s: math.log10(f(s[1], c)),
|
|
2288
|
-
"Ln": lambda s: math.log(f(s[1], c)),
|
|
2289
|
-
"Lb": lambda s: math.log2(f(s[1], c)), # CortexJS name for Log2
|
|
2290
|
-
"Lg": lambda s: math.log10(f(s[1], c)), # CortexJS name for Log10
|
|
2291
|
-
"LogOnePlus": lambda s: math.log1p(f(s[1], c)),
|
|
2292
|
-
# "Equal": lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
|
|
2293
|
-
"Equal": lambda s: comparison_safe_converter(f(s[1], c))
|
|
2294
|
-
== comparison_safe_converter(f(s[2], c)),
|
|
2295
|
-
"IsTrue": lambda s: bool(f(s[1], c)),
|
|
2296
|
-
"IsFalse": lambda s: not bool(f(s[1], c)),
|
|
2297
|
-
"StrictEqual": lambda s: f(s[1], c) == f(s[2], c),
|
|
2298
|
-
"IdenticallyEqual": IdenticallyEqual,
|
|
2299
|
-
"Congruent": Congruent,
|
|
2300
|
-
# "Greater": lambda s: f(s[1], c) > f(s[2], c),
|
|
2301
|
-
"Greater": Greater,
|
|
2302
|
-
# "GreaterEqual": lambda s: f(s[1], c) >= f(s[2], c),
|
|
2303
|
-
"GreaterEqual": GreaterEqual,
|
|
2304
|
-
# "Less": lambda s: f(s[1], c) < f(s[2], c),
|
|
2305
|
-
"Less": Less,
|
|
2306
|
-
# "LessEqual": lambda s: f(s[1], c) <= f(s[2], c),
|
|
2307
|
-
"LessEqual": LessEqual,
|
|
2308
|
-
# "NotEqual": lambda s: f(s[1], c) != f(s[2], c),
|
|
2309
|
-
"NotEqual": lambda s: comparison_safe_converter(f(s[1], c))
|
|
2310
|
-
!= comparison_safe_converter(f(s[2], c)),
|
|
2311
|
-
"And": BooleanAnd,
|
|
2312
|
-
"Or": BooleanOr,
|
|
2313
|
-
"Abs": lambda s: abs(f(s[1], c)),
|
|
2314
|
-
"Round": lambda s: (
|
|
2315
|
-
round(f(s[1], c), f(s[2], c))
|
|
2316
|
-
if len(s) == 3
|
|
2317
|
-
else int(round(f(s[1], c)))
|
|
2318
|
-
),
|
|
2319
|
-
"Max": Max,
|
|
2320
|
-
"Min": Min,
|
|
2321
|
-
"Average": Average,
|
|
2322
|
-
"Mean": Average, # CortexJS name for Average
|
|
2323
|
-
"Median": Median,
|
|
2324
|
-
"Length": Length,
|
|
2325
|
-
"Count": Length, # CortexJS name for Length
|
|
2326
|
-
"Any": Any,
|
|
2327
|
-
"All": All,
|
|
2328
|
-
"Array": Arr,
|
|
2329
|
-
"List": lambda s: ["Array"] + [f(x, c) for x in s[1:]], # CortexJS name for Array
|
|
2330
|
-
"In": In,
|
|
2331
|
-
"Not_in": Not_in,
|
|
2332
|
-
"Element": In, # CortexJS name for In (["Element", value, set])
|
|
2333
|
-
"NotElement": Not_in, # CortexJS name for Not_in
|
|
2334
|
-
"Contains_any_of": Contains_any_of,
|
|
2335
|
-
"Contains_all_of": Contains_all_of,
|
|
2336
|
-
"Contains_none_of": Contains_none_of,
|
|
2337
|
-
"NotIn": Not_in,
|
|
2338
|
-
"ContainsAnyOf": Contains_any_of,
|
|
2339
|
-
"ContainsAllOf": Contains_all_of,
|
|
2340
|
-
"ContainsNoneOf": Contains_none_of,
|
|
2341
|
-
"Int": Int,
|
|
2342
|
-
"Float": Float,
|
|
2343
|
-
"Floor": Floor,
|
|
2344
|
-
"Ceil": Ceil,
|
|
2345
|
-
"Str": Str,
|
|
2346
|
-
# --- Strings ---
|
|
2347
|
-
"String": String,
|
|
2348
|
-
"StringJoin": StringJoin,
|
|
2349
|
-
"ToUpperCase": lambda s: f(s[1], c).upper(),
|
|
2350
|
-
"ToLowerCase": lambda s: f(s[1], c).lower(),
|
|
2351
|
-
"CaseFold": lambda s: f(s[1], c).casefold(),
|
|
2352
|
-
"Trim": lambda s: f(s[1], c).strip(),
|
|
2353
|
-
"TrimStart": lambda s: f(s[1], c).lstrip(),
|
|
2354
|
-
"TrimEnd": lambda s: f(s[1], c).rstrip(),
|
|
2355
|
-
"StringSplit": StringSplit,
|
|
2356
|
-
"StringReplace": StringReplace,
|
|
2357
|
-
"StringCompare": StringCompare,
|
|
2358
|
-
"StringRepeat": StringRepeat,
|
|
2359
|
-
"PadStart": PadStart,
|
|
2360
|
-
"PadEnd": PadEnd,
|
|
2361
|
-
"Characters": Characters,
|
|
2362
|
-
"GraphemeClusters": Characters, # CortexJS synonym for Characters
|
|
2363
|
-
"Utf8": Utf8,
|
|
2364
|
-
"Utf16": Utf16,
|
|
2365
|
-
"UnicodeScalars": UnicodeScalars,
|
|
2366
|
-
"StringFrom": StringFrom,
|
|
2367
|
-
"IntegerString": IntegerString,
|
|
2368
|
-
"DigitsFrom": DigitsFrom,
|
|
2369
|
-
"NumberFrom": NumberFrom,
|
|
2370
|
-
"RegExp": RegExp,
|
|
2371
|
-
"IsMatch": IsMatch,
|
|
2372
|
-
"StringMatch": StringMatch,
|
|
2373
|
-
"StringMatchAll": StringMatchAll,
|
|
2374
|
-
"Not": Not,
|
|
2375
|
-
# "IsDefined": lambda s: s[1] in c,
|
|
2376
|
-
"IsDefined": IsDefined,
|
|
2377
|
-
"IsUndefined": IsUndefined,
|
|
2378
|
-
"Map": Map,
|
|
2379
|
-
"StrictMap": StrictMap,
|
|
2380
|
-
"Filter": Filter,
|
|
2381
|
-
"HasMatchingSublist": HasMatchingSublist,
|
|
2382
|
-
"Strptime": Strptime,
|
|
2383
|
-
"Strftime": Strftime,
|
|
2384
|
-
"Today": Today,
|
|
2385
|
-
"Now": Now,
|
|
2386
|
-
"TimeDeltaWeeks": TimeDeltaWeeks,
|
|
2387
|
-
"TimeDeltaHours": TimeDeltaHours,
|
|
2388
|
-
"TimeDeltaMinutes": TimeDeltaMinutes,
|
|
2389
|
-
"TimeDeltaDays": TimeDeltaDays,
|
|
2390
|
-
"Function": Function,
|
|
2391
|
-
"Variable": Variable,
|
|
2392
|
-
"MultiplyByScalar": MultiplyByScalar,
|
|
2393
|
-
"MultiplyByArray": MultiplyByArray,
|
|
2394
|
-
"AddScalar": AddScalar,
|
|
2395
|
-
"SubtractScalar": SubtractScalar,
|
|
2396
|
-
"AddArray": AddArray,
|
|
2397
|
-
"SubtractArray": SubtractArray,
|
|
2398
|
-
"GenerateRange": GenerateRange,
|
|
2399
|
-
"AtIndex": AtIndex,
|
|
2400
|
-
"Slice": Slice,
|
|
2401
|
-
"CumulativeProduct": CumulativeProduct,
|
|
2402
|
-
"CumulativeSum": CumulativeSum,
|
|
2403
|
-
"Interp": Interp,
|
|
2404
|
-
"FindIntervalIndex": FindIntervalIndex,
|
|
2405
|
-
"TrapezoidalIntegrate": TrapezoidalIntegrate,
|
|
2406
|
-
"Reduce": Reduce,
|
|
2407
|
-
"Product": Product,
|
|
2408
|
-
"Appended": Appended,
|
|
2409
|
-
"Sin": Sin,
|
|
2410
|
-
"Cos": Cos,
|
|
2411
|
-
"Tan": Tan,
|
|
2412
|
-
"Arcsin": Arcsin,
|
|
2413
|
-
"Arccos": Arccos,
|
|
2414
|
-
"Arctan": Arctan,
|
|
2415
|
-
"Arctan2": lambda s: math.atan2(f(s[1], c), f(s[2], c)),
|
|
2416
|
-
"Pi": Pi,
|
|
2417
|
-
"Which": Which, # CortexJS multi-branch conditional (not Switch - see Which's docstring)
|
|
2418
|
-
# --- Trigonometric: reciprocal, hyperbolic, area-hyperbolic ---
|
|
2419
|
-
"Cot": lambda s: 1 / math.tan(f(s[1], c)),
|
|
2420
|
-
"Sec": lambda s: 1 / math.cos(f(s[1], c)),
|
|
2421
|
-
"Csc": lambda s: 1 / math.sin(f(s[1], c)),
|
|
2422
|
-
"Arccot": lambda s: math.atan(1 / f(s[1], c)),
|
|
2423
|
-
"Arcsec": lambda s: math.acos(1 / f(s[1], c)),
|
|
2424
|
-
"Arccsc": lambda s: math.asin(1 / f(s[1], c)),
|
|
2425
|
-
"Sinh": lambda s: math.sinh(f(s[1], c)),
|
|
2426
|
-
"Cosh": lambda s: math.cosh(f(s[1], c)),
|
|
2427
|
-
"Tanh": lambda s: math.tanh(f(s[1], c)),
|
|
2428
|
-
"Coth": lambda s: 1 / math.tanh(f(s[1], c)),
|
|
2429
|
-
"Sech": lambda s: 1 / math.cosh(f(s[1], c)),
|
|
2430
|
-
"Csch": lambda s: 1 / math.sinh(f(s[1], c)),
|
|
2431
|
-
"Arsinh": lambda s: math.asinh(f(s[1], c)),
|
|
2432
|
-
"Arcosh": lambda s: math.acosh(f(s[1], c)),
|
|
2433
|
-
"Artanh": lambda s: math.atanh(f(s[1], c)),
|
|
2434
|
-
"Arcoth": lambda s: math.atanh(1 / f(s[1], c)),
|
|
2435
|
-
"Arsech": lambda s: math.acosh(1 / f(s[1], c)),
|
|
2436
|
-
"Arcsch": lambda s: math.asinh(1 / f(s[1], c)),
|
|
2437
|
-
"Hypot": lambda s: math.hypot(f(s[1], c), f(s[2], c)),
|
|
2438
|
-
"Sinc": lambda s: (
|
|
2439
|
-
1.0 if f(s[1], c) == 0 else math.sin(f(s[1], c)) / f(s[1], c)
|
|
2440
|
-
),
|
|
2441
|
-
# --- Constants ---
|
|
2442
|
-
"Degrees": lambda s: math.pi / 180,
|
|
2443
|
-
"ExponentialE": lambda s: math.e,
|
|
2444
|
-
"GoldenRatio": lambda s: (1 + math.sqrt(5)) / 2,
|
|
2445
|
-
"MachineEpsilon": lambda s: sys.float_info.epsilon,
|
|
2446
|
-
"CatalanConstant": lambda s: 0.915965594177219015054603514932384110774,
|
|
2447
|
-
"EulerGamma": lambda s: 0.5772156649015328606065120900824024310421,
|
|
2448
|
-
"Rational": Rational,
|
|
2449
|
-
"Numerator": Numerator,
|
|
2450
|
-
"Denominator": Denominator,
|
|
2451
|
-
# --- Number theory / special functions ---
|
|
2452
|
-
"Chop": lambda s: 0 if abs(f(s[1], c)) < 1e-10 else f(s[1], c),
|
|
2453
|
-
"Mod": lambda s: f(s[1], c) % f(s[2], c),
|
|
2454
|
-
"Clamp": Clamp,
|
|
2455
|
-
"GCD": lambda s: math.gcd(int(f(s[1], c)), int(f(s[2], c))),
|
|
2456
|
-
"LCM": lambda s: math.lcm(int(f(s[1], c)), int(f(s[2], c))),
|
|
2457
|
-
"Factorial": lambda s: math.factorial(int(f(s[1], c))),
|
|
2458
|
-
"Binomial": lambda s: math.comb(int(f(s[1], c)), int(f(s[2], c))),
|
|
2459
|
-
"IsPrime": IsPrime,
|
|
2460
|
-
"Erf": lambda s: math.erf(f(s[1], c)),
|
|
2461
|
-
"Erfc": lambda s: math.erfc(f(s[1], c)),
|
|
2462
|
-
# --- Boolean logic ---
|
|
2463
|
-
"Xor": lambda s: bool(f(s[1], c)) ^ bool(f(s[2], c)),
|
|
2464
|
-
"Nand": lambda s: not all(f(x, c) for x in s[1:]),
|
|
2465
|
-
"Nor": lambda s: not any(f(x, c) for x in s[1:]),
|
|
2466
|
-
"Implies": lambda s: (not f(s[1], c)) or bool(f(s[2], c)),
|
|
2467
|
-
"Equivalent": lambda s: bool(f(s[1], c)) == bool(f(s[2], c)),
|
|
2468
|
-
# --- Statistics ---
|
|
2469
|
-
"Variance": Variance,
|
|
2470
|
-
"StandardDeviation": StandardDeviation,
|
|
2471
|
-
"PopulationVariance": PopulationVariance,
|
|
2472
|
-
"PopulationStandardDeviation": PopulationStandardDeviation,
|
|
2473
|
-
"Mode": Mode,
|
|
2474
|
-
"Quartiles": Quartiles,
|
|
2475
|
-
"InterquartileRange": InterquartileRange,
|
|
2476
|
-
"Covariance": Covariance,
|
|
2477
|
-
"Correlation": Correlation,
|
|
2478
|
-
# --- Collections ---
|
|
2479
|
-
"First": First,
|
|
2480
|
-
"Second": Second,
|
|
2481
|
-
"Third": Third,
|
|
2482
|
-
"Last": Last,
|
|
2483
|
-
"Rest": Rest,
|
|
2484
|
-
"Most": Most,
|
|
2485
|
-
"Reverse": Reverse,
|
|
2486
|
-
"Sort": Sort,
|
|
2487
|
-
"IsEmpty": IsEmpty,
|
|
2488
|
-
"Range": Range,
|
|
2489
|
-
"Join": Join,
|
|
2490
|
-
"Unique": Unique,
|
|
2491
|
-
"Zip": Zip,
|
|
2492
|
-
"At": At,
|
|
2493
|
-
"Take": Take,
|
|
2494
|
-
"Drop": Drop,
|
|
2495
|
-
"TakeWhile": TakeWhile,
|
|
2496
|
-
"DropWhile": DropWhile,
|
|
2497
|
-
"Contains": Contains,
|
|
2498
|
-
"IndexOf": IndexOf,
|
|
2499
|
-
"IndexWhere": IndexWhere,
|
|
2500
|
-
"Find": Find,
|
|
2501
|
-
"CountIf": CountIf,
|
|
2502
|
-
"Position": Position,
|
|
2503
|
-
"RotateLeft": RotateLeft,
|
|
2504
|
-
"RotateRight": RotateRight,
|
|
2505
|
-
"MaxBy": MaxBy,
|
|
2506
|
-
"MinBy": MinBy,
|
|
2507
|
-
"ArgMax": ArgMax,
|
|
2508
|
-
"ArgMin": ArgMin,
|
|
2509
|
-
"Ordering": Ordering,
|
|
2510
|
-
"FlatMap": FlatMap,
|
|
2511
|
-
"Scan": Scan,
|
|
2512
|
-
"Differences": Differences,
|
|
2513
|
-
"Fold": Fold,
|
|
2514
|
-
"Dedup": Dedup,
|
|
2515
|
-
"Append": Appended, # CortexJS name for Appended
|
|
2516
|
-
"Insert": Insert,
|
|
2517
|
-
"DeleteAt": DeleteAt,
|
|
2518
|
-
"ReplaceAt": ReplaceAt,
|
|
2519
|
-
"Partition": Partition,
|
|
2520
|
-
"Chunk": Chunk,
|
|
2521
|
-
"GroupBy": GroupBy,
|
|
2522
|
-
"ChunkBy": ChunkBy,
|
|
2523
|
-
"Tally": Tally,
|
|
2524
|
-
# --- Set algebra (over Array - no dedicated Set type) ---
|
|
2525
|
-
"Union": Union,
|
|
2526
|
-
"Intersection": Intersection,
|
|
2527
|
-
"SetMinus": SetMinus,
|
|
2528
|
-
"SymmetricDifference": SymmetricDifference,
|
|
2529
|
-
}
|
|
2530
817
|
if not s:
|
|
2531
818
|
# Empty equation given - []
|
|
2532
819
|
return None
|
|
2533
820
|
if s[0] in constructs:
|
|
821
|
+
if s[0] in blacklist:
|
|
822
|
+
raise MathJSONException(
|
|
823
|
+
PermissionError(
|
|
824
|
+
f"'{s[0]}' has been disabled in this solver instance."
|
|
825
|
+
),
|
|
826
|
+
s,
|
|
827
|
+
mathjson_construct=s[0],
|
|
828
|
+
)
|
|
2534
829
|
try:
|
|
2535
|
-
return constructs[s[0]](s)
|
|
830
|
+
return constructs[s[0]](f, c, solver_parameters, s)
|
|
2536
831
|
|
|
2537
832
|
# except RecursionError:
|
|
2538
833
|
# return s[0]
|
|
@@ -2574,7 +869,9 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
|
|
|
2574
869
|
return f
|
|
2575
870
|
|
|
2576
871
|
|
|
2577
|
-
def extract_variables(
|
|
872
|
+
def extract_variables(
|
|
873
|
+
s: MathJSONExpression, li: set[str], ignore_list: set[str]
|
|
874
|
+
) -> set[str]:
|
|
2578
875
|
constructs = [
|
|
2579
876
|
"Add",
|
|
2580
877
|
"Sum",
|
|
@@ -2751,6 +1048,88 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
|
|
|
2751
1048
|
"IsPrime",
|
|
2752
1049
|
"Erf",
|
|
2753
1050
|
"Erfc",
|
|
1051
|
+
"PowerMod",
|
|
1052
|
+
"ModularInverse",
|
|
1053
|
+
"IntegerSqrt",
|
|
1054
|
+
"FactorInteger",
|
|
1055
|
+
"PrimeFactors",
|
|
1056
|
+
"PrimeNu",
|
|
1057
|
+
"PrimeOmega",
|
|
1058
|
+
"Radical",
|
|
1059
|
+
"IsSquareFree",
|
|
1060
|
+
"Divisors",
|
|
1061
|
+
"Sigma0",
|
|
1062
|
+
"Sigma1",
|
|
1063
|
+
"SigmaMinus1",
|
|
1064
|
+
"DivisorSigma",
|
|
1065
|
+
"Divides",
|
|
1066
|
+
"Totient",
|
|
1067
|
+
"IsPerfectPower",
|
|
1068
|
+
"NthPrime",
|
|
1069
|
+
"NextPrime",
|
|
1070
|
+
"PrimePi",
|
|
1071
|
+
"ExtendedGCD",
|
|
1072
|
+
"ChineseRemainder",
|
|
1073
|
+
"CarmichaelLambda",
|
|
1074
|
+
"JacobiSymbol",
|
|
1075
|
+
"LegendreSymbol",
|
|
1076
|
+
"MultiplicativeOrder",
|
|
1077
|
+
"PrimitiveRoot",
|
|
1078
|
+
"LucasL",
|
|
1079
|
+
"CatalanNumber",
|
|
1080
|
+
"BernoulliB",
|
|
1081
|
+
"ContinuedFraction",
|
|
1082
|
+
"FromContinuedFraction",
|
|
1083
|
+
"IntegerDigits",
|
|
1084
|
+
"DigitCount",
|
|
1085
|
+
"DigitSum",
|
|
1086
|
+
"FromDigits",
|
|
1087
|
+
"IsSquare",
|
|
1088
|
+
"IsTriangular",
|
|
1089
|
+
"IsPentagonal",
|
|
1090
|
+
"IsOctahedral",
|
|
1091
|
+
"IsCenteredSquare",
|
|
1092
|
+
"IsPerfect",
|
|
1093
|
+
"IsAbundant",
|
|
1094
|
+
"IsHappy",
|
|
1095
|
+
"Gamma",
|
|
1096
|
+
"GammaLn",
|
|
1097
|
+
"Beta",
|
|
1098
|
+
"Factorial2",
|
|
1099
|
+
"ErfInv",
|
|
1100
|
+
"LambertW",
|
|
1101
|
+
"AGM",
|
|
1102
|
+
"EllipticK",
|
|
1103
|
+
"EllipticE",
|
|
1104
|
+
"Hypergeometric1F1",
|
|
1105
|
+
"Hypergeometric2F1",
|
|
1106
|
+
"BesselJ",
|
|
1107
|
+
"BesselY",
|
|
1108
|
+
"BesselI",
|
|
1109
|
+
"BesselK",
|
|
1110
|
+
"AiryAi",
|
|
1111
|
+
"AiryBi",
|
|
1112
|
+
"AiryAiPrime",
|
|
1113
|
+
"AiryBiPrime",
|
|
1114
|
+
"Zeta",
|
|
1115
|
+
"GammaRegularized",
|
|
1116
|
+
"BetaRegularized",
|
|
1117
|
+
"Choose",
|
|
1118
|
+
"Fibonacci",
|
|
1119
|
+
"Multinomial",
|
|
1120
|
+
"Subfactorial",
|
|
1121
|
+
"BellNumber",
|
|
1122
|
+
"PowerSet",
|
|
1123
|
+
"Permutations",
|
|
1124
|
+
"Combinations",
|
|
1125
|
+
"CartesianProduct",
|
|
1126
|
+
"Head",
|
|
1127
|
+
"Tail",
|
|
1128
|
+
"Hold",
|
|
1129
|
+
"Identity",
|
|
1130
|
+
"Type",
|
|
1131
|
+
"IsSame",
|
|
1132
|
+
"Same",
|
|
2754
1133
|
"Xor",
|
|
2755
1134
|
"Nand",
|
|
2756
1135
|
"Nor",
|
|
@@ -2765,6 +1144,18 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
|
|
|
2765
1144
|
"InterquartileRange",
|
|
2766
1145
|
"Covariance",
|
|
2767
1146
|
"Correlation",
|
|
1147
|
+
"Skewness",
|
|
1148
|
+
"Kurtosis",
|
|
1149
|
+
"LinearRegression",
|
|
1150
|
+
"PolynomialFit",
|
|
1151
|
+
"NormalDistribution",
|
|
1152
|
+
"BinomialDistribution",
|
|
1153
|
+
"PoissonDistribution",
|
|
1154
|
+
"UniformDistribution",
|
|
1155
|
+
"ExponentialDistribution",
|
|
1156
|
+
"PDF",
|
|
1157
|
+
"CDF",
|
|
1158
|
+
"Quantile",
|
|
2768
1159
|
"First",
|
|
2769
1160
|
"Second",
|
|
2770
1161
|
"Third",
|
|
@@ -2814,6 +1205,14 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
|
|
|
2814
1205
|
"Intersection",
|
|
2815
1206
|
"SetMinus",
|
|
2816
1207
|
"SymmetricDifference",
|
|
1208
|
+
"Subset",
|
|
1209
|
+
"SubsetEqual",
|
|
1210
|
+
"Superset",
|
|
1211
|
+
"SupersetEqual",
|
|
1212
|
+
"NotSubset",
|
|
1213
|
+
"NotSuperset",
|
|
1214
|
+
"Interval",
|
|
1215
|
+
"Open",
|
|
2817
1216
|
]
|
|
2818
1217
|
if isinstance(s, str):
|
|
2819
1218
|
if s in ignore_list:
|
|
@@ -2836,11 +1235,7 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
|
|
|
2836
1235
|
# ["If", [cond, val], ..., else_val].
|
|
2837
1236
|
is_cortexjs_form = len(s) > 1 and (
|
|
2838
1237
|
not isinstance(s[1], list)
|
|
2839
|
-
or (
|
|
2840
|
-
bool(s[1])
|
|
2841
|
-
and isinstance(s[1][0], str)
|
|
2842
|
-
and s[1][0] in constructs
|
|
2843
|
-
)
|
|
1238
|
+
or (bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs)
|
|
2844
1239
|
)
|
|
2845
1240
|
if is_cortexjs_form:
|
|
2846
1241
|
for x in s[1:]:
|
|
@@ -2861,6 +1256,27 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
|
|
|
2861
1256
|
ignore_list.add("_")
|
|
2862
1257
|
if len(s) > 1:
|
|
2863
1258
|
li.update(extract_variables(s[1], li, ignore_list))
|
|
1259
|
+
elif s[0] in ("Head", "Tail", "Hold", "IsSame", "Same"):
|
|
1260
|
+
# These deliberately never evaluate their arguments either
|
|
1261
|
+
# (Head/Tail/Hold work on the raw, unevaluated expression
|
|
1262
|
+
# tree; IsSame/Same do a pure structural comparison of the
|
|
1263
|
+
# two raw trees) - same reasoning as the unrecognized-
|
|
1264
|
+
# construct case below, just for constructs that *are*
|
|
1265
|
+
# recognized. A bare name inside their arguments is never
|
|
1266
|
+
# resolved as a parameter reference, so it's not a free
|
|
1267
|
+
# variable to supply.
|
|
1268
|
+
pass
|
|
1269
|
+
elif s[0] not in constructs:
|
|
1270
|
+
# Unrecognized construct (e.g. "Color", "Quantity" - anything
|
|
1271
|
+
# this solver doesn't implement): f() never evaluates or
|
|
1272
|
+
# substitutes into such expressions either (its fallback for
|
|
1273
|
+
# an unknown head is to return the whole list unchanged), so
|
|
1274
|
+
# none of its arguments are free variables to supply. Treat
|
|
1275
|
+
# the whole thing as opaque data rather than recursing into
|
|
1276
|
+
# it, so a decorative/unrelated subtree (e.g. a color literal
|
|
1277
|
+
# meant for something else downstream) doesn't get reported
|
|
1278
|
+
# as a required parameter.
|
|
1279
|
+
pass
|
|
2864
1280
|
else:
|
|
2865
1281
|
for x in s[1:]:
|
|
2866
1282
|
li.update(extract_variables(x, li, ignore_list))
|