mathjson-solver 2.2.1__py3-none-any.whl → 2.4.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.
@@ -1,197 +1,12 @@
1
1
  import numbers
2
2
  import sys
3
- from typing import Union, Any
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 is_numeric(x):
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,765 @@ def translate_v1_mathjson(expr):
348
43
  return expr
349
44
 
350
45
 
351
- def create_mathjson_solver(solver_parameters, legacy_v1=False):
352
- def f(s, *args):
353
- if args:
354
- c = deepcopy(args[0])
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
+ DateDiffSeconds,
196
+ DateDiffMinutes,
197
+ DateDiffHours,
198
+ DateDiffDays,
199
+ DateDiffYears,
200
+ )
201
+ from ._functional_constructs import (
202
+ Fold,
203
+ Map,
204
+ StrictMap,
205
+ Filter,
206
+ Reduce,
207
+ )
208
+ from ._number_theory_constructs import (
209
+ IsPrime,
210
+ FactorInteger,
211
+ PrimeFactors,
212
+ PrimeNu,
213
+ PrimeOmega,
214
+ Radical,
215
+ IsSquareFree,
216
+ Divisors,
217
+ Sigma0,
218
+ Sigma1,
219
+ SigmaMinus1,
220
+ DivisorSigma,
221
+ Totient,
222
+ IsPerfectPower,
223
+ NthPrime,
224
+ NextPrime,
225
+ PrimePi,
226
+ ExtendedGCD,
227
+ ChineseRemainder,
228
+ CarmichaelLambda,
229
+ JacobiSymbol,
230
+ MultiplicativeOrder,
231
+ PrimitiveRoot,
232
+ LucasL,
233
+ BernoulliB,
234
+ ContinuedFraction,
235
+ FromContinuedFraction,
236
+ IntegerDigits,
237
+ DigitCount,
238
+ DigitSum,
239
+ FromDigits,
240
+ IsSquare,
241
+ IsTriangular,
242
+ IsPentagonal,
243
+ IsOctahedral,
244
+ IsCenteredSquare,
245
+ IsPerfect,
246
+ IsAbundant,
247
+ IsHappy,
248
+ )
249
+ from ._special_function_constructs import (
250
+ Beta,
251
+ Factorial2,
252
+ ErfInv,
253
+ LambertW,
254
+ AGM,
255
+ EllipticK,
256
+ EllipticE,
257
+ Hypergeometric1F1,
258
+ Hypergeometric2F1,
259
+ BesselJ,
260
+ BesselY,
261
+ BesselI,
262
+ BesselK,
263
+ AiryAi,
264
+ AiryBi,
265
+ AiryAiPrime,
266
+ AiryBiPrime,
267
+ Zeta,
268
+ GammaRegularized,
269
+ BetaRegularized,
270
+ )
271
+ from ._statistics_constructs import (
272
+ Variance,
273
+ StandardDeviation,
274
+ PopulationVariance,
275
+ PopulationStandardDeviation,
276
+ Mode,
277
+ Quartiles,
278
+ InterquartileRange,
279
+ Covariance,
280
+ Correlation,
281
+ Skewness,
282
+ Kurtosis,
283
+ LinearRegression,
284
+ PolynomialFit,
285
+ NormalDistribution,
286
+ BinomialDistribution,
287
+ PoissonDistribution,
288
+ UniformDistribution,
289
+ ExponentialDistribution,
290
+ PDF,
291
+ CDF,
292
+ Quantile,
293
+ )
294
+ from ._string_constructs import (
295
+ Str,
296
+ String,
297
+ StringJoin,
298
+ Utf8,
299
+ Utf16,
300
+ UnicodeScalars,
301
+ StringFrom,
302
+ Characters,
303
+ StringSplit,
304
+ StringReplace,
305
+ StringCompare,
306
+ IntegerString,
307
+ DigitsFrom,
308
+ NumberFrom,
309
+ StringRepeat,
310
+ PadStart,
311
+ PadEnd,
312
+ RegExp,
313
+ IsMatch,
314
+ StringMatch,
315
+ StringMatchAll,
316
+ )
317
+ from ._trig_constructs import (
318
+ Sin,
319
+ Arcsin,
320
+ Cos,
321
+ Arccos,
322
+ Tan,
323
+ Arctan,
324
+ Pi,
325
+ )
326
+
327
+
328
+ def If(f, c, solver_parameters, s):
329
+ if len(s) < 3:
330
+ raise ValueError("Wrong parameters for 'If'")
331
+
332
+ # Detect the CortexJS flat form: ["If", cond, then] or
333
+ # ["If", cond, then, else]. In the Python pair-form below,
334
+ # s[1] is always a [condition, value] pair whose first
335
+ # element (the condition) is itself a MathJSON construct
336
+ # call, e.g. ["Equal", 1, 0]. A CortexJS flat condition is
337
+ # either not a list at all, or is itself such a construct
338
+ # call (its own first element is a *known construct name*).
339
+ # Requiring a known name - rather than any string - keeps a
340
+ # Python-form condition that is a bare parameter reference,
341
+ # e.g. ["If", ["my_flag", "yes"], "no"], from being
342
+ # misdetected as CortexJS form.
343
+ is_cortexjs_form = not isinstance(s[1], list) or (
344
+ bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs
345
+ )
346
+
347
+ if is_cortexjs_form:
348
+ if len(s) not in (3, 4):
349
+ raise ValueError("Wrong parameters for 'If'")
350
+ if f(s[1], c):
351
+ return f(s[2], c)
352
+ elif len(s) == 4:
353
+ return f(s[3], c)
355
354
  else:
356
- c = {}
357
- # c = deepcopy(kwargs.get("c", {}))
355
+ return None # CortexJS: Nothing, no else and condition false
356
+
357
+ for x in s[1:-1]:
358
+ if len(x) != 2:
359
+ raise ValueError("Wrong if or elif in 'If'")
360
+ try:
361
+ if f(x[0], c):
362
+ try:
363
+ return f(x[1], c)
364
+ except MathJSONException:
365
+ # Branch failed, try next condition
366
+ continue
367
+ except MathJSONException:
368
+ return f(s[-1], c) # return default value (else)
369
+
370
+ return f(s[-1], c)
371
+
372
+
373
+ constructs = {
374
+ "Sum": Sum,
375
+ "Add": Add,
376
+ "Subtract": Subtract,
377
+ "Constants": Constants,
378
+ "Switch": Switch,
379
+ "StrictSwitch": StrictSwitch,
380
+ "If": If,
381
+ "Multiply": lambda f, c, solver_parameters, s: reduce(
382
+ lambda a, b: float(a) * float(b), [f(x, c) for x in s[1:]]
383
+ ),
384
+ "Divide": lambda f, c, solver_parameters, s: f(s[1], c) / f(s[2], c),
385
+ "Negate": lambda f, c, solver_parameters, s: -f(s[1], c),
386
+ "Power": lambda f, c, solver_parameters, s: pow(f(s[1], c), f(s[2], c)),
387
+ "Root": lambda f, c, solver_parameters, s: pow(f(s[1], c), 1.0 / f(s[2], c)),
388
+ "Sqrt": lambda f, c, solver_parameters, s: pow(f(s[1], c), 1.0 / 2),
389
+ "Square": lambda f, c, solver_parameters, s: pow(f(s[1], c), 2),
390
+ "Exp": lambda f, c, solver_parameters, s: math.exp(f(s[1], c)),
391
+ # CortexJS-compatible: ["Log", x] is log base 10; ["Log", x, b] is
392
+ # log base b. Use "Ln" for natural log. (BREAKING as of 2.0.0 -
393
+ # "Log" previously meant natural log.)
394
+ "Log": lambda f, c, solver_parameters, s: (
395
+ math.log10(f(s[1], c)) if len(s) == 2 else math.log(f(s[1], c), f(s[2], c))
396
+ ),
397
+ "Log2": lambda f, c, solver_parameters, s: math.log2(f(s[1], c)),
398
+ "Log10": lambda f, c, solver_parameters, s: math.log10(f(s[1], c)),
399
+ "Ln": lambda f, c, solver_parameters, s: math.log(f(s[1], c)),
400
+ "Lb": lambda f, c, solver_parameters, s: math.log2(
401
+ f(s[1], c)
402
+ ), # CortexJS name for Log2
403
+ "Lg": lambda f, c, solver_parameters, s: math.log10(
404
+ f(s[1], c)
405
+ ), # CortexJS name for Log10
406
+ "LogOnePlus": lambda f, c, solver_parameters, s: math.log1p(f(s[1], c)),
407
+ # "Equal": lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
408
+ "Equal": lambda f, c, solver_parameters, s: comparison_safe_converter(f(s[1], c))
409
+ == comparison_safe_converter(f(s[2], c)),
410
+ "IsTrue": lambda f, c, solver_parameters, s: bool(f(s[1], c)),
411
+ "IsFalse": lambda f, c, solver_parameters, s: not bool(f(s[1], c)),
412
+ "StrictEqual": lambda f, c, solver_parameters, s: f(s[1], c) == f(s[2], c),
413
+ "IdenticallyEqual": IdenticallyEqual,
414
+ "Congruent": Congruent,
415
+ # "Greater": lambda s: f(s[1], c) > f(s[2], c),
416
+ "Greater": Greater,
417
+ # "GreaterEqual": lambda s: f(s[1], c) >= f(s[2], c),
418
+ "GreaterEqual": GreaterEqual,
419
+ # "Less": lambda s: f(s[1], c) < f(s[2], c),
420
+ "Less": Less,
421
+ # "LessEqual": lambda s: f(s[1], c) <= f(s[2], c),
422
+ "LessEqual": LessEqual,
423
+ # "NotEqual": lambda s: f(s[1], c) != f(s[2], c),
424
+ "NotEqual": lambda f, c, solver_parameters, s: comparison_safe_converter(f(s[1], c))
425
+ != comparison_safe_converter(f(s[2], c)),
426
+ "And": BooleanAnd,
427
+ "Or": BooleanOr,
428
+ "Abs": lambda f, c, solver_parameters, s: abs(f(s[1], c)),
429
+ "Round": lambda f, c, solver_parameters, s: (
430
+ round(f(s[1], c), f(s[2], c)) if len(s) == 3 else int(round(f(s[1], c)))
431
+ ),
432
+ "Max": Max,
433
+ "Min": Min,
434
+ "Average": Average,
435
+ "Mean": Average, # CortexJS name for Average
436
+ "Median": Median,
437
+ "Length": Length,
438
+ "Count": Length, # CortexJS name for Length
439
+ "Any": Any,
440
+ "All": All,
441
+ "Array": Arr,
442
+ "List": lambda f, c, solver_parameters, s: ["Array"]
443
+ + [f(x, c) for x in s[1:]], # CortexJS name for Array
444
+ "In": In,
445
+ "Not_in": Not_in,
446
+ "Element": In, # CortexJS name for In - array, string, or Interval membership
447
+ "NotElement": Not_in, # CortexJS name for Not_in
448
+ "Contains_any_of": Contains_any_of,
449
+ "Contains_all_of": Contains_all_of,
450
+ "Contains_none_of": Contains_none_of,
451
+ "NotIn": Not_in,
452
+ "ContainsAnyOf": Contains_any_of,
453
+ "ContainsAllOf": Contains_all_of,
454
+ "ContainsNoneOf": Contains_none_of,
455
+ "Int": Int,
456
+ "Float": Float,
457
+ "Floor": Floor,
458
+ "Ceil": Ceil,
459
+ "Str": Str,
460
+ # --- Strings ---
461
+ "String": String,
462
+ "StringJoin": StringJoin,
463
+ "ToUpperCase": lambda f, c, solver_parameters, s: f(s[1], c).upper(),
464
+ "ToLowerCase": lambda f, c, solver_parameters, s: f(s[1], c).lower(),
465
+ "CaseFold": lambda f, c, solver_parameters, s: f(s[1], c).casefold(),
466
+ "Trim": lambda f, c, solver_parameters, s: f(s[1], c).strip(),
467
+ "TrimStart": lambda f, c, solver_parameters, s: f(s[1], c).lstrip(),
468
+ "TrimEnd": lambda f, c, solver_parameters, s: f(s[1], c).rstrip(),
469
+ "StringSplit": StringSplit,
470
+ "StringReplace": StringReplace,
471
+ "StringCompare": StringCompare,
472
+ "StringRepeat": StringRepeat,
473
+ "PadStart": PadStart,
474
+ "PadEnd": PadEnd,
475
+ "Characters": Characters,
476
+ "GraphemeClusters": Characters, # CortexJS synonym for Characters
477
+ "Utf8": Utf8,
478
+ "Utf16": Utf16,
479
+ "UnicodeScalars": UnicodeScalars,
480
+ "StringFrom": StringFrom,
481
+ "IntegerString": IntegerString,
482
+ "DigitsFrom": DigitsFrom,
483
+ "NumberFrom": NumberFrom,
484
+ "RegExp": RegExp,
485
+ "IsMatch": IsMatch,
486
+ "StringMatch": StringMatch,
487
+ "StringMatchAll": StringMatchAll,
488
+ "Not": Not,
489
+ # "IsDefined": lambda s: s[1] in c,
490
+ "IsDefined": IsDefined,
491
+ "IsUndefined": IsUndefined,
492
+ "Map": Map,
493
+ "StrictMap": StrictMap,
494
+ "Filter": Filter,
495
+ "HasMatchingSublist": HasMatchingSublist,
496
+ "Strptime": Strptime,
497
+ "Strftime": Strftime,
498
+ "Today": Today,
499
+ "Now": Now,
500
+ "TimeDeltaWeeks": TimeDeltaWeeks,
501
+ "TimeDeltaHours": TimeDeltaHours,
502
+ "TimeDeltaMinutes": TimeDeltaMinutes,
503
+ "TimeDeltaDays": TimeDeltaDays,
504
+ "DateDiffSeconds": DateDiffSeconds,
505
+ "DateDiffMinutes": DateDiffMinutes,
506
+ "DateDiffHours": DateDiffHours,
507
+ "DateDiffDays": DateDiffDays,
508
+ "DateDiffYears": DateDiffYears,
509
+ "Function": Function,
510
+ "Variable": Variable,
511
+ "MultiplyByScalar": MultiplyByScalar,
512
+ "MultiplyByArray": MultiplyByArray,
513
+ "AddScalar": AddScalar,
514
+ "SubtractScalar": SubtractScalar,
515
+ "AddArray": AddArray,
516
+ "SubtractArray": SubtractArray,
517
+ "GenerateRange": GenerateRange,
518
+ "AtIndex": AtIndex,
519
+ "Slice": Slice,
520
+ "CumulativeProduct": CumulativeProduct,
521
+ "CumulativeSum": CumulativeSum,
522
+ "Interp": Interp,
523
+ "FindIntervalIndex": FindIntervalIndex,
524
+ "TrapezoidalIntegrate": TrapezoidalIntegrate,
525
+ "Reduce": Reduce,
526
+ "Product": Product,
527
+ "Appended": Appended,
528
+ "Sin": Sin,
529
+ "Cos": Cos,
530
+ "Tan": Tan,
531
+ "Arcsin": Arcsin,
532
+ "Arccos": Arccos,
533
+ "Arctan": Arctan,
534
+ "Arctan2": lambda f, c, solver_parameters, s: math.atan2(f(s[1], c), f(s[2], c)),
535
+ "Pi": Pi,
536
+ "Which": Which, # CortexJS multi-branch conditional (not Switch - see Which's docstring)
537
+ # --- Trigonometric: reciprocal, hyperbolic, area-hyperbolic ---
538
+ "Cot": lambda f, c, solver_parameters, s: 1 / math.tan(f(s[1], c)),
539
+ "Sec": lambda f, c, solver_parameters, s: 1 / math.cos(f(s[1], c)),
540
+ "Csc": lambda f, c, solver_parameters, s: 1 / math.sin(f(s[1], c)),
541
+ "Arccot": lambda f, c, solver_parameters, s: math.atan(1 / f(s[1], c)),
542
+ "Arcsec": lambda f, c, solver_parameters, s: math.acos(1 / f(s[1], c)),
543
+ "Arccsc": lambda f, c, solver_parameters, s: math.asin(1 / f(s[1], c)),
544
+ "Sinh": lambda f, c, solver_parameters, s: math.sinh(f(s[1], c)),
545
+ "Cosh": lambda f, c, solver_parameters, s: math.cosh(f(s[1], c)),
546
+ "Tanh": lambda f, c, solver_parameters, s: math.tanh(f(s[1], c)),
547
+ "Coth": lambda f, c, solver_parameters, s: 1 / math.tanh(f(s[1], c)),
548
+ "Sech": lambda f, c, solver_parameters, s: 1 / math.cosh(f(s[1], c)),
549
+ "Csch": lambda f, c, solver_parameters, s: 1 / math.sinh(f(s[1], c)),
550
+ "Arsinh": lambda f, c, solver_parameters, s: math.asinh(f(s[1], c)),
551
+ "Arcosh": lambda f, c, solver_parameters, s: math.acosh(f(s[1], c)),
552
+ "Artanh": lambda f, c, solver_parameters, s: math.atanh(f(s[1], c)),
553
+ "Arcoth": lambda f, c, solver_parameters, s: math.atanh(1 / f(s[1], c)),
554
+ "Arsech": lambda f, c, solver_parameters, s: math.acosh(1 / f(s[1], c)),
555
+ "Arcsch": lambda f, c, solver_parameters, s: math.asinh(1 / f(s[1], c)),
556
+ "Hypot": lambda f, c, solver_parameters, s: math.hypot(f(s[1], c), f(s[2], c)),
557
+ "Sinc": lambda f, c, solver_parameters, s: (
558
+ 1.0 if f(s[1], c) == 0 else math.sin(f(s[1], c)) / f(s[1], c)
559
+ ),
560
+ # --- Constants ---
561
+ "Degrees": lambda f, c, solver_parameters, s: math.pi / 180,
562
+ "ExponentialE": lambda f, c, solver_parameters, s: math.e,
563
+ "GoldenRatio": lambda f, c, solver_parameters, s: (1 + math.sqrt(5)) / 2,
564
+ "MachineEpsilon": lambda f, c, solver_parameters, s: sys.float_info.epsilon,
565
+ "CatalanConstant": lambda f, c, solver_parameters, s: 0.915965594177219015054603514932384110774,
566
+ "EulerGamma": lambda f, c, solver_parameters, s: 0.5772156649015328606065120900824024310421,
567
+ "Rational": Rational,
568
+ "Numerator": Numerator,
569
+ "Denominator": Denominator,
570
+ # --- Number theory / special functions ---
571
+ "Chop": lambda f, c, solver_parameters, s: (
572
+ 0 if abs(f(s[1], c)) < 1e-10 else f(s[1], c)
573
+ ),
574
+ "Mod": lambda f, c, solver_parameters, s: f(s[1], c) % f(s[2], c),
575
+ "Clamp": Clamp,
576
+ "GCD": lambda f, c, solver_parameters, s: math.gcd(
577
+ int(f(s[1], c)), int(f(s[2], c))
578
+ ),
579
+ "LCM": lambda f, c, solver_parameters, s: math.lcm(
580
+ int(f(s[1], c)), int(f(s[2], c))
581
+ ),
582
+ "Factorial": lambda f, c, solver_parameters, s: math.factorial(int(f(s[1], c))),
583
+ "Binomial": lambda f, c, solver_parameters, s: math.comb(
584
+ int(f(s[1], c)), int(f(s[2], c))
585
+ ),
586
+ "IsPrime": IsPrime,
587
+ "Erf": lambda f, c, solver_parameters, s: math.erf(f(s[1], c)),
588
+ "Erfc": lambda f, c, solver_parameters, s: math.erfc(f(s[1], c)),
589
+ # --- Number theory ---
590
+ "PowerMod": lambda f, c, solver_parameters, s: pow(
591
+ int(f(s[1], c)), int(f(s[2], c)), int(f(s[3], c))
592
+ ),
593
+ "ModularInverse": lambda f, c, solver_parameters, s: pow(
594
+ int(f(s[1], c)), -1, int(f(s[2], c))
595
+ ),
596
+ "IntegerSqrt": lambda f, c, solver_parameters, s: math.isqrt(int(f(s[1], c))),
597
+ "FactorInteger": FactorInteger,
598
+ "PrimeFactors": PrimeFactors,
599
+ "PrimeNu": PrimeNu,
600
+ "PrimeOmega": PrimeOmega,
601
+ "Radical": Radical,
602
+ "IsSquareFree": IsSquareFree,
603
+ "Divisors": Divisors,
604
+ "Sigma0": Sigma0,
605
+ "Sigma1": Sigma1,
606
+ "SigmaMinus1": SigmaMinus1,
607
+ "DivisorSigma": DivisorSigma,
608
+ "Divides": lambda f, c, solver_parameters, s: f(s[2], c) % f(s[1], c) == 0,
609
+ "Totient": Totient,
610
+ "IsPerfectPower": IsPerfectPower,
611
+ "NthPrime": NthPrime,
612
+ "NextPrime": NextPrime,
613
+ "PrimePi": PrimePi,
614
+ "ExtendedGCD": ExtendedGCD,
615
+ "ChineseRemainder": ChineseRemainder,
616
+ "CarmichaelLambda": CarmichaelLambda,
617
+ "JacobiSymbol": JacobiSymbol,
618
+ "LegendreSymbol": JacobiSymbol, # same algorithm when n is prime
619
+ "MultiplicativeOrder": MultiplicativeOrder,
620
+ "PrimitiveRoot": PrimitiveRoot,
621
+ "LucasL": LucasL,
622
+ "CatalanNumber": lambda f, c, solver_parameters, s: math.comb(
623
+ 2 * int(f(s[1], c)), int(f(s[1], c))
624
+ )
625
+ // (int(f(s[1], c)) + 1),
626
+ "BernoulliB": BernoulliB,
627
+ "ContinuedFraction": ContinuedFraction,
628
+ "FromContinuedFraction": FromContinuedFraction,
629
+ "IntegerDigits": IntegerDigits,
630
+ "DigitCount": DigitCount,
631
+ "DigitSum": DigitSum,
632
+ "FromDigits": FromDigits,
633
+ "IsSquare": IsSquare,
634
+ "IsTriangular": IsTriangular,
635
+ "IsPentagonal": IsPentagonal,
636
+ "IsOctahedral": IsOctahedral,
637
+ "IsCenteredSquare": IsCenteredSquare,
638
+ "IsPerfect": IsPerfect,
639
+ "IsAbundant": IsAbundant,
640
+ "IsHappy": IsHappy,
641
+ # --- Special functions ---
642
+ "Gamma": lambda f, c, solver_parameters, s: math.gamma(f(s[1], c)),
643
+ "GammaLn": lambda f, c, solver_parameters, s: math.lgamma(f(s[1], c)),
644
+ "Beta": Beta,
645
+ "Factorial2": Factorial2,
646
+ "ErfInv": ErfInv,
647
+ "LambertW": LambertW,
648
+ "AGM": AGM,
649
+ "EllipticK": EllipticK,
650
+ "EllipticE": EllipticE,
651
+ "Hypergeometric1F1": Hypergeometric1F1,
652
+ "Hypergeometric2F1": Hypergeometric2F1,
653
+ "BesselJ": BesselJ,
654
+ "BesselY": BesselY,
655
+ "BesselI": BesselI,
656
+ "BesselK": BesselK,
657
+ "AiryAi": AiryAi,
658
+ "AiryBi": AiryBi,
659
+ "AiryAiPrime": AiryAiPrime,
660
+ "AiryBiPrime": AiryBiPrime,
661
+ "Zeta": Zeta,
662
+ "GammaRegularized": GammaRegularized,
663
+ "BetaRegularized": BetaRegularized,
664
+ # --- Combinatorics (trivial subset) ---
665
+ "Choose": lambda f, c, solver_parameters, s: math.comb(
666
+ int(f(s[1], c)), int(f(s[2], c))
667
+ ),
668
+ "Fibonacci": Fibonacci,
669
+ "Multinomial": Multinomial,
670
+ "Subfactorial": Subfactorial,
671
+ "BellNumber": BellNumber,
672
+ "PowerSet": PowerSet,
673
+ "Permutations": Permutations,
674
+ "Combinations": Combinations,
675
+ "CartesianProduct": CartesianProduct,
676
+ # --- Core: structural introspection ---
677
+ "Head": Head,
678
+ "Tail": Tail,
679
+ "Hold": Hold,
680
+ "Identity": lambda f, c, solver_parameters, s: f(s[1], c),
681
+ "Type": Type,
682
+ "IsSame": IsSame,
683
+ "Same": IsSame, # see IsSame's docstring for the distinction CortexJS draws
684
+ # --- Boolean logic ---
685
+ "Xor": lambda f, c, solver_parameters, s: bool(f(s[1], c)) ^ bool(f(s[2], c)),
686
+ "Nand": lambda f, c, solver_parameters, s: not all(f(x, c) for x in s[1:]),
687
+ "Nor": lambda f, c, solver_parameters, s: not any(f(x, c) for x in s[1:]),
688
+ "Implies": lambda f, c, solver_parameters, s: (not f(s[1], c)) or bool(f(s[2], c)),
689
+ "Equivalent": lambda f, c, solver_parameters, s: bool(f(s[1], c))
690
+ == bool(f(s[2], c)),
691
+ # --- Statistics ---
692
+ "Variance": Variance,
693
+ "StandardDeviation": StandardDeviation,
694
+ "PopulationVariance": PopulationVariance,
695
+ "PopulationStandardDeviation": PopulationStandardDeviation,
696
+ "Mode": Mode,
697
+ "Quartiles": Quartiles,
698
+ "InterquartileRange": InterquartileRange,
699
+ "Covariance": Covariance,
700
+ "Correlation": Correlation,
701
+ "Skewness": Skewness,
702
+ "Kurtosis": Kurtosis,
703
+ "LinearRegression": LinearRegression,
704
+ "PolynomialFit": PolynomialFit,
705
+ "NormalDistribution": NormalDistribution,
706
+ "BinomialDistribution": BinomialDistribution,
707
+ "PoissonDistribution": PoissonDistribution,
708
+ "UniformDistribution": UniformDistribution,
709
+ "ExponentialDistribution": ExponentialDistribution,
710
+ "PDF": PDF,
711
+ "CDF": CDF,
712
+ "Quantile": Quantile,
713
+ # --- Collections ---
714
+ "First": First,
715
+ "Second": Second,
716
+ "Third": Third,
717
+ "Last": Last,
718
+ "Rest": Rest,
719
+ "Most": Most,
720
+ "Reverse": Reverse,
721
+ "Sort": Sort,
722
+ "IsEmpty": IsEmpty,
723
+ "Range": Range,
724
+ "Join": Join,
725
+ "Unique": Unique,
726
+ "Zip": Zip,
727
+ "At": At,
728
+ "Take": Take,
729
+ "Drop": Drop,
730
+ "TakeWhile": TakeWhile,
731
+ "DropWhile": DropWhile,
732
+ "Contains": Contains,
733
+ "IndexOf": IndexOf,
734
+ "IndexWhere": IndexWhere,
735
+ "Find": Find,
736
+ "CountIf": CountIf,
737
+ "Position": Position,
738
+ "RotateLeft": RotateLeft,
739
+ "RotateRight": RotateRight,
740
+ "MaxBy": MaxBy,
741
+ "MinBy": MinBy,
742
+ "ArgMax": ArgMax,
743
+ "ArgMin": ArgMin,
744
+ "Ordering": Ordering,
745
+ "FlatMap": FlatMap,
746
+ "Scan": Scan,
747
+ "Differences": Differences,
748
+ "Fold": Fold,
749
+ "Dedup": Dedup,
750
+ "Append": Appended, # CortexJS name for Appended
751
+ "Insert": Insert,
752
+ "DeleteAt": DeleteAt,
753
+ "ReplaceAt": ReplaceAt,
754
+ "Partition": Partition,
755
+ "Chunk": Chunk,
756
+ "GroupBy": GroupBy,
757
+ "ChunkBy": ChunkBy,
758
+ "Tally": Tally,
759
+ # --- Set algebra (over Array - no dedicated Set type) ---
760
+ "Union": Union,
761
+ "Intersection": Intersection,
762
+ "SetMinus": SetMinus,
763
+ "SymmetricDifference": SymmetricDifference,
764
+ "Subset": Subset,
765
+ "SubsetEqual": SubsetEqual,
766
+ "Superset": Superset,
767
+ "SupersetEqual": SupersetEqual,
768
+ "NotSubset": NotSubset,
769
+ "NotSuperset": NotSuperset,
770
+ "Interval": Interval,
771
+ "Open": Open,
772
+ }
773
+
774
+
775
+ def create_mathjson_solver(
776
+ solver_parameters: dict[str, MathJSONExpression],
777
+ legacy_v1: bool = False,
778
+ blacklist: Iterable[str] | None = None,
779
+ ) -> Callable[[MathJSONExpression], _Any]:
780
+ """
781
+ `blacklist`, if given, is an iterable of construct names (e.g.
782
+ `["PowerSet", "Permutations"]`) that this solver instance refuses to
783
+ evaluate - deployments can disable individual constructs they don't
784
+ want available for their expression sources, independent of what
785
+ the library implements. Attempting to use a blacklisted construct
786
+ raises `MathJSONException` (wrapping `PermissionError`) rather than
787
+ evaluating it or silently ignoring it. A name that isn't an actual
788
+ construct has no effect (not validated against the known-construct
789
+ list - a deliberate simplicity trade-off, not an oversight).
790
+
791
+ This is a resource/access *policy* control, not a substitute for a
792
+ construct being safe to run at all - e.g. the combinatorial
793
+ enumeration functions (`PowerSet`, `Permutations`, `Combinations`,
794
+ `CartesianProduct`) have no built-in output-size limit, so a
795
+ deployment accepting untrusted expressions should blacklist them
796
+ (or any other construct it doesn't want exposed) rather than assume
797
+ every construct is safe by default for every threat model.
798
+ """
799
+ blacklist = frozenset(blacklist) if blacklist else frozenset()
800
+
801
+ def f(s, *args):
802
+ # Leaf values never touch `c` at all - check them before doing
803
+ # anything with it, since leaves vastly outnumber interior nodes
804
+ # in any real expression tree.
358
805
  if isinstance(s, numbers.Number):
359
806
  return s
360
807
  # CortexJS represents the boolean literals as the bare symbols
@@ -366,2173 +813,31 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
366
813
  # solver parameter or local variable.
367
814
  if s == "True" or s == "False":
368
815
  return s == "True"
816
+ # `c` is passed through by reference, not copied, here or at any
817
+ # of the call sites below - almost every construct only reads
818
+ # it. The few constructs that introduce new bindings (Constants,
819
+ # Reduce's legacy accumulator form, TrapezoidalIntegrate) are
820
+ # responsible for making their own `c = dict(c)` copy before
821
+ # writing into it, the same way `_apply_fn` already does for
822
+ # `Function` - so a written binding is visible to whatever that
823
+ # construct evaluates internally, but never leaks back into the
824
+ # caller's scope once the construct returns.
825
+ c = args[0] if args else {}
369
826
  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
827
  if not s:
2531
828
  # Empty equation given - []
2532
829
  return None
2533
830
  if s[0] in constructs:
831
+ if s[0] in blacklist:
832
+ raise MathJSONException(
833
+ PermissionError(
834
+ f"'{s[0]}' has been disabled in this solver instance."
835
+ ),
836
+ s,
837
+ mathjson_construct=s[0],
838
+ )
2534
839
  try:
2535
- return constructs[s[0]](s)
840
+ return constructs[s[0]](f, c, solver_parameters, s)
2536
841
 
2537
842
  # except RecursionError:
2538
843
  # return s[0]
@@ -2574,7 +879,9 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
2574
879
  return f
2575
880
 
2576
881
 
2577
- def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set):
882
+ def extract_variables(
883
+ s: MathJSONExpression, li: set[str], ignore_list: set[str]
884
+ ) -> set[str]:
2578
885
  constructs = [
2579
886
  "Add",
2580
887
  "Sum",
@@ -2677,6 +984,11 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
2677
984
  "TimeDeltaHours",
2678
985
  "TimeDeltaMinutes",
2679
986
  "TimeDeltaDays",
987
+ "DateDiffSeconds",
988
+ "DateDiffMinutes",
989
+ "DateDiffHours",
990
+ "DateDiffDays",
991
+ "DateDiffYears",
2680
992
  "Function",
2681
993
  "Variable",
2682
994
  "MultiplyByScalar",
@@ -2751,6 +1063,88 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
2751
1063
  "IsPrime",
2752
1064
  "Erf",
2753
1065
  "Erfc",
1066
+ "PowerMod",
1067
+ "ModularInverse",
1068
+ "IntegerSqrt",
1069
+ "FactorInteger",
1070
+ "PrimeFactors",
1071
+ "PrimeNu",
1072
+ "PrimeOmega",
1073
+ "Radical",
1074
+ "IsSquareFree",
1075
+ "Divisors",
1076
+ "Sigma0",
1077
+ "Sigma1",
1078
+ "SigmaMinus1",
1079
+ "DivisorSigma",
1080
+ "Divides",
1081
+ "Totient",
1082
+ "IsPerfectPower",
1083
+ "NthPrime",
1084
+ "NextPrime",
1085
+ "PrimePi",
1086
+ "ExtendedGCD",
1087
+ "ChineseRemainder",
1088
+ "CarmichaelLambda",
1089
+ "JacobiSymbol",
1090
+ "LegendreSymbol",
1091
+ "MultiplicativeOrder",
1092
+ "PrimitiveRoot",
1093
+ "LucasL",
1094
+ "CatalanNumber",
1095
+ "BernoulliB",
1096
+ "ContinuedFraction",
1097
+ "FromContinuedFraction",
1098
+ "IntegerDigits",
1099
+ "DigitCount",
1100
+ "DigitSum",
1101
+ "FromDigits",
1102
+ "IsSquare",
1103
+ "IsTriangular",
1104
+ "IsPentagonal",
1105
+ "IsOctahedral",
1106
+ "IsCenteredSquare",
1107
+ "IsPerfect",
1108
+ "IsAbundant",
1109
+ "IsHappy",
1110
+ "Gamma",
1111
+ "GammaLn",
1112
+ "Beta",
1113
+ "Factorial2",
1114
+ "ErfInv",
1115
+ "LambertW",
1116
+ "AGM",
1117
+ "EllipticK",
1118
+ "EllipticE",
1119
+ "Hypergeometric1F1",
1120
+ "Hypergeometric2F1",
1121
+ "BesselJ",
1122
+ "BesselY",
1123
+ "BesselI",
1124
+ "BesselK",
1125
+ "AiryAi",
1126
+ "AiryBi",
1127
+ "AiryAiPrime",
1128
+ "AiryBiPrime",
1129
+ "Zeta",
1130
+ "GammaRegularized",
1131
+ "BetaRegularized",
1132
+ "Choose",
1133
+ "Fibonacci",
1134
+ "Multinomial",
1135
+ "Subfactorial",
1136
+ "BellNumber",
1137
+ "PowerSet",
1138
+ "Permutations",
1139
+ "Combinations",
1140
+ "CartesianProduct",
1141
+ "Head",
1142
+ "Tail",
1143
+ "Hold",
1144
+ "Identity",
1145
+ "Type",
1146
+ "IsSame",
1147
+ "Same",
2754
1148
  "Xor",
2755
1149
  "Nand",
2756
1150
  "Nor",
@@ -2765,6 +1159,18 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
2765
1159
  "InterquartileRange",
2766
1160
  "Covariance",
2767
1161
  "Correlation",
1162
+ "Skewness",
1163
+ "Kurtosis",
1164
+ "LinearRegression",
1165
+ "PolynomialFit",
1166
+ "NormalDistribution",
1167
+ "BinomialDistribution",
1168
+ "PoissonDistribution",
1169
+ "UniformDistribution",
1170
+ "ExponentialDistribution",
1171
+ "PDF",
1172
+ "CDF",
1173
+ "Quantile",
2768
1174
  "First",
2769
1175
  "Second",
2770
1176
  "Third",
@@ -2814,6 +1220,14 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
2814
1220
  "Intersection",
2815
1221
  "SetMinus",
2816
1222
  "SymmetricDifference",
1223
+ "Subset",
1224
+ "SubsetEqual",
1225
+ "Superset",
1226
+ "SupersetEqual",
1227
+ "NotSubset",
1228
+ "NotSuperset",
1229
+ "Interval",
1230
+ "Open",
2817
1231
  ]
2818
1232
  if isinstance(s, str):
2819
1233
  if s in ignore_list:
@@ -2836,11 +1250,7 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
2836
1250
  # ["If", [cond, val], ..., else_val].
2837
1251
  is_cortexjs_form = len(s) > 1 and (
2838
1252
  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
- )
1253
+ or (bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs)
2844
1254
  )
2845
1255
  if is_cortexjs_form:
2846
1256
  for x in s[1:]:
@@ -2861,6 +1271,27 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
2861
1271
  ignore_list.add("_")
2862
1272
  if len(s) > 1:
2863
1273
  li.update(extract_variables(s[1], li, ignore_list))
1274
+ elif s[0] in ("Head", "Tail", "Hold", "IsSame", "Same"):
1275
+ # These deliberately never evaluate their arguments either
1276
+ # (Head/Tail/Hold work on the raw, unevaluated expression
1277
+ # tree; IsSame/Same do a pure structural comparison of the
1278
+ # two raw trees) - same reasoning as the unrecognized-
1279
+ # construct case below, just for constructs that *are*
1280
+ # recognized. A bare name inside their arguments is never
1281
+ # resolved as a parameter reference, so it's not a free
1282
+ # variable to supply.
1283
+ pass
1284
+ elif s[0] not in constructs:
1285
+ # Unrecognized construct (e.g. "Color", "Quantity" - anything
1286
+ # this solver doesn't implement): f() never evaluates or
1287
+ # substitutes into such expressions either (its fallback for
1288
+ # an unknown head is to return the whole list unchanged), so
1289
+ # none of its arguments are free variables to supply. Treat
1290
+ # the whole thing as opaque data rather than recursing into
1291
+ # it, so a decorative/unrelated subtree (e.g. a color literal
1292
+ # meant for something else downstream) doesn't get reported
1293
+ # as a required parameter.
1294
+ pass
2864
1295
  else:
2865
1296
  for x in s[1:]:
2866
1297
  li.update(extract_variables(x, li, ignore_list))