mathjson-solver 2.2.0__py3-none-any.whl → 2.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,165 +1,12 @@
1
1
  import numbers
2
- from typing import Union, Any
2
+ import sys
3
+ from typing import Any as _Any
4
+ from collections.abc import Callable, Iterable
3
5
  from functools import reduce
4
6
  import math
5
- from copy import deepcopy
6
- from statistics import median, variance, stdev
7
- import datetime
8
-
9
- NUMPY_AVAILABLE = False
10
- try:
11
- import numpy as np
12
-
13
- NUMPY_AVAILABLE = True
14
- except ImportError:
15
- pass
16
-
17
- NoneType = type(None)
18
-
19
-
20
- def _try_parse_datetime(value):
21
- """Try to parse a string as datetime or date. Returns original value if not parseable."""
22
- if isinstance(value, (datetime.datetime, datetime.date)):
23
- return value
24
- if isinstance(value, str):
25
- try:
26
- return datetime.datetime.fromisoformat(value)
27
- except ValueError:
28
- pass
29
- try:
30
- return datetime.date.fromisoformat(value)
31
- except ValueError:
32
- pass
33
- return value
34
-
35
-
36
- # def find_interpolation_bounds(
37
- # l: list, target: int | float
38
- # ) -> Union[Union[int, float], tuple[Union[int, float], Union[int, float]]]:
39
- # for i, x in enumerate(l):
40
- # if i == 0:
41
- # continue
42
- # if l[i - 1] <= target and target <= l[i]:
43
- # if target == l[i - 1] or target == l[i]:
44
- # return target
45
- # else:
46
- # return l[i - 1], l[i]
47
- # else:
48
- # raise ValueError("Target value is outside interpolation range.")
49
-
50
-
51
- def _MultiplyByScalar(l: list[numbers.Real], a: numbers.Real) -> list[numbers.Real]:
52
- return [x * a for x in l]
53
-
54
-
55
- def _MultiplyByArray(
56
- l1: list[numbers.Real], l2: list[numbers.Real]
57
- ) -> list[numbers.Real]:
58
- return [a * b for a, b in zip(l1, l2)]
59
-
60
-
61
- def _AddScalar(l: list[numbers.Real], a: numbers.Real) -> list[numbers.Real]:
62
- return [x + a for x in l]
63
-
64
-
65
- def _SubtractScalar(l: list[numbers.Real], a: numbers.Real) -> list[numbers.Real]:
66
- return [x - a for x in l]
67
-
68
-
69
- def _AddArray(l1: list[numbers.Real], l2: list[numbers.Real]) -> list[numbers.Real]:
70
- return [a + b for a, b in zip(l1, l2)]
71
-
72
-
73
- def _SubtractArray(
74
- l1: list[numbers.Real], l2: list[numbers.Real]
75
- ) -> list[numbers.Real]:
76
- return [a - b for a, b in zip(l1, l2)]
77
-
78
-
79
- def _CumulativeProduct(l: list) -> list:
80
- res = []
81
- for i, x in enumerate(l):
82
- if i == 0:
83
- res.append(x)
84
- else:
85
- res.append(reduce(lambda a, b: a * b, l[: i + 1]))
86
- return res
87
-
88
-
89
- def _CumulativeSum(l: list) -> list:
90
- res = []
91
- for i, x in enumerate(l):
92
- if i == 0:
93
- res.append(x)
94
- else:
95
- res.append(reduce(lambda a, b: a + b, l[: i + 1]))
96
- return res
97
-
98
-
99
- def find_interpolation_bounds_indexes(
100
- l: list, target: int | float
101
- ) -> Union[Union[int, float], tuple[Union[int, float], Union[int, float]]]:
102
- for i, x in enumerate(l):
103
- if i == 0:
104
- continue
105
- if l[i - 1] <= target and target <= l[i]:
106
- if target == l[i - 1]:
107
- return i - 1
108
- elif target == l[i]:
109
- return i
110
- else:
111
- return i - 1, i
112
- else:
113
- raise ValueError("Target value is outside interpolation range.")
114
-
115
-
116
- def find_interpolation_bounds_2indexes(
117
- l: list, target: int | float
118
- ) -> Union[Union[int, float], tuple[Union[int, float], Union[int, float]]]:
119
- for i, x in enumerate(l):
120
- if i == len(l) - 1:
121
- return i - 1, i
122
- if l[i] <= target and target < l[i + 1]:
123
- return i, i + 1
124
- else:
125
- raise ValueError("Target value is outside interpolation range.")
126
-
127
-
128
- def linear_interpolate(x_array, y_array, target_x):
129
- # Find the interval where target_x falls
130
- # Handle edge cases (target_x outside range)
131
- # Apply: y = y1 + (y2 - y1) * (target_x - x1) / (x2 - x1)
132
-
133
- # first check if both arrays are the same length
134
- if len(x_array) != len(y_array) or len(x_array) < 2:
135
- raise ValueError(
136
- "Both arrays need to be the same length and with at least 2 elements."
137
- )
138
- bounds_indexes = find_interpolation_bounds_indexes(x_array, target_x)
139
- if isinstance(bounds_indexes, tuple):
140
- x1, x2 = x_array[bounds_indexes[0]], x_array[bounds_indexes[1]]
141
- y1, y2 = y_array[bounds_indexes[0]], y_array[bounds_indexes[1]]
142
- return y1 + (y2 - y1) * (target_x - x1) / (x2 - x1)
143
- else:
144
- return y_array[bounds_indexes]
145
-
146
-
147
- class MathJSONException(Exception):
148
- """Exception for MathJSON processing issues"""
149
-
150
- def __init__(self, e, expr, *args, **kwargs):
151
- super().__init__(args)
152
- self.e = e
153
- self.expr = expr
154
- self.construct = kwargs.get("mathjson_construct", "MathJSON")
155
-
156
- def __str__(self):
157
- if hasattr(self.e, "message"):
158
- m = self.e.message
159
- else:
160
- m = str(self.e)
161
- return f"Problem in {self.construct}. {self.expr}. {m}"
162
7
 
8
+ from ._common import comparison_safe_converter
9
+ from ._exceptions import MathJSONExpression, MathJSONException
163
10
 
164
11
  # def requires_array(func):
165
12
  # def inner1(*args, **kwargs):
@@ -174,127 +21,7 @@ class MathJSONException(Exception):
174
21
  # return inner1
175
22
 
176
23
 
177
- def is_numeric(x):
178
- try:
179
- float(x)
180
- except ValueError:
181
- return False
182
- except TypeError:
183
- return False
184
- else:
185
- return True
186
-
187
-
188
- def _is_prime(n) -> bool:
189
- n = int(n)
190
- if n < 2:
191
- return False
192
- if n == 2:
193
- return True
194
- if n % 2 == 0:
195
- return False
196
- return all(n % i for i in range(3, int(n**0.5) + 1, 2))
197
-
198
-
199
- def has_matching_sublist(
200
- *,
201
- my_list: list,
202
- required_match_count: int,
203
- position: int,
204
- contiguous: bool,
205
- conditions: list[bool],
206
- ) -> bool:
207
- if contiguous:
208
- # Check for contiguous matches based on position
209
- if position == 0:
210
- # Check if the beginning of the list matches
211
- count = sum(
212
- 1
213
- for i in range(min(required_match_count, len(my_list)))
214
- if conditions[i]
215
- )
216
- return count == required_match_count
217
- elif position > 0:
218
- # Skip the first `position` elements
219
- count = sum(
220
- 1
221
- for i in range(position, position + required_match_count)
222
- if i < len(my_list) and conditions[i]
223
- )
224
- return count == required_match_count
225
- elif position == -1:
226
- # Check if the end of the list matches
227
- count = sum(
228
- 1
229
- for i in range(len(my_list) - required_match_count, len(my_list))
230
- if conditions[i]
231
- )
232
- return count == required_match_count
233
- elif position < -1:
234
- # Skip the last `abs(position)` elements
235
- count = sum(1 for i in range(len(my_list) + position) if conditions[i])
236
- return count == required_match_count
237
- else:
238
- # Check for non-contiguous matches
239
- count = sum(1 for i in range(len(my_list)) if conditions[i])
240
- return count >= required_match_count
241
-
242
-
243
- # def has_sublist2(
244
- # *,
245
- # my_list: list,
246
- # required_match_count: int,
247
- # position: int,
248
- # contiguous: bool,
249
- # condition: callable,
250
- # ) -> bool:
251
- # if contiguous:
252
- # # Check for contiguous matches based on position
253
- # if position == 0:
254
- # # Check if the beginning of the list matches
255
- # count = sum(1 for x in my_list[:required_match_count] if condition(x))
256
- # return count == required_match_count
257
- # elif position > 0:
258
- # # Skip the first `position` elements
259
- # count = sum(
260
- # 1
261
- # for x in my_list[position : position + required_match_count]
262
- # if condition(x)
263
- # )
264
- # return count == required_match_count
265
- # elif position == -1:
266
- # # Check if the end of the list matches
267
- # count = sum(1 for x in my_list[-required_match_count:] if condition(x))
268
- # return count == required_match_count
269
- # elif position < -1:
270
- # # Skip the last `abs(position)` elements
271
- # count = sum(1 for x in my_list[:position] if condition(x))
272
- # return count == required_match_count
273
- # else:
274
- # # Check for non-contiguous matches
275
- # count = sum(1 for x in my_list if condition(x))
276
- # return count >= required_match_count
277
-
278
-
279
- def comparison_safe_converter(x):
280
- if type(x) in [bool, NoneType]: # bool before int (bool IS an int in Python)
281
- return "1" if x else "0"
282
- elif type(x) in [int, float, str]:
283
- return f"{x}"
284
- return x
285
-
286
-
287
- def comparison_safe_converter_for_pairs(
288
- v1, v2
289
- ) -> (Union[str, float], Union[str, float]):
290
- if is_numeric(v1):
291
- v1 = float(v1)
292
- if is_numeric(v2):
293
- v2 = float(v2)
294
- return v1, v2
295
-
296
-
297
- def translate_v1_mathjson(expr):
24
+ def translate_v1_mathjson(expr: MathJSONExpression) -> MathJSONExpression:
298
25
  """
299
26
  Rewrite a MathJSON expression written for mathjson-solver < 2.0.0 so it
300
27
  evaluates to the same result on >= 2.0.0.
@@ -316,1191 +43,791 @@ def translate_v1_mathjson(expr):
316
43
  return expr
317
44
 
318
45
 
319
- def create_mathjson_solver(solver_parameters, legacy_v1=False):
320
- def f(s, *args):
321
- if args:
322
- 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
+ )
196
+ from ._functional_constructs import (
197
+ Fold,
198
+ Map,
199
+ StrictMap,
200
+ Filter,
201
+ Reduce,
202
+ )
203
+ from ._number_theory_constructs import (
204
+ IsPrime,
205
+ FactorInteger,
206
+ PrimeFactors,
207
+ PrimeNu,
208
+ PrimeOmega,
209
+ Radical,
210
+ IsSquareFree,
211
+ Divisors,
212
+ Sigma0,
213
+ Sigma1,
214
+ SigmaMinus1,
215
+ DivisorSigma,
216
+ Totient,
217
+ IsPerfectPower,
218
+ NthPrime,
219
+ NextPrime,
220
+ PrimePi,
221
+ ExtendedGCD,
222
+ ChineseRemainder,
223
+ CarmichaelLambda,
224
+ JacobiSymbol,
225
+ MultiplicativeOrder,
226
+ PrimitiveRoot,
227
+ LucasL,
228
+ BernoulliB,
229
+ ContinuedFraction,
230
+ FromContinuedFraction,
231
+ IntegerDigits,
232
+ DigitCount,
233
+ DigitSum,
234
+ FromDigits,
235
+ IsSquare,
236
+ IsTriangular,
237
+ IsPentagonal,
238
+ IsOctahedral,
239
+ IsCenteredSquare,
240
+ IsPerfect,
241
+ IsAbundant,
242
+ IsHappy,
243
+ )
244
+ from ._special_function_constructs import (
245
+ Beta,
246
+ Factorial2,
247
+ ErfInv,
248
+ LambertW,
249
+ AGM,
250
+ EllipticK,
251
+ EllipticE,
252
+ Hypergeometric1F1,
253
+ Hypergeometric2F1,
254
+ BesselJ,
255
+ BesselY,
256
+ BesselI,
257
+ BesselK,
258
+ AiryAi,
259
+ AiryBi,
260
+ AiryAiPrime,
261
+ AiryBiPrime,
262
+ Zeta,
263
+ GammaRegularized,
264
+ BetaRegularized,
265
+ )
266
+ from ._statistics_constructs import (
267
+ Variance,
268
+ StandardDeviation,
269
+ PopulationVariance,
270
+ PopulationStandardDeviation,
271
+ Mode,
272
+ Quartiles,
273
+ InterquartileRange,
274
+ Covariance,
275
+ Correlation,
276
+ Skewness,
277
+ Kurtosis,
278
+ LinearRegression,
279
+ PolynomialFit,
280
+ NormalDistribution,
281
+ BinomialDistribution,
282
+ PoissonDistribution,
283
+ UniformDistribution,
284
+ ExponentialDistribution,
285
+ PDF,
286
+ CDF,
287
+ Quantile,
288
+ )
289
+ from ._string_constructs import (
290
+ Str,
291
+ String,
292
+ StringJoin,
293
+ Utf8,
294
+ Utf16,
295
+ UnicodeScalars,
296
+ StringFrom,
297
+ Characters,
298
+ StringSplit,
299
+ StringReplace,
300
+ StringCompare,
301
+ IntegerString,
302
+ DigitsFrom,
303
+ NumberFrom,
304
+ StringRepeat,
305
+ PadStart,
306
+ PadEnd,
307
+ RegExp,
308
+ IsMatch,
309
+ StringMatch,
310
+ StringMatchAll,
311
+ )
312
+ from ._trig_constructs import (
313
+ Sin,
314
+ Arcsin,
315
+ Cos,
316
+ Arccos,
317
+ Tan,
318
+ Arctan,
319
+ Pi,
320
+ )
321
+
322
+
323
+ def If(f, c, solver_parameters, s):
324
+ if len(s) < 3:
325
+ raise ValueError("Wrong parameters for 'If'")
326
+
327
+ # Detect the CortexJS flat form: ["If", cond, then] or
328
+ # ["If", cond, then, else]. In the Python pair-form below,
329
+ # s[1] is always a [condition, value] pair whose first
330
+ # element (the condition) is itself a MathJSON construct
331
+ # call, e.g. ["Equal", 1, 0]. A CortexJS flat condition is
332
+ # either not a list at all, or is itself such a construct
333
+ # call (its own first element is a *known construct name*).
334
+ # Requiring a known name - rather than any string - keeps a
335
+ # Python-form condition that is a bare parameter reference,
336
+ # e.g. ["If", ["my_flag", "yes"], "no"], from being
337
+ # misdetected as CortexJS form.
338
+ is_cortexjs_form = not isinstance(s[1], list) or (
339
+ bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs
340
+ )
341
+
342
+ if is_cortexjs_form:
343
+ if len(s) not in (3, 4):
344
+ raise ValueError("Wrong parameters for 'If'")
345
+ if f(s[1], c):
346
+ return f(s[2], c)
347
+ elif len(s) == 4:
348
+ return f(s[3], c)
323
349
  else:
324
- c = {}
325
- # c = deepcopy(kwargs.get("c", {}))
326
- if isinstance(s, numbers.Number):
327
- return s
328
- if isinstance(s, list):
329
-
330
- def Arr(s):
331
- return s
332
-
333
- def Add(s):
334
- l_res = []
335
- tmp = 0
336
- for i, x in enumerate(s[1:]):
337
- res = f(x, c)
338
- if is_numeric(res):
339
- res = float(res)
340
- if i == 0:
341
- tmp = res
342
- else:
343
- # Handle datetime string + timedelta
344
- if isinstance(res, datetime.timedelta):
345
- tmp = _try_parse_datetime(tmp)
346
- elif isinstance(tmp, datetime.timedelta):
347
- res = _try_parse_datetime(res)
348
- try:
349
- tmp = tmp + res
350
- except TypeError:
351
- pass
352
-
353
- # Convert datetime result back to string
354
- if isinstance(tmp, (datetime.datetime, datetime.date)):
355
- return tmp.isoformat()
356
- return tmp
357
-
358
- # tmp = 0
359
- # for i, x in enumerate(l):
360
- # if i == 0:
361
- # tmp = x
362
- # else:
363
- # tmp = tmp + x
364
- # return tmp
365
-
366
- # def Sum(s):
367
- # l_res = []
368
- # for x in s[1:]:
369
- # res = f(x, c)
370
- # if isinstance(res, list):
371
- # l_res.append(sum([xx for xx in res[1:]]))
372
- # else:
373
- # l_res.append(res)
374
- # return sum(l_res)
375
-
376
- def Sum(s):
377
- l_res = ["Array"]
378
- for x in s[1:]:
379
- res = f(x, c)
380
- if isinstance(res, list):
381
- l_res.append(Add(["Array"] + [xx for xx in res[1:]]))
382
- else:
383
- l_res.append(res)
384
- return Add(l_res)
385
-
386
- def Subtract(s):
387
- values = [f(x, c) for x in s[1:]]
388
- # Convert datetime strings if we're dealing with timedelta
389
- converted = []
390
- for i, v in enumerate(values):
391
- if isinstance(v, datetime.timedelta):
392
- converted.append(v)
393
- elif any(isinstance(other, datetime.timedelta) for other in values):
394
- converted.append(_try_parse_datetime(v))
395
- else:
396
- converted.append(v)
397
- result = reduce(lambda a, b: a - b, converted)
398
- if isinstance(result, (datetime.datetime, datetime.date)):
399
- return result.isoformat()
400
- return result
401
-
402
- def Max(s):
403
- args = s[1:]
404
- if len(args) == 1:
405
- if isinstance(args[0], str):
406
- return max(
407
- [f(x, c) for x in f(args[0], c) if is_numeric(f(x, c))]
408
- )
409
- else:
410
- return max(
411
- [f(x, c) for x in args[0][1:] if is_numeric(f(x, c))]
412
- )
413
- else:
414
- # CortexJS-style variadic form: ["Max", a, b, c, ...]
415
- return max([f(x, c) for x in args])
416
-
417
- def Min(s):
418
- args = s[1:]
419
- if len(args) == 1:
420
- if isinstance(args[0], str):
421
- return min(
422
- [f(x, c) for x in f(args[0], c) if is_numeric(f(x, c))]
423
- )
424
- else:
425
- return min(
426
- [f(x, c) for x in args[0][1:] if is_numeric(f(x, c))]
427
- )
428
- else:
429
- # CortexJS-style variadic form: ["Min", a, b, c, ...]
430
- return min([f(x, c) for x in args])
431
-
432
- def Average(s):
433
- if isinstance(s[1], str):
434
- # A reference to "answer" has been passed
435
- s_ = [float(f(x, c)) for x in f(s[1], c) if is_numeric(f(x, c))]
436
- else:
437
- s_ = [float(f(x, c)) for x in s[1][1:] if is_numeric(f(x, c))]
438
- try:
439
- return sum(s_) / len(s_)
440
- except ZeroDivisionError:
441
- return None
442
-
443
- def Median(s):
444
- if isinstance(s[1], str):
445
- return median([f(x, c) for x in f(s[1], c) if is_numeric(f(x, c))])
446
- else:
447
- return median([f(x, c) for x in s[1][1:] if is_numeric(f(x, c))])
448
-
449
- def Length(s):
450
- if isinstance(s[1], str):
451
- return len([x for x in f(s[1], c)][1:])
452
- else:
453
- return len([x for x in s[1][1:]])
454
-
455
- def Clamp(s):
456
- """
457
- ["Clamp", value] or ["Clamp", value, lower, upper]
458
- Bounds `value` between `lower` (default -1) and `upper` (default 1),
459
- matching CortexJS `Clamp`.
460
- """
461
- value = f(s[1], c)
462
- lower = f(s[2], c) if len(s) > 2 else -1
463
- upper = f(s[3], c) if len(s) > 3 else 1
464
- return max(lower, min(upper, value))
465
-
466
- def _arr_vals(s):
467
- lst = f(s[1], c)
468
- if not (isinstance(lst, list) and lst[0] == "Array"):
469
- raise ValueError("Parameter 1 must be an array.")
470
- return [f(x, c) for x in lst[1:]]
471
-
472
- def First(s):
473
- return _arr_vals(s)[0]
474
-
475
- def Last(s):
476
- return _arr_vals(s)[-1]
477
-
478
- def Rest(s):
479
- return ["Array"] + _arr_vals(s)[1:]
480
-
481
- def Most(s):
482
- return ["Array"] + _arr_vals(s)[:-1]
483
-
484
- def Reverse(s):
485
- return ["Array"] + list(reversed(_arr_vals(s)))
486
-
487
- def Sort(s):
488
- return ["Array"] + sorted(_arr_vals(s))
489
-
490
- def IsEmpty(s):
491
- lst = f(s[1], c)
492
- if not (isinstance(lst, list) and lst[0] == "Array"):
493
- raise ValueError("Parameter 1 must be an array.")
494
- return len(lst) <= 1
495
-
496
- def Range(s):
497
- """
498
- CortexJS-compatible `Range`:
499
- ["Range", upper] -> 1..upper (inclusive)
500
- ["Range", lower, upper] -> lower..upper (inclusive)
501
- ["Range", lower, upper, step] -> lower..upper (inclusive), stepped
502
- Distinct from `GenerateRange`, which is 0-indexed and exclusive at
503
- the upper end.
504
- """
505
- if len(s) == 2:
506
- return ["Array"] + list(range(1, int(f(s[1], c)) + 1))
507
- elif len(s) == 3:
508
- lo, hi = int(f(s[1], c)), int(f(s[2], c))
509
- return ["Array"] + list(range(lo, hi + 1))
510
- else:
511
- lo, hi, step = (
512
- int(f(s[1], c)),
513
- int(f(s[2], c)),
514
- int(f(s[3], c)),
515
- )
516
- return ["Array"] + list(
517
- range(lo, hi + 1 if step > 0 else hi - 1, step)
518
- )
519
-
520
- def Join(s):
521
- """
522
- ["Join", array1, array2, ...]
523
- Concatenates the given arrays.
524
- """
525
- result = ["Array"]
526
- for arg in s[1:]:
527
- lst = f(arg, c)
528
- if not (isinstance(lst, list) and lst[0] == "Array"):
529
- raise ValueError("All parameters must be arrays.")
530
- result += [f(x, c) for x in lst[1:]]
531
- return result
532
-
533
- def Unique(s):
534
- seen = []
535
- for x in _arr_vals(s):
536
- if x not in seen:
537
- seen.append(x)
538
- return ["Array"] + seen
539
-
540
- def Zip(s):
541
- lists = [[f(x, c) for x in f(arg, c)[1:]] for arg in s[1:]]
542
- return ["Array"] + [["Array", a, b] for a, b in zip(*lists)]
543
-
544
- def At(s):
545
- """
546
- ["At", array, index]
547
- 1-indexed element access (CortexJS `At`), with negative indexes
548
- counting from the end.
549
- """
550
- vals = _arr_vals(s)
551
- idx = int(f(s[2], c))
552
- if idx > 0:
553
- return vals[idx - 1]
554
- else:
555
- return vals[idx]
556
-
557
- def IsPrime(s):
558
- return _is_prime(f(s[1], c))
559
-
560
- def Variance(s):
561
- return variance(_arr_vals(s))
562
-
563
- def StandardDeviation(s):
564
- return stdev(_arr_vals(s))
565
-
566
- def Any(s):
567
- evaluated = f(s[1], c)
568
- if isinstance(evaluated, list) and evaluated[0] == "Array":
569
- return any([f(x, c) for x in evaluated[1:]])
570
- raise ValueError("Parameter 1 must be an array.")
571
-
572
- def All(s):
573
- evaluated = f(s[1], c)
574
- if isinstance(evaluated, list) and evaluated[0] == "Array":
575
- return all([f(x, c) for x in evaluated[1:]])
576
- raise ValueError("Parameter 1 must be an array.")
577
-
578
- def Int(s):
579
- try:
580
- return int(f(s[1], c))
581
- except ValueError:
582
- return int(float(f(s[1], c)))
583
-
584
- def Float(s):
585
- return float(f(s[1], c))
586
-
587
- def Floor(s):
588
- return math.floor(f(s[1], c))
589
-
590
- def Ceil(s):
591
- return math.ceil(f(s[1], c))
592
-
593
- def Constants(s):
594
- for x in s[1:-1]:
595
- try:
596
- c[x[0]] = f(x[1], c)
597
- except Exception:
598
- c[x[0]] = None
599
- return f(s[-1], c)
350
+ return None # CortexJS: Nothing, no else and condition false
600
351
 
601
- def Switch(s):
602
- expression = f(s[1], c)
603
- for x in s[3:]:
604
- if len(x) != 2:
605
- raise ValueError(
606
- "Case of 'Switch' should have exactly two parameters"
607
- )
608
- if comparison_safe_converter(
609
- expression
610
- ) == comparison_safe_converter(f(x[0], c)):
611
- return f(x[1], c)
612
- else:
613
- return f(s[2], c)
614
-
615
- def StrictSwitch(s):
616
- expression = f(s[1], c)
617
- for x in s[3:]:
618
- if len(x) != 2:
619
- raise ValueError(
620
- "Case of 'StrictSwitch' should have exactly two parameters"
621
- )
622
- if expression == f(x[0], c):
623
- return f(x[1], c)
624
- else:
625
- return f(s[2], c)
626
-
627
- def If(s):
628
- if len(s) < 3:
629
- raise ValueError("Wrong parameters for 'If'")
630
-
631
- # Detect the CortexJS flat form: ["If", cond, then] or
632
- # ["If", cond, then, else]. In the Python pair-form below,
633
- # s[1] is always a [condition, value] pair whose first
634
- # element (the condition) is itself a MathJSON construct
635
- # call, e.g. ["Equal", 1, 0]. A CortexJS flat condition is
636
- # either not a list at all, or is itself such a construct
637
- # call (its own first element is a *known construct name*).
638
- # Requiring a known name - rather than any string - keeps a
639
- # Python-form condition that is a bare parameter reference,
640
- # e.g. ["If", ["my_flag", "yes"], "no"], from being
641
- # misdetected as CortexJS form.
642
- is_cortexjs_form = not isinstance(s[1], list) or (
643
- bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs
644
- )
645
-
646
- if is_cortexjs_form:
647
- if len(s) not in (3, 4):
648
- raise ValueError("Wrong parameters for 'If'")
649
- if f(s[1], c):
650
- return f(s[2], c)
651
- elif len(s) == 4:
652
- return f(s[3], c)
653
- else:
654
- return None # CortexJS: Nothing, no else and condition false
655
-
656
- for x in s[1:-1]:
657
- if len(x) != 2:
658
- raise ValueError("Wrong if or elif in 'If'")
659
- try:
660
- if f(x[0], c):
661
- try:
662
- return f(x[1], c)
663
- except MathJSONException:
664
- # Branch failed, try next condition
665
- continue
666
- except MathJSONException:
667
- return f(s[-1], c) # return default value (else)
668
-
669
- return f(s[-1], c)
670
-
671
- def In(s):
672
- if len(s) != 3:
673
- raise ValueError("Wrong parameters for 'In'")
674
- if isinstance(s[2], list) and s[2][0] == "Array":
675
- return f(s[1], c) in [f(x, c) for x in s[2][1:]]
676
-
677
- elif isinstance(s[2], str):
678
- return f(s[1], c) in f(s[2], c)
679
- else:
680
- raise ValueError(
681
- "Wrong parameters for 'In'. Parameter 2 must be a list."
682
- )
683
-
684
- def Not_in(s):
685
- return not In(s)
686
-
687
- def Contains_any_of(s):
688
- if isinstance(s[1], list) and s[1][0] == "Array":
689
- list1 = [f(x, c) for x in s[1][1:]]
690
- elif isinstance(s[1], str):
691
- list1 = f(s[1], c)
692
-
693
- if isinstance(s[2], list) and s[2][0] == "Array":
694
- list2 = [f(x, c) for x in s[2][1:]]
695
- elif isinstance(s[2], str):
696
- list2 = f(s[2], c)
697
-
698
- if any(x in list1 for x in list2):
699
- return True
700
- return False
701
-
702
- def Contains_all_of(s):
703
- if isinstance(s[1], list) and s[1][0] == "Array":
704
- list1 = [f(x, c) for x in s[1][1:]]
705
- elif isinstance(s[1], str):
706
- list1 = f(s[1], c)
707
-
708
- if isinstance(s[2], list) and s[2][0] == "Array":
709
- list2 = [f(x, c) for x in s[2][1:]]
710
- elif isinstance(s[2], str):
711
- list2 = f(s[2], c)
712
-
713
- if all(x in list1 for x in list2):
714
- return True
715
- return False
716
-
717
- def Contains_none_of(s):
718
- return not Contains_any_of(s)
719
-
720
- def Str(s):
721
- if len(s) < 2:
722
- raise ValueError("Wrong parameters for 'Str'")
723
- return f"{f(s[1])}"
724
-
725
- def Not(s):
726
- return not f(s[1])
727
-
728
- def _apply_fn(fn_expr, args):
729
- """
730
- Apply a "function" argument (as used by Map, Filter, and the
731
- CortexJS form of Reduce) to positional `args`. Supports two
732
- conventions:
733
-
734
- - CortexJS `["Function", body, param1, param2, ...]`. If no
735
- parameter names are given, `args` are bound to the
736
- anonymous placeholders "_" (only when there is a single
737
- argument) and "_1", "_2", ... (always), for use inside
738
- `body`.
739
- - The existing "call template" convention:
740
- `[function_name, ...]`, applied as
741
- `f([function_name] + args, c)`.
742
- """
743
- if isinstance(fn_expr, list) and fn_expr and fn_expr[0] == "Function":
744
- body = fn_expr[1]
745
- params = fn_expr[2:]
746
- local_c = dict(c)
747
- if params:
748
- for name, value in zip(params, args):
749
- local_c[name] = value
750
- else:
751
- if len(args) == 1:
752
- local_c["_"] = args[0]
753
- for i, value in enumerate(args, start=1):
754
- local_c[f"_{i}"] = value
755
- return f(body, local_c)
756
- elif isinstance(fn_expr, list) and fn_expr:
757
- function_name = fn_expr[0]
758
- return f([function_name] + list(args), c)
759
- else:
760
- raise ValueError(
761
- "Wrong function parameter: expected a call template "
762
- "(e.g. ['Square']) or a ['Function', body, ...] expression."
763
- )
764
-
765
- def Map(s):
766
- """
767
- ["Map", list, function, more parameters]
768
- The `function` must accept at least one parameter. That is for the current loop element.
769
- The `more parameters` are for any additional parameters that function might have.
770
- `function` can also be a CortexJS ["Function", body, ...params] expression.
771
- """
772
- z = f(s[1], c)
773
- if isinstance(z, list):
774
- retlist = ["Array"]
775
- for x in z[1:]:
776
- try:
777
- retlist.append(_apply_fn(s[2], [x] + s[3:]))
778
- except MathJSONException:
779
- retlist.append(x)
780
- return retlist
781
-
782
- def StrictMap(s):
783
- """
784
- ["Map", list, function, more parameters]
785
- The `function` must accept at least one parameter. That is for the current loop element.
786
- The `more parameters` are for any additional parameters that function might have.
787
- `function` can also be a CortexJS ["Function", body, ...params] expression.
788
- """
789
- z = f(s[1], c)
790
- if isinstance(z, list):
791
- retlist = ["Array"]
792
- for x in z[1:]:
793
- retlist.append(_apply_fn(s[2], [x] + s[3:]))
794
- return retlist
795
-
796
- def Filter(s):
797
- """
798
- ["Filter", list, function, more parameters]
799
- The `function` must accept at least one parameter. That is for the current loop element.
800
- The `more parameters` are for any additional parameters that function might have.
801
- `function` can also be a CortexJS ["Function", body, ...params] expression.
802
- """
803
- z = f(s[1], c)
804
- if isinstance(z, list):
805
- retlist = ["Array"]
806
- for x in z[1:]:
807
- if _apply_fn(s[2], [x] + s[3:]):
808
- retlist.append(x)
809
- return retlist
810
-
811
- def HasMatchingSublist(s):
812
- """
813
- ["HasMatchingSublist", list, required_match_count, position, contiguous, function, more parameters]
814
- """
815
- the_list = f(s[1], c)[1:]
816
- required_match_count = f(s[2], c)
817
- position = f(s[3], c)
818
- contiguous = f(s[4], c)
819
- conditions = []
820
-
821
- for i, x in enumerate(the_list):
822
- the_function_name = s[5][0]
823
- ss = [the_function_name, x] + s[6:]
824
- conditions.append(f(ss, c))
825
- pass
826
-
827
- return has_matching_sublist(
828
- my_list=the_list,
829
- required_match_count=required_match_count,
830
- position=position,
831
- contiguous=contiguous,
832
- conditions=conditions,
833
- )
834
-
835
- def Strptime(s):
836
- datetime_str = f(s[1], c)
837
- parameters = f(s[2], c)
838
- return datetime.datetime.strptime(datetime_str, parameters).isoformat()
839
-
840
- def Strftime(s):
841
- dt = _try_parse_datetime(f(s[1], c))
842
- if not isinstance(dt, (datetime.datetime, datetime.date)):
843
- raise ValueError(f"Strftime: could not parse input as datetime: {dt!r}")
844
- parameters = f(s[2], c)
845
- return dt.strftime(parameters)
846
-
847
- def Now(s):
848
- return datetime.datetime.now().isoformat()
849
-
850
- def Today(s):
851
- return datetime.date.today().isoformat()
852
-
853
- def TimeDeltaDays(s):
854
- return datetime.timedelta(days=f(s[1], c))
855
-
856
- def TimeDeltaMinutes(s):
857
- return datetime.timedelta(minutes=f(s[1], c))
858
-
859
- def TimeDeltaHours(s):
860
- return datetime.timedelta(hours=f(s[1], c))
861
-
862
- def TimeDeltaWeeks(s):
863
- return datetime.timedelta(weeks=f(s[1], c))
864
-
865
- # def Equal(s):
866
- # a = comparison_safe_converter(f(s[1], c))
867
- # b = comparison_safe_converter(f(s[2], c))
868
- # return a == b
869
- # if type(a) in [int, float, str]:
870
- # a = f"{a}"
871
- # elif type(a) in [bool, NoneType]:
872
- # if a:
873
- # a = True
874
- # else:
875
- # a = None
876
-
877
- # if is_numeric(a):
878
-
879
- # lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
880
-
881
- def IsDefined(s):
882
- return s[1] in solver_parameters or s[1] in c
883
-
884
- def IsUndefined(s):
885
- return not IsDefined(s)
886
-
887
- def Greater(s):
888
- v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
889
- try:
890
- return v1 > v2
891
- except TypeError:
892
- return False
893
-
894
- def GreaterEqual(s):
895
- v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
896
- try:
897
- return v1 >= v2
898
- except TypeError:
899
- return False
900
-
901
- def Less(s):
902
- v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
903
- try:
904
- return v1 < v2
905
- except TypeError:
906
- return False
907
-
908
- def LessEqual(s):
909
- v1, v2 = comparison_safe_converter_for_pairs(f(s[1], c), f(s[2], c))
352
+ for x in s[1:-1]:
353
+ if len(x) != 2:
354
+ raise ValueError("Wrong if or elif in 'If'")
355
+ try:
356
+ if f(x[0], c):
910
357
  try:
911
- return v1 <= v2
912
- except TypeError:
913
- return False
914
-
915
- def BooleanAnd(s):
916
- """
917
- Boolean AND operation.
918
- ["And", condition1, condition2, ...]
919
- """
920
- for x in s[1:]:
921
- if not f(x, c):
922
- return False
923
- return True
924
-
925
- def BooleanOr(s):
926
- """
927
- Boolean OR operation.
928
- ["Or", condition1, condition2, ...]
929
- """
930
- for x in s[1:]:
931
- if f(x, c):
932
- return True
933
- return False
934
-
935
- # sin, cos, tan, arcsin, arccos, arctan
936
- def Sin(s):
937
- return math.sin(f(s[1], c))
938
-
939
- def Arcsin(s):
940
- return math.asin(f(s[1], c))
941
-
942
- def Cos(s):
943
- return math.cos(f(s[1], c))
944
-
945
- def Arccos(s):
946
- return math.acos(f(s[1], c))
947
-
948
- def Tan(s):
949
- return math.tan(f(s[1], c))
950
-
951
- def Arctan(s):
952
- return math.atan(f(s[1], c))
953
-
954
- def Pi(s):
955
- return math.pi
956
-
957
- def Variable(s):
958
- """
959
- ["Variable", variable_name]
960
- The `variable_name` must be a string.
961
- """
962
- variable_name = s[1]
963
- if variable_name in c:
964
- return f(c[variable_name], c)
965
- else:
966
- raise KeyError(f"Variable '{variable_name}' is not defined")
967
-
968
- def Function(s):
969
- """
970
- ["Function", body_expression, param_name1, param_name2, ...]
971
- Defines a CortexJS-style lambda: `body_expression` is evaluated
972
- with the given parameter names bound to whatever arguments it
973
- is called with. `Function` expressions are meant to be passed
974
- as the `function` argument of Map, Filter, and Reduce; if no
975
- parameter names are given, the anonymous placeholders "_",
976
- "_1", "_2", ... are used instead (see those functions).
977
- Evaluating a ["Function", ...] expression outside of such a
978
- context just returns it unevaluated.
979
- """
980
- return s
981
-
982
- def MultiplyByScalar(s):
983
- """
984
- ["MultiplyByScalar", array, scalar]
985
- The `array` must be an array of numeric values.
986
- The `scalar` is the number to multiply each element by.
987
- """
988
- array = f(s[1], c)
989
- scalar = f(s[2], c)
990
- if not (isinstance(array, list) and array[0] == "Array"):
991
- raise ValueError("Parameter 1 must be an array.")
992
- array = [f(x, c) for x in array[1:]]
993
- return ["Array"] + _MultiplyByScalar(array, scalar)
994
-
995
- def MultiplyByArray(s):
996
- """
997
- ["MultiplyByArray", array1, array2]
998
- The `array1` and `array2` must be arrays of the same length.
999
- """
1000
- array1 = f(s[1], c)
1001
- array2 = f(s[2], c)
1002
- if not (isinstance(array1, list) and array1[0] == "Array"):
1003
- raise ValueError("Parameter 1 must be an array.")
1004
- if not (isinstance(array2, list) and array2[0] == "Array"):
1005
- raise ValueError("Parameter 2 must be an array.")
1006
- array1 = [f(x, c) for x in array1[1:]]
1007
- array2 = [f(x, c) for x in array2[1:]]
1008
- if len(array1) != len(array2):
1009
- raise ValueError("Both arrays must be of the same length.")
1010
- return ["Array"] + _MultiplyByArray(array1, array2)
1011
-
1012
- def AddScalar(s):
1013
- """
1014
- ["AddScalar", array, scalar]
1015
- The `array` must be an array of numeric values.
1016
- The `scalar` is the number to add to each element.
1017
- """
1018
- array = f(s[1], c)
1019
- scalar = f(s[2], c)
1020
- if not (isinstance(array, list) and array[0] == "Array"):
1021
- raise ValueError("Parameter 1 must be an array.")
1022
- array = [f(x, c) for x in array[1:]]
1023
- return ["Array"] + _AddScalar(array, scalar)
1024
-
1025
- def SubtractScalar(s):
1026
- """
1027
- ["SubtractScalar", array, scalar]
1028
- The `array` must be an array of numeric values.
1029
- The `scalar` is the number to subtract from each element.
1030
- """
1031
- array = f(s[1], c)
1032
- scalar = f(s[2], c)
1033
- if not (isinstance(array, list) and array[0] == "Array"):
1034
- raise ValueError("Parameter 1 must be an array.")
1035
- array = [f(x, c) for x in array[1:]]
1036
- return ["Array"] + _SubtractScalar(array, scalar)
1037
-
1038
- def AddArray(s):
1039
- """
1040
- ["AddArray", array1, array2]
1041
- The `array1` and `array2` must be arrays of the same length.
1042
- """
1043
- array1 = f(s[1], c)
1044
- array2 = f(s[2], c)
1045
- if not (isinstance(array1, list) and array1[0] == "Array"):
1046
- raise ValueError("Parameter 1 must be an array.")
1047
- if not (isinstance(array2, list) and array2[0] == "Array"):
1048
- raise ValueError("Parameter 2 must be an array.")
1049
- array1 = [f(x, c) for x in array1[1:]]
1050
- array2 = [f(x, c) for x in array2[1:]]
1051
- if len(array1) != len(array2):
1052
- raise ValueError("Both arrays must be of the same length.")
1053
- return ["Array"] + _AddArray(array1, array2)
1054
-
1055
- def SubtractArray(s):
1056
- """
1057
- ["SubtractArray", array1, array2]
1058
- The `array1` and `array2` must be arrays of the same length.
1059
- """
1060
- array1 = f(s[1], c)
1061
- array2 = f(s[2], c)
1062
- if not (isinstance(array1, list) and array1[0] == "Array"):
1063
- raise ValueError("Parameter 1 must be an array.")
1064
- if not (isinstance(array2, list) and array2[0] == "Array"):
1065
- raise ValueError("Parameter 2 must be an array.")
1066
- array1 = [f(x, c) for x in array1[1:]]
1067
- array2 = [f(x, c) for x in array2[1:]]
1068
- if len(array1) != len(array2):
1069
- raise ValueError("Both arrays must be of the same length.")
1070
- return ["Array"] + _SubtractArray(array1, array2)
1071
-
1072
- def GenerateRange(s):
1073
- """
1074
- ["GenerateRange", end]
1075
- or
1076
- ["GenerateRange", start, end, step]
1077
- The `start`, `end`, and `step` are numeric values.
1078
- """
1079
- if len(s) == 2:
1080
- end = f(s[1], c)
1081
- start = 0
1082
- step = 1
1083
- elif len(s) == 4:
1084
- start = f(s[1], c)
1085
- end = f(s[2], c)
1086
- step = f(s[3], c)
1087
- else:
1088
- raise ValueError(
1089
- "GenerateRange requires either 1 or 3 parameters (end or start, end, step)."
1090
- )
1091
- if step == 0:
1092
- raise ValueError("Step cannot be zero.")
1093
- if (start < end and step < 0) or (start > end and step > 0):
1094
- raise ValueError("Step direction is incorrect for the given range.")
1095
- result = ["Array"]
1096
- if start < end:
1097
- current = start
1098
- while current < end:
1099
- result.append(current)
1100
- current += step
1101
- else:
1102
- current = start
1103
- while current > end:
1104
- result.append(current)
1105
- current += step
1106
- return result
1107
-
1108
- def AtIndex(s):
1109
- """
1110
- ["AtIndex", array, index]
1111
- The `array` must be an array of values.
1112
- The `index` is the index of the element to retrieve.
1113
- """
1114
- array = f(s[1], c)
1115
- index = f(s[2], c)
1116
- if not (isinstance(array, list) and array[0] == "Array"):
1117
- raise ValueError("Parameter 1 must be an array.")
1118
- # array = [f(x, c) for x in array[1:]]
1119
- # return array[index]
1120
- array = [x for x in array[1:]]
1121
- return f(array[index], c)
1122
-
1123
- def Slice(s):
1124
- """
1125
- ["Slice", array, start, end]
1126
- The `array` must be an array of values.
1127
- The `start` and `end` are the slice indices.
1128
- """
1129
- array = f(s[1], c)
1130
- start = f(s[2], c)
1131
- end = f(s[3], c)
1132
- if not (isinstance(array, list) and array[0] == "Array"):
1133
- raise ValueError("Parameter 1 must be an array.")
1134
- array = [f(x, c) for x in array[1:]]
1135
- return ["Array"] + array[start:end]
1136
-
1137
- def CumulativeProduct(s):
1138
- """
1139
- ["CumulativeProduct", array]
1140
- The `array` must be an array of numeric values.
1141
- """
1142
- array = f(s[1], c)
1143
- if not (isinstance(array, list) and array[0] == "Array"):
1144
- raise ValueError("Parameter 1 must be an array.")
1145
- array = [f(x, c) for x in array[1:]]
1146
- return ["Array"] + _CumulativeProduct(array)
1147
- # return _CumulativeProduct(array)
1148
-
1149
- def CumulativeSum(s):
1150
- """
1151
- ["CumulativeSum", array]
1152
- The `array` must be an array of numeric values.
1153
- """
1154
- array = f(s[1], c)
1155
- if not (isinstance(array, list) and array[0] == "Array"):
1156
- raise ValueError("Parameter 1 must be an array.")
1157
- array = [f(x, c) for x in array[1:]]
1158
- return ["Array"] + _CumulativeSum(array)
1159
- # return
1160
-
1161
- def Interp(s):
1162
- """
1163
- ["Interp", x_array, y_array, target_x]
1164
- The `x_array` and `y_array` must be arrays of the same length.
1165
- The `target_x` is the x value to interpolate for.
1166
- """
1167
- x_array = f(s[1], c)
1168
- y_array = f(s[2], c)
1169
- target_x = f(s[3], c)
1170
- if not (isinstance(x_array, list) and x_array[0] == "Array"):
1171
- raise ValueError("Parameter 1 must be an array.")
1172
- if not (isinstance(y_array, list) and y_array[0] == "Array"):
1173
- raise ValueError("Parameter 2 must be an array.")
1174
- x_array = [f(x, c) for x in x_array[1:]]
1175
- y_array = [f(y, c) for y in y_array[1:]]
1176
- return linear_interpolate(x_array, y_array, target_x)
1177
-
1178
- def FindIntervalIndex(s):
1179
- """
1180
- ["FindIntervalIndex", array, target_value]
1181
- The `array` must be an array of numeric values.
1182
- The `target_value` is the value to find the interval index for.
1183
- """
1184
- array = f(s[1], c)
1185
- target_value = f(s[2], c)
1186
- if not (isinstance(array, list) and array[0] == "Array"):
1187
- raise ValueError("Parameter 1 must be an array.")
1188
- array = [f(x, c) for x in array[1:]]
1189
- zz = find_interpolation_bounds_2indexes(array, target_value)
1190
- return zz[0]
1191
-
1192
- def TrapezoidalIntegrate(s):
1193
- """
1194
- ["TrapezoidalIntegrate", function_expression, start, end, n, variable]
1195
- """
1196
- if not NUMPY_AVAILABLE:
1197
- raise ImportError(
1198
- "TrapezoidalIntegrate requires 'numpy'. Install with 'pip install numpy'."
1199
- )
1200
- function_expression = s[1]
1201
- start = f(s[2], c)
1202
- end = f(s[3], c)
1203
- n = f(s[4], c)
1204
- variable = s[5]
1205
-
1206
- t = np.linspace(start, end, n + 1)
1207
-
1208
- # Calculate the integral using the trapezoidal rule
1209
-
1210
- values = []
1211
- for x in t:
1212
- variable_name = variable[1]
1213
- variable_value = x
1214
- c[variable_name] = variable_value
1215
- values.append(f(function_expression, c))
1216
- h = (end - start) / n
1217
- return h * (0.5 * values[0] + np.sum(values[1:-1]) + 0.5 * values[-1])
1218
-
1219
- # return total_area
1220
-
1221
- def Reduce(s):
1222
- """
1223
- Two calling conventions, disambiguated by argument count:
1224
-
1225
- CortexJS form (3 or 4 arguments):
1226
- ["Reduce", list, function]
1227
- ["Reduce", list, function, initial_value]
1228
- `function` is applied as `function(accumulator, current_item)`
1229
- on each element; without `initial_value`, the first element
1230
- seeds the accumulator. `function` can be a call template
1231
- (e.g. ["Add"]) or a ["Function", body, ...params] expression
1232
- (see `_apply_fn`).
1233
-
1234
- Original Python form (6 arguments):
1235
- ["Reduce", list, initial_value, function, str_name_of_accumulator, str_name_of_current, str_name_of_index]
1236
- """
1237
- if len(s) <= 4:
1238
- the_list = f(s[1], c)
1239
- if not (isinstance(the_list, list) and the_list[0] == "Array"):
1240
- raise ValueError("Parameter 1 must be an array.")
1241
- elements = the_list[1:]
1242
- fn_expr = s[2]
1243
-
1244
- if len(s) == 4:
1245
- accumulator = f(s[3], c)
1246
- remaining = elements
1247
- else:
1248
- if not elements:
1249
- raise ValueError(
1250
- "'Reduce' on an empty collection requires an initial value."
1251
- )
1252
- accumulator = f(elements[0], c)
1253
- remaining = elements[1:]
1254
-
1255
- for x in remaining:
1256
- accumulator = _apply_fn(fn_expr, [accumulator, x])
1257
- return accumulator
1258
-
1259
- the_list = f(s[1], c)[1:]
1260
- initial_value = f(s[2], c)
1261
- function_expression = s[3]
1262
-
1263
- _accumulator = s[4]
1264
- name_accumulator = _accumulator[1]
1265
-
1266
- _current = s[5]
1267
- name_current = _current[1]
1268
-
1269
- _index = s[6]
1270
- name_index = _index[1]
1271
-
1272
- c[name_accumulator] = initial_value
1273
-
1274
- for i, x in enumerate(the_list):
1275
- c[name_current] = x
1276
- c[name_index] = i
1277
- c[name_accumulator] = f(function_expression, c)
1278
-
1279
- return c[name_accumulator]
1280
-
1281
- def Product(s):
1282
- """
1283
- ["Product", array]
1284
- Multiplies together the numeric elements of `array`.
1285
- """
1286
- the_list = f(s[1], c)
1287
- if not (isinstance(the_list, list) and the_list[0] == "Array"):
1288
- raise ValueError("Parameter 1 must be an array.")
1289
- result = 1
1290
- for x in the_list[1:]:
1291
- result *= f(x, c)
1292
- return result
1293
-
1294
- def Appended(s):
1295
- """
1296
- ["Appended", array, value]
1297
- The `array` must be an array of values.
1298
- The `value` is the value to append to the array.
1299
- """
1300
- array = f(s[1], c)
1301
-
1302
- if not (isinstance(array, list) and array[0] == "Array"):
1303
- raise ValueError("Parameter 1 must be an array.")
1304
-
1305
- value = f(s[2], c)
1306
-
1307
- array = [x for x in array[1:]]
1308
- array.append(value)
1309
- return ["Array"] + array
358
+ return f(x[1], c)
359
+ except MathJSONException:
360
+ # Branch failed, try next condition
361
+ continue
362
+ except MathJSONException:
363
+ return f(s[-1], c) # return default value (else)
364
+
365
+ return f(s[-1], c)
366
+
367
+
368
+ constructs = {
369
+ "Sum": Sum,
370
+ "Add": Add,
371
+ "Subtract": Subtract,
372
+ "Constants": Constants,
373
+ "Switch": Switch,
374
+ "StrictSwitch": StrictSwitch,
375
+ "If": If,
376
+ "Multiply": lambda f, c, solver_parameters, s: reduce(
377
+ lambda a, b: float(a) * float(b), [f(x, c) for x in s[1:]]
378
+ ),
379
+ "Divide": lambda f, c, solver_parameters, s: f(s[1], c) / f(s[2], c),
380
+ "Negate": lambda f, c, solver_parameters, s: -f(s[1], c),
381
+ "Power": lambda f, c, solver_parameters, s: pow(f(s[1], c), f(s[2], c)),
382
+ "Root": lambda f, c, solver_parameters, s: pow(f(s[1], c), 1.0 / f(s[2], c)),
383
+ "Sqrt": lambda f, c, solver_parameters, s: pow(f(s[1], c), 1.0 / 2),
384
+ "Square": lambda f, c, solver_parameters, s: pow(f(s[1], c), 2),
385
+ "Exp": lambda f, c, solver_parameters, s: math.exp(f(s[1], c)),
386
+ # CortexJS-compatible: ["Log", x] is log base 10; ["Log", x, b] is
387
+ # log base b. Use "Ln" for natural log. (BREAKING as of 2.0.0 -
388
+ # "Log" previously meant natural log.)
389
+ "Log": lambda f, c, solver_parameters, s: (
390
+ math.log10(f(s[1], c)) if len(s) == 2 else math.log(f(s[1], c), f(s[2], c))
391
+ ),
392
+ "Log2": lambda f, c, solver_parameters, s: math.log2(f(s[1], c)),
393
+ "Log10": lambda f, c, solver_parameters, s: math.log10(f(s[1], c)),
394
+ "Ln": lambda f, c, solver_parameters, s: math.log(f(s[1], c)),
395
+ "Lb": lambda f, c, solver_parameters, s: math.log2(
396
+ f(s[1], c)
397
+ ), # CortexJS name for Log2
398
+ "Lg": lambda f, c, solver_parameters, s: math.log10(
399
+ f(s[1], c)
400
+ ), # CortexJS name for Log10
401
+ "LogOnePlus": lambda f, c, solver_parameters, s: math.log1p(f(s[1], c)),
402
+ # "Equal": lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
403
+ "Equal": lambda f, c, solver_parameters, s: comparison_safe_converter(f(s[1], c))
404
+ == comparison_safe_converter(f(s[2], c)),
405
+ "IsTrue": lambda f, c, solver_parameters, s: bool(f(s[1], c)),
406
+ "IsFalse": lambda f, c, solver_parameters, s: not bool(f(s[1], c)),
407
+ "StrictEqual": lambda f, c, solver_parameters, s: f(s[1], c) == f(s[2], c),
408
+ "IdenticallyEqual": IdenticallyEqual,
409
+ "Congruent": Congruent,
410
+ # "Greater": lambda s: f(s[1], c) > f(s[2], c),
411
+ "Greater": Greater,
412
+ # "GreaterEqual": lambda s: f(s[1], c) >= f(s[2], c),
413
+ "GreaterEqual": GreaterEqual,
414
+ # "Less": lambda s: f(s[1], c) < f(s[2], c),
415
+ "Less": Less,
416
+ # "LessEqual": lambda s: f(s[1], c) <= f(s[2], c),
417
+ "LessEqual": LessEqual,
418
+ # "NotEqual": lambda s: f(s[1], c) != f(s[2], c),
419
+ "NotEqual": lambda f, c, solver_parameters, s: comparison_safe_converter(f(s[1], c))
420
+ != comparison_safe_converter(f(s[2], c)),
421
+ "And": BooleanAnd,
422
+ "Or": BooleanOr,
423
+ "Abs": lambda f, c, solver_parameters, s: abs(f(s[1], c)),
424
+ "Round": lambda f, c, solver_parameters, s: (
425
+ round(f(s[1], c), f(s[2], c)) if len(s) == 3 else int(round(f(s[1], c)))
426
+ ),
427
+ "Max": Max,
428
+ "Min": Min,
429
+ "Average": Average,
430
+ "Mean": Average, # CortexJS name for Average
431
+ "Median": Median,
432
+ "Length": Length,
433
+ "Count": Length, # CortexJS name for Length
434
+ "Any": Any,
435
+ "All": All,
436
+ "Array": Arr,
437
+ "List": lambda f, c, solver_parameters, s: ["Array"]
438
+ + [f(x, c) for x in s[1:]], # CortexJS name for Array
439
+ "In": In,
440
+ "Not_in": Not_in,
441
+ "Element": In, # CortexJS name for In - array, string, or Interval membership
442
+ "NotElement": Not_in, # CortexJS name for Not_in
443
+ "Contains_any_of": Contains_any_of,
444
+ "Contains_all_of": Contains_all_of,
445
+ "Contains_none_of": Contains_none_of,
446
+ "NotIn": Not_in,
447
+ "ContainsAnyOf": Contains_any_of,
448
+ "ContainsAllOf": Contains_all_of,
449
+ "ContainsNoneOf": Contains_none_of,
450
+ "Int": Int,
451
+ "Float": Float,
452
+ "Floor": Floor,
453
+ "Ceil": Ceil,
454
+ "Str": Str,
455
+ # --- Strings ---
456
+ "String": String,
457
+ "StringJoin": StringJoin,
458
+ "ToUpperCase": lambda f, c, solver_parameters, s: f(s[1], c).upper(),
459
+ "ToLowerCase": lambda f, c, solver_parameters, s: f(s[1], c).lower(),
460
+ "CaseFold": lambda f, c, solver_parameters, s: f(s[1], c).casefold(),
461
+ "Trim": lambda f, c, solver_parameters, s: f(s[1], c).strip(),
462
+ "TrimStart": lambda f, c, solver_parameters, s: f(s[1], c).lstrip(),
463
+ "TrimEnd": lambda f, c, solver_parameters, s: f(s[1], c).rstrip(),
464
+ "StringSplit": StringSplit,
465
+ "StringReplace": StringReplace,
466
+ "StringCompare": StringCompare,
467
+ "StringRepeat": StringRepeat,
468
+ "PadStart": PadStart,
469
+ "PadEnd": PadEnd,
470
+ "Characters": Characters,
471
+ "GraphemeClusters": Characters, # CortexJS synonym for Characters
472
+ "Utf8": Utf8,
473
+ "Utf16": Utf16,
474
+ "UnicodeScalars": UnicodeScalars,
475
+ "StringFrom": StringFrom,
476
+ "IntegerString": IntegerString,
477
+ "DigitsFrom": DigitsFrom,
478
+ "NumberFrom": NumberFrom,
479
+ "RegExp": RegExp,
480
+ "IsMatch": IsMatch,
481
+ "StringMatch": StringMatch,
482
+ "StringMatchAll": StringMatchAll,
483
+ "Not": Not,
484
+ # "IsDefined": lambda s: s[1] in c,
485
+ "IsDefined": IsDefined,
486
+ "IsUndefined": IsUndefined,
487
+ "Map": Map,
488
+ "StrictMap": StrictMap,
489
+ "Filter": Filter,
490
+ "HasMatchingSublist": HasMatchingSublist,
491
+ "Strptime": Strptime,
492
+ "Strftime": Strftime,
493
+ "Today": Today,
494
+ "Now": Now,
495
+ "TimeDeltaWeeks": TimeDeltaWeeks,
496
+ "TimeDeltaHours": TimeDeltaHours,
497
+ "TimeDeltaMinutes": TimeDeltaMinutes,
498
+ "TimeDeltaDays": TimeDeltaDays,
499
+ "Function": Function,
500
+ "Variable": Variable,
501
+ "MultiplyByScalar": MultiplyByScalar,
502
+ "MultiplyByArray": MultiplyByArray,
503
+ "AddScalar": AddScalar,
504
+ "SubtractScalar": SubtractScalar,
505
+ "AddArray": AddArray,
506
+ "SubtractArray": SubtractArray,
507
+ "GenerateRange": GenerateRange,
508
+ "AtIndex": AtIndex,
509
+ "Slice": Slice,
510
+ "CumulativeProduct": CumulativeProduct,
511
+ "CumulativeSum": CumulativeSum,
512
+ "Interp": Interp,
513
+ "FindIntervalIndex": FindIntervalIndex,
514
+ "TrapezoidalIntegrate": TrapezoidalIntegrate,
515
+ "Reduce": Reduce,
516
+ "Product": Product,
517
+ "Appended": Appended,
518
+ "Sin": Sin,
519
+ "Cos": Cos,
520
+ "Tan": Tan,
521
+ "Arcsin": Arcsin,
522
+ "Arccos": Arccos,
523
+ "Arctan": Arctan,
524
+ "Arctan2": lambda f, c, solver_parameters, s: math.atan2(f(s[1], c), f(s[2], c)),
525
+ "Pi": Pi,
526
+ "Which": Which, # CortexJS multi-branch conditional (not Switch - see Which's docstring)
527
+ # --- Trigonometric: reciprocal, hyperbolic, area-hyperbolic ---
528
+ "Cot": lambda f, c, solver_parameters, s: 1 / math.tan(f(s[1], c)),
529
+ "Sec": lambda f, c, solver_parameters, s: 1 / math.cos(f(s[1], c)),
530
+ "Csc": lambda f, c, solver_parameters, s: 1 / math.sin(f(s[1], c)),
531
+ "Arccot": lambda f, c, solver_parameters, s: math.atan(1 / f(s[1], c)),
532
+ "Arcsec": lambda f, c, solver_parameters, s: math.acos(1 / f(s[1], c)),
533
+ "Arccsc": lambda f, c, solver_parameters, s: math.asin(1 / f(s[1], c)),
534
+ "Sinh": lambda f, c, solver_parameters, s: math.sinh(f(s[1], c)),
535
+ "Cosh": lambda f, c, solver_parameters, s: math.cosh(f(s[1], c)),
536
+ "Tanh": lambda f, c, solver_parameters, s: math.tanh(f(s[1], c)),
537
+ "Coth": lambda f, c, solver_parameters, s: 1 / math.tanh(f(s[1], c)),
538
+ "Sech": lambda f, c, solver_parameters, s: 1 / math.cosh(f(s[1], c)),
539
+ "Csch": lambda f, c, solver_parameters, s: 1 / math.sinh(f(s[1], c)),
540
+ "Arsinh": lambda f, c, solver_parameters, s: math.asinh(f(s[1], c)),
541
+ "Arcosh": lambda f, c, solver_parameters, s: math.acosh(f(s[1], c)),
542
+ "Artanh": lambda f, c, solver_parameters, s: math.atanh(f(s[1], c)),
543
+ "Arcoth": lambda f, c, solver_parameters, s: math.atanh(1 / f(s[1], c)),
544
+ "Arsech": lambda f, c, solver_parameters, s: math.acosh(1 / f(s[1], c)),
545
+ "Arcsch": lambda f, c, solver_parameters, s: math.asinh(1 / f(s[1], c)),
546
+ "Hypot": lambda f, c, solver_parameters, s: math.hypot(f(s[1], c), f(s[2], c)),
547
+ "Sinc": lambda f, c, solver_parameters, s: (
548
+ 1.0 if f(s[1], c) == 0 else math.sin(f(s[1], c)) / f(s[1], c)
549
+ ),
550
+ # --- Constants ---
551
+ "Degrees": lambda f, c, solver_parameters, s: math.pi / 180,
552
+ "ExponentialE": lambda f, c, solver_parameters, s: math.e,
553
+ "GoldenRatio": lambda f, c, solver_parameters, s: (1 + math.sqrt(5)) / 2,
554
+ "MachineEpsilon": lambda f, c, solver_parameters, s: sys.float_info.epsilon,
555
+ "CatalanConstant": lambda f, c, solver_parameters, s: 0.915965594177219015054603514932384110774,
556
+ "EulerGamma": lambda f, c, solver_parameters, s: 0.5772156649015328606065120900824024310421,
557
+ "Rational": Rational,
558
+ "Numerator": Numerator,
559
+ "Denominator": Denominator,
560
+ # --- Number theory / special functions ---
561
+ "Chop": lambda f, c, solver_parameters, s: (
562
+ 0 if abs(f(s[1], c)) < 1e-10 else f(s[1], c)
563
+ ),
564
+ "Mod": lambda f, c, solver_parameters, s: f(s[1], c) % f(s[2], c),
565
+ "Clamp": Clamp,
566
+ "GCD": lambda f, c, solver_parameters, s: math.gcd(
567
+ int(f(s[1], c)), int(f(s[2], c))
568
+ ),
569
+ "LCM": lambda f, c, solver_parameters, s: math.lcm(
570
+ int(f(s[1], c)), int(f(s[2], c))
571
+ ),
572
+ "Factorial": lambda f, c, solver_parameters, s: math.factorial(int(f(s[1], c))),
573
+ "Binomial": lambda f, c, solver_parameters, s: math.comb(
574
+ int(f(s[1], c)), int(f(s[2], c))
575
+ ),
576
+ "IsPrime": IsPrime,
577
+ "Erf": lambda f, c, solver_parameters, s: math.erf(f(s[1], c)),
578
+ "Erfc": lambda f, c, solver_parameters, s: math.erfc(f(s[1], c)),
579
+ # --- Number theory ---
580
+ "PowerMod": lambda f, c, solver_parameters, s: pow(
581
+ int(f(s[1], c)), int(f(s[2], c)), int(f(s[3], c))
582
+ ),
583
+ "ModularInverse": lambda f, c, solver_parameters, s: pow(
584
+ int(f(s[1], c)), -1, int(f(s[2], c))
585
+ ),
586
+ "IntegerSqrt": lambda f, c, solver_parameters, s: math.isqrt(int(f(s[1], c))),
587
+ "FactorInteger": FactorInteger,
588
+ "PrimeFactors": PrimeFactors,
589
+ "PrimeNu": PrimeNu,
590
+ "PrimeOmega": PrimeOmega,
591
+ "Radical": Radical,
592
+ "IsSquareFree": IsSquareFree,
593
+ "Divisors": Divisors,
594
+ "Sigma0": Sigma0,
595
+ "Sigma1": Sigma1,
596
+ "SigmaMinus1": SigmaMinus1,
597
+ "DivisorSigma": DivisorSigma,
598
+ "Divides": lambda f, c, solver_parameters, s: f(s[2], c) % f(s[1], c) == 0,
599
+ "Totient": Totient,
600
+ "IsPerfectPower": IsPerfectPower,
601
+ "NthPrime": NthPrime,
602
+ "NextPrime": NextPrime,
603
+ "PrimePi": PrimePi,
604
+ "ExtendedGCD": ExtendedGCD,
605
+ "ChineseRemainder": ChineseRemainder,
606
+ "CarmichaelLambda": CarmichaelLambda,
607
+ "JacobiSymbol": JacobiSymbol,
608
+ "LegendreSymbol": JacobiSymbol, # same algorithm when n is prime
609
+ "MultiplicativeOrder": MultiplicativeOrder,
610
+ "PrimitiveRoot": PrimitiveRoot,
611
+ "LucasL": LucasL,
612
+ "CatalanNumber": lambda f, c, solver_parameters, s: math.comb(
613
+ 2 * int(f(s[1], c)), int(f(s[1], c))
614
+ )
615
+ // (int(f(s[1], c)) + 1),
616
+ "BernoulliB": BernoulliB,
617
+ "ContinuedFraction": ContinuedFraction,
618
+ "FromContinuedFraction": FromContinuedFraction,
619
+ "IntegerDigits": IntegerDigits,
620
+ "DigitCount": DigitCount,
621
+ "DigitSum": DigitSum,
622
+ "FromDigits": FromDigits,
623
+ "IsSquare": IsSquare,
624
+ "IsTriangular": IsTriangular,
625
+ "IsPentagonal": IsPentagonal,
626
+ "IsOctahedral": IsOctahedral,
627
+ "IsCenteredSquare": IsCenteredSquare,
628
+ "IsPerfect": IsPerfect,
629
+ "IsAbundant": IsAbundant,
630
+ "IsHappy": IsHappy,
631
+ # --- Special functions ---
632
+ "Gamma": lambda f, c, solver_parameters, s: math.gamma(f(s[1], c)),
633
+ "GammaLn": lambda f, c, solver_parameters, s: math.lgamma(f(s[1], c)),
634
+ "Beta": Beta,
635
+ "Factorial2": Factorial2,
636
+ "ErfInv": ErfInv,
637
+ "LambertW": LambertW,
638
+ "AGM": AGM,
639
+ "EllipticK": EllipticK,
640
+ "EllipticE": EllipticE,
641
+ "Hypergeometric1F1": Hypergeometric1F1,
642
+ "Hypergeometric2F1": Hypergeometric2F1,
643
+ "BesselJ": BesselJ,
644
+ "BesselY": BesselY,
645
+ "BesselI": BesselI,
646
+ "BesselK": BesselK,
647
+ "AiryAi": AiryAi,
648
+ "AiryBi": AiryBi,
649
+ "AiryAiPrime": AiryAiPrime,
650
+ "AiryBiPrime": AiryBiPrime,
651
+ "Zeta": Zeta,
652
+ "GammaRegularized": GammaRegularized,
653
+ "BetaRegularized": BetaRegularized,
654
+ # --- Combinatorics (trivial subset) ---
655
+ "Choose": lambda f, c, solver_parameters, s: math.comb(
656
+ int(f(s[1], c)), int(f(s[2], c))
657
+ ),
658
+ "Fibonacci": Fibonacci,
659
+ "Multinomial": Multinomial,
660
+ "Subfactorial": Subfactorial,
661
+ "BellNumber": BellNumber,
662
+ "PowerSet": PowerSet,
663
+ "Permutations": Permutations,
664
+ "Combinations": Combinations,
665
+ "CartesianProduct": CartesianProduct,
666
+ # --- Core: structural introspection ---
667
+ "Head": Head,
668
+ "Tail": Tail,
669
+ "Hold": Hold,
670
+ "Identity": lambda f, c, solver_parameters, s: f(s[1], c),
671
+ "Type": Type,
672
+ "IsSame": IsSame,
673
+ "Same": IsSame, # see IsSame's docstring for the distinction CortexJS draws
674
+ # --- Boolean logic ---
675
+ "Xor": lambda f, c, solver_parameters, s: bool(f(s[1], c)) ^ bool(f(s[2], c)),
676
+ "Nand": lambda f, c, solver_parameters, s: not all(f(x, c) for x in s[1:]),
677
+ "Nor": lambda f, c, solver_parameters, s: not any(f(x, c) for x in s[1:]),
678
+ "Implies": lambda f, c, solver_parameters, s: (not f(s[1], c)) or bool(f(s[2], c)),
679
+ "Equivalent": lambda f, c, solver_parameters, s: bool(f(s[1], c))
680
+ == bool(f(s[2], c)),
681
+ # --- Statistics ---
682
+ "Variance": Variance,
683
+ "StandardDeviation": StandardDeviation,
684
+ "PopulationVariance": PopulationVariance,
685
+ "PopulationStandardDeviation": PopulationStandardDeviation,
686
+ "Mode": Mode,
687
+ "Quartiles": Quartiles,
688
+ "InterquartileRange": InterquartileRange,
689
+ "Covariance": Covariance,
690
+ "Correlation": Correlation,
691
+ "Skewness": Skewness,
692
+ "Kurtosis": Kurtosis,
693
+ "LinearRegression": LinearRegression,
694
+ "PolynomialFit": PolynomialFit,
695
+ "NormalDistribution": NormalDistribution,
696
+ "BinomialDistribution": BinomialDistribution,
697
+ "PoissonDistribution": PoissonDistribution,
698
+ "UniformDistribution": UniformDistribution,
699
+ "ExponentialDistribution": ExponentialDistribution,
700
+ "PDF": PDF,
701
+ "CDF": CDF,
702
+ "Quantile": Quantile,
703
+ # --- Collections ---
704
+ "First": First,
705
+ "Second": Second,
706
+ "Third": Third,
707
+ "Last": Last,
708
+ "Rest": Rest,
709
+ "Most": Most,
710
+ "Reverse": Reverse,
711
+ "Sort": Sort,
712
+ "IsEmpty": IsEmpty,
713
+ "Range": Range,
714
+ "Join": Join,
715
+ "Unique": Unique,
716
+ "Zip": Zip,
717
+ "At": At,
718
+ "Take": Take,
719
+ "Drop": Drop,
720
+ "TakeWhile": TakeWhile,
721
+ "DropWhile": DropWhile,
722
+ "Contains": Contains,
723
+ "IndexOf": IndexOf,
724
+ "IndexWhere": IndexWhere,
725
+ "Find": Find,
726
+ "CountIf": CountIf,
727
+ "Position": Position,
728
+ "RotateLeft": RotateLeft,
729
+ "RotateRight": RotateRight,
730
+ "MaxBy": MaxBy,
731
+ "MinBy": MinBy,
732
+ "ArgMax": ArgMax,
733
+ "ArgMin": ArgMin,
734
+ "Ordering": Ordering,
735
+ "FlatMap": FlatMap,
736
+ "Scan": Scan,
737
+ "Differences": Differences,
738
+ "Fold": Fold,
739
+ "Dedup": Dedup,
740
+ "Append": Appended, # CortexJS name for Appended
741
+ "Insert": Insert,
742
+ "DeleteAt": DeleteAt,
743
+ "ReplaceAt": ReplaceAt,
744
+ "Partition": Partition,
745
+ "Chunk": Chunk,
746
+ "GroupBy": GroupBy,
747
+ "ChunkBy": ChunkBy,
748
+ "Tally": Tally,
749
+ # --- Set algebra (over Array - no dedicated Set type) ---
750
+ "Union": Union,
751
+ "Intersection": Intersection,
752
+ "SetMinus": SetMinus,
753
+ "SymmetricDifference": SymmetricDifference,
754
+ "Subset": Subset,
755
+ "SubsetEqual": SubsetEqual,
756
+ "Superset": Superset,
757
+ "SupersetEqual": SupersetEqual,
758
+ "NotSubset": NotSubset,
759
+ "NotSuperset": NotSuperset,
760
+ "Interval": Interval,
761
+ "Open": Open,
762
+ }
763
+
764
+
765
+ def create_mathjson_solver(
766
+ solver_parameters: dict[str, MathJSONExpression],
767
+ legacy_v1: bool = False,
768
+ blacklist: Iterable[str] | None = None,
769
+ ) -> Callable[[MathJSONExpression], _Any]:
770
+ """
771
+ `blacklist`, if given, is an iterable of construct names (e.g.
772
+ `["PowerSet", "Permutations"]`) that this solver instance refuses to
773
+ evaluate - deployments can disable individual constructs they don't
774
+ want available for their expression sources, independent of what
775
+ the library implements. Attempting to use a blacklisted construct
776
+ raises `MathJSONException` (wrapping `PermissionError`) rather than
777
+ evaluating it or silently ignoring it. A name that isn't an actual
778
+ construct has no effect (not validated against the known-construct
779
+ list - a deliberate simplicity trade-off, not an oversight).
780
+
781
+ This is a resource/access *policy* control, not a substitute for a
782
+ construct being safe to run at all - e.g. the combinatorial
783
+ enumeration functions (`PowerSet`, `Permutations`, `Combinations`,
784
+ `CartesianProduct`) have no built-in output-size limit, so a
785
+ deployment accepting untrusted expressions should blacklist them
786
+ (or any other construct it doesn't want exposed) rather than assume
787
+ every construct is safe by default for every threat model.
788
+ """
789
+ blacklist = frozenset(blacklist) if blacklist else frozenset()
1310
790
 
1311
- constructs = {
1312
- "Sum": Sum,
1313
- "Add": Add,
1314
- "Subtract": Subtract,
1315
- "Constants": Constants,
1316
- "Switch": Switch,
1317
- "StrictSwitch": StrictSwitch,
1318
- "If": If,
1319
- "Multiply": lambda s: reduce(
1320
- lambda a, b: float(a) * float(b), [f(x, c) for x in s[1:]]
1321
- ),
1322
- "Divide": lambda s: f(s[1], c) / f(s[2], c),
1323
- "Negate": lambda s: -f(s[1], c),
1324
- "Power": lambda s: pow(f(s[1], c), f(s[2], c)),
1325
- "Root": lambda s: pow(f(s[1], c), 1.0 / f(s[2], c)),
1326
- "Sqrt": lambda s: pow(f(s[1], c), 1.0 / 2),
1327
- "Square": lambda s: pow(f(s[1], c), 2),
1328
- "Exp": lambda s: math.exp(f(s[1], c)),
1329
- # CortexJS-compatible: ["Log", x] is log base 10; ["Log", x, b] is
1330
- # log base b. Use "Ln" for natural log. (BREAKING as of 2.0.0 -
1331
- # "Log" previously meant natural log.)
1332
- "Log": lambda s: (
1333
- math.log10(f(s[1], c))
1334
- if len(s) == 2
1335
- else math.log(f(s[1], c), f(s[2], c))
1336
- ),
1337
- "Log2": lambda s: math.log2(f(s[1], c)),
1338
- "Log10": lambda s: math.log10(f(s[1], c)),
1339
- "Ln": lambda s: math.log(f(s[1], c)),
1340
- "Lb": lambda s: math.log2(f(s[1], c)), # CortexJS name for Log2
1341
- "Lg": lambda s: math.log10(f(s[1], c)), # CortexJS name for Log10
1342
- "LogOnePlus": lambda s: math.log1p(f(s[1], c)),
1343
- # "Equal": lambda s: f"{f(s[1], c)}" == f"{f(s[2], c)}",
1344
- "Equal": lambda s: comparison_safe_converter(f(s[1], c))
1345
- == comparison_safe_converter(f(s[2], c)),
1346
- "IsTrue": lambda s: bool(f(s[1], c)),
1347
- "IsFalse": lambda s: not bool(f(s[1], c)),
1348
- "StrictEqual": lambda s: f(s[1], c) == f(s[2], c),
1349
- # "Greater": lambda s: f(s[1], c) > f(s[2], c),
1350
- "Greater": Greater,
1351
- # "GreaterEqual": lambda s: f(s[1], c) >= f(s[2], c),
1352
- "GreaterEqual": GreaterEqual,
1353
- # "Less": lambda s: f(s[1], c) < f(s[2], c),
1354
- "Less": Less,
1355
- # "LessEqual": lambda s: f(s[1], c) <= f(s[2], c),
1356
- "LessEqual": LessEqual,
1357
- # "NotEqual": lambda s: f(s[1], c) != f(s[2], c),
1358
- "NotEqual": lambda s: comparison_safe_converter(f(s[1], c))
1359
- != comparison_safe_converter(f(s[2], c)),
1360
- "And": BooleanAnd,
1361
- "Or": BooleanOr,
1362
- "Abs": lambda s: abs(f(s[1], c)),
1363
- "Round": lambda s: (
1364
- round(f(s[1], c), f(s[2], c))
1365
- if len(s) == 3
1366
- else int(round(f(s[1], c)))
1367
- ),
1368
- "Max": Max,
1369
- "Min": Min,
1370
- "Average": Average,
1371
- "Mean": Average, # CortexJS name for Average
1372
- "Median": Median,
1373
- "Length": Length,
1374
- "Count": Length, # CortexJS name for Length
1375
- "Any": Any,
1376
- "All": All,
1377
- "Array": Arr,
1378
- "List": lambda s: ["Array"] + [f(x, c) for x in s[1:]], # CortexJS name for Array
1379
- "In": In,
1380
- "Not_in": Not_in,
1381
- "Contains_any_of": Contains_any_of,
1382
- "Contains_all_of": Contains_all_of,
1383
- "Contains_none_of": Contains_none_of,
1384
- "NotIn": Not_in,
1385
- "ContainsAnyOf": Contains_any_of,
1386
- "ContainsAllOf": Contains_all_of,
1387
- "ContainsNoneOf": Contains_none_of,
1388
- "Int": Int,
1389
- "Float": Float,
1390
- "Floor": Floor,
1391
- "Ceil": Ceil,
1392
- "Str": Str,
1393
- "Not": Not,
1394
- # "IsDefined": lambda s: s[1] in c,
1395
- "IsDefined": IsDefined,
1396
- "IsUndefined": IsUndefined,
1397
- "Map": Map,
1398
- "StrictMap": StrictMap,
1399
- "Filter": Filter,
1400
- "HasMatchingSublist": HasMatchingSublist,
1401
- "Strptime": Strptime,
1402
- "Strftime": Strftime,
1403
- "Today": Today,
1404
- "Now": Now,
1405
- "TimeDeltaWeeks": TimeDeltaWeeks,
1406
- "TimeDeltaHours": TimeDeltaHours,
1407
- "TimeDeltaMinutes": TimeDeltaMinutes,
1408
- "TimeDeltaDays": TimeDeltaDays,
1409
- "Function": Function,
1410
- "Variable": Variable,
1411
- "MultiplyByScalar": MultiplyByScalar,
1412
- "MultiplyByArray": MultiplyByArray,
1413
- "AddScalar": AddScalar,
1414
- "SubtractScalar": SubtractScalar,
1415
- "AddArray": AddArray,
1416
- "SubtractArray": SubtractArray,
1417
- "GenerateRange": GenerateRange,
1418
- "AtIndex": AtIndex,
1419
- "Slice": Slice,
1420
- "CumulativeProduct": CumulativeProduct,
1421
- "CumulativeSum": CumulativeSum,
1422
- "Interp": Interp,
1423
- "FindIntervalIndex": FindIntervalIndex,
1424
- "TrapezoidalIntegrate": TrapezoidalIntegrate,
1425
- "Reduce": Reduce,
1426
- "Product": Product,
1427
- "Appended": Appended,
1428
- "Sin": Sin,
1429
- "Cos": Cos,
1430
- "Tan": Tan,
1431
- "Arcsin": Arcsin,
1432
- "Arccos": Arccos,
1433
- "Arctan": Arctan,
1434
- "Arctan2": lambda s: math.atan2(f(s[1], c), f(s[2], c)),
1435
- "Pi": Pi,
1436
- "Which": Switch, # CortexJS name for Switch
1437
- # --- Trigonometric: reciprocal, hyperbolic, area-hyperbolic ---
1438
- "Cot": lambda s: 1 / math.tan(f(s[1], c)),
1439
- "Sec": lambda s: 1 / math.cos(f(s[1], c)),
1440
- "Csc": lambda s: 1 / math.sin(f(s[1], c)),
1441
- "Arccot": lambda s: math.atan(1 / f(s[1], c)),
1442
- "Arcsec": lambda s: math.acos(1 / f(s[1], c)),
1443
- "Arccsc": lambda s: math.asin(1 / f(s[1], c)),
1444
- "Sinh": lambda s: math.sinh(f(s[1], c)),
1445
- "Cosh": lambda s: math.cosh(f(s[1], c)),
1446
- "Tanh": lambda s: math.tanh(f(s[1], c)),
1447
- "Coth": lambda s: 1 / math.tanh(f(s[1], c)),
1448
- "Sech": lambda s: 1 / math.cosh(f(s[1], c)),
1449
- "Csch": lambda s: 1 / math.sinh(f(s[1], c)),
1450
- "Arsinh": lambda s: math.asinh(f(s[1], c)),
1451
- "Arcosh": lambda s: math.acosh(f(s[1], c)),
1452
- "Artanh": lambda s: math.atanh(f(s[1], c)),
1453
- "Arcoth": lambda s: math.atanh(1 / f(s[1], c)),
1454
- "Arsech": lambda s: math.acosh(1 / f(s[1], c)),
1455
- "Arcsch": lambda s: math.asinh(1 / f(s[1], c)),
1456
- "Hypot": lambda s: math.hypot(f(s[1], c), f(s[2], c)),
1457
- "Sinc": lambda s: (
1458
- 1.0 if f(s[1], c) == 0 else math.sin(f(s[1], c)) / f(s[1], c)
1459
- ),
1460
- # --- Constants ---
1461
- "Degrees": lambda s: math.pi / 180,
1462
- "ExponentialE": lambda s: math.e,
1463
- "GoldenRatio": lambda s: (1 + math.sqrt(5)) / 2,
1464
- # --- Number theory / special functions ---
1465
- "Chop": lambda s: 0 if abs(f(s[1], c)) < 1e-10 else f(s[1], c),
1466
- "Mod": lambda s: f(s[1], c) % f(s[2], c),
1467
- "Clamp": Clamp,
1468
- "GCD": lambda s: math.gcd(int(f(s[1], c)), int(f(s[2], c))),
1469
- "LCM": lambda s: math.lcm(int(f(s[1], c)), int(f(s[2], c))),
1470
- "Factorial": lambda s: math.factorial(int(f(s[1], c))),
1471
- "Binomial": lambda s: math.comb(int(f(s[1], c)), int(f(s[2], c))),
1472
- "IsPrime": IsPrime,
1473
- "Erf": lambda s: math.erf(f(s[1], c)),
1474
- "Erfc": lambda s: math.erfc(f(s[1], c)),
1475
- # --- Boolean logic ---
1476
- "Xor": lambda s: bool(f(s[1], c)) ^ bool(f(s[2], c)),
1477
- "Nand": lambda s: not all(f(x, c) for x in s[1:]),
1478
- "Nor": lambda s: not any(f(x, c) for x in s[1:]),
1479
- "Implies": lambda s: (not f(s[1], c)) or bool(f(s[2], c)),
1480
- "Equivalent": lambda s: bool(f(s[1], c)) == bool(f(s[2], c)),
1481
- # --- Statistics ---
1482
- "Variance": Variance,
1483
- "StandardDeviation": StandardDeviation,
1484
- # --- Collections ---
1485
- "First": First,
1486
- "Last": Last,
1487
- "Rest": Rest,
1488
- "Most": Most,
1489
- "Reverse": Reverse,
1490
- "Sort": Sort,
1491
- "IsEmpty": IsEmpty,
1492
- "Range": Range,
1493
- "Join": Join,
1494
- "Unique": Unique,
1495
- "Zip": Zip,
1496
- "At": At,
1497
- }
791
+ def f(s, *args):
792
+ # Leaf values never touch `c` at all - check them before doing
793
+ # anything with it, since leaves vastly outnumber interior nodes
794
+ # in any real expression tree.
795
+ if isinstance(s, numbers.Number):
796
+ return s
797
+ # CortexJS represents the boolean literals as the bare symbols
798
+ # "True" and "False" (as opposed to native JSON `true`/`false`,
799
+ # which already arrive here as Python bool - itself a `numbers.Number`
800
+ # subtype, so it's handled by the check above). Resolve them to
801
+ # actual booleans unconditionally, the same way numeric literals
802
+ # are resolved above, so they can't be shadowed by a same-named
803
+ # solver parameter or local variable.
804
+ if s == "True" or s == "False":
805
+ return s == "True"
806
+ # `c` is passed through by reference, not copied, here or at any
807
+ # of the call sites below - almost every construct only reads
808
+ # it. The few constructs that introduce new bindings (Constants,
809
+ # Reduce's legacy accumulator form, TrapezoidalIntegrate) are
810
+ # responsible for making their own `c = dict(c)` copy before
811
+ # writing into it, the same way `_apply_fn` already does for
812
+ # `Function` - so a written binding is visible to whatever that
813
+ # construct evaluates internally, but never leaks back into the
814
+ # caller's scope once the construct returns.
815
+ c = args[0] if args else {}
816
+ if isinstance(s, list):
1498
817
  if not s:
1499
818
  # Empty equation given - []
1500
819
  return None
1501
820
  if s[0] in constructs:
821
+ if s[0] in blacklist:
822
+ raise MathJSONException(
823
+ PermissionError(
824
+ f"'{s[0]}' has been disabled in this solver instance."
825
+ ),
826
+ s,
827
+ mathjson_construct=s[0],
828
+ )
1502
829
  try:
1503
- return constructs[s[0]](s)
830
+ return constructs[s[0]](f, c, solver_parameters, s)
1504
831
 
1505
832
  # except RecursionError:
1506
833
  # return s[0]
@@ -1542,7 +869,9 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1542
869
  return f
1543
870
 
1544
871
 
1545
- def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set):
872
+ def extract_variables(
873
+ s: MathJSONExpression, li: set[str], ignore_list: set[str]
874
+ ) -> set[str]:
1546
875
  constructs = [
1547
876
  "Add",
1548
877
  "Sum",
@@ -1591,15 +920,46 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1591
920
  "ContainsAnyOf",
1592
921
  "ContainsAllOf",
1593
922
  "ContainsNoneOf",
923
+ "Element",
924
+ "NotElement",
1594
925
  "Int",
1595
926
  "Float",
1596
927
  "Floor",
1597
928
  "Ceil",
1598
929
  "Str",
930
+ "String",
931
+ "StringJoin",
932
+ "ToUpperCase",
933
+ "ToLowerCase",
934
+ "CaseFold",
935
+ "Trim",
936
+ "TrimStart",
937
+ "TrimEnd",
938
+ "StringSplit",
939
+ "StringReplace",
940
+ "StringCompare",
941
+ "StringRepeat",
942
+ "PadStart",
943
+ "PadEnd",
944
+ "Characters",
945
+ "GraphemeClusters",
946
+ "Utf8",
947
+ "Utf16",
948
+ "UnicodeScalars",
949
+ "StringFrom",
950
+ "IntegerString",
951
+ "DigitsFrom",
952
+ "NumberFrom",
953
+ "RegExp",
954
+ "IsMatch",
955
+ "StringMatch",
956
+ "StringMatchAll",
1599
957
  "Not",
1600
958
  "IsDefined",
1601
959
  "IsUndefined",
1602
960
  "StrictEqual",
961
+ "IdenticallyEqual",
962
+ "Congruent",
1603
963
  "NotEqual",
1604
964
  "StrictSwitch",
1605
965
  "Map",
@@ -1672,6 +1032,12 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1672
1032
  "Degrees",
1673
1033
  "ExponentialE",
1674
1034
  "GoldenRatio",
1035
+ "MachineEpsilon",
1036
+ "CatalanConstant",
1037
+ "EulerGamma",
1038
+ "Rational",
1039
+ "Numerator",
1040
+ "Denominator",
1675
1041
  "Chop",
1676
1042
  "Mod",
1677
1043
  "Clamp",
@@ -1682,6 +1048,88 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1682
1048
  "IsPrime",
1683
1049
  "Erf",
1684
1050
  "Erfc",
1051
+ "PowerMod",
1052
+ "ModularInverse",
1053
+ "IntegerSqrt",
1054
+ "FactorInteger",
1055
+ "PrimeFactors",
1056
+ "PrimeNu",
1057
+ "PrimeOmega",
1058
+ "Radical",
1059
+ "IsSquareFree",
1060
+ "Divisors",
1061
+ "Sigma0",
1062
+ "Sigma1",
1063
+ "SigmaMinus1",
1064
+ "DivisorSigma",
1065
+ "Divides",
1066
+ "Totient",
1067
+ "IsPerfectPower",
1068
+ "NthPrime",
1069
+ "NextPrime",
1070
+ "PrimePi",
1071
+ "ExtendedGCD",
1072
+ "ChineseRemainder",
1073
+ "CarmichaelLambda",
1074
+ "JacobiSymbol",
1075
+ "LegendreSymbol",
1076
+ "MultiplicativeOrder",
1077
+ "PrimitiveRoot",
1078
+ "LucasL",
1079
+ "CatalanNumber",
1080
+ "BernoulliB",
1081
+ "ContinuedFraction",
1082
+ "FromContinuedFraction",
1083
+ "IntegerDigits",
1084
+ "DigitCount",
1085
+ "DigitSum",
1086
+ "FromDigits",
1087
+ "IsSquare",
1088
+ "IsTriangular",
1089
+ "IsPentagonal",
1090
+ "IsOctahedral",
1091
+ "IsCenteredSquare",
1092
+ "IsPerfect",
1093
+ "IsAbundant",
1094
+ "IsHappy",
1095
+ "Gamma",
1096
+ "GammaLn",
1097
+ "Beta",
1098
+ "Factorial2",
1099
+ "ErfInv",
1100
+ "LambertW",
1101
+ "AGM",
1102
+ "EllipticK",
1103
+ "EllipticE",
1104
+ "Hypergeometric1F1",
1105
+ "Hypergeometric2F1",
1106
+ "BesselJ",
1107
+ "BesselY",
1108
+ "BesselI",
1109
+ "BesselK",
1110
+ "AiryAi",
1111
+ "AiryBi",
1112
+ "AiryAiPrime",
1113
+ "AiryBiPrime",
1114
+ "Zeta",
1115
+ "GammaRegularized",
1116
+ "BetaRegularized",
1117
+ "Choose",
1118
+ "Fibonacci",
1119
+ "Multinomial",
1120
+ "Subfactorial",
1121
+ "BellNumber",
1122
+ "PowerSet",
1123
+ "Permutations",
1124
+ "Combinations",
1125
+ "CartesianProduct",
1126
+ "Head",
1127
+ "Tail",
1128
+ "Hold",
1129
+ "Identity",
1130
+ "Type",
1131
+ "IsSame",
1132
+ "Same",
1685
1133
  "Xor",
1686
1134
  "Nand",
1687
1135
  "Nor",
@@ -1689,7 +1137,28 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1689
1137
  "Equivalent",
1690
1138
  "Variance",
1691
1139
  "StandardDeviation",
1140
+ "PopulationVariance",
1141
+ "PopulationStandardDeviation",
1142
+ "Mode",
1143
+ "Quartiles",
1144
+ "InterquartileRange",
1145
+ "Covariance",
1146
+ "Correlation",
1147
+ "Skewness",
1148
+ "Kurtosis",
1149
+ "LinearRegression",
1150
+ "PolynomialFit",
1151
+ "NormalDistribution",
1152
+ "BinomialDistribution",
1153
+ "PoissonDistribution",
1154
+ "UniformDistribution",
1155
+ "ExponentialDistribution",
1156
+ "PDF",
1157
+ "CDF",
1158
+ "Quantile",
1692
1159
  "First",
1160
+ "Second",
1161
+ "Third",
1693
1162
  "Last",
1694
1163
  "Rest",
1695
1164
  "Most",
@@ -1701,11 +1170,56 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1701
1170
  "Unique",
1702
1171
  "Zip",
1703
1172
  "At",
1173
+ "Take",
1174
+ "Drop",
1175
+ "TakeWhile",
1176
+ "DropWhile",
1177
+ "Contains",
1178
+ "IndexOf",
1179
+ "IndexWhere",
1180
+ "Find",
1181
+ "CountIf",
1182
+ "Position",
1183
+ "RotateLeft",
1184
+ "RotateRight",
1185
+ "MaxBy",
1186
+ "MinBy",
1187
+ "ArgMax",
1188
+ "ArgMin",
1189
+ "Ordering",
1190
+ "FlatMap",
1191
+ "Scan",
1192
+ "Differences",
1193
+ "Fold",
1194
+ "Dedup",
1195
+ "Append",
1196
+ "Insert",
1197
+ "DeleteAt",
1198
+ "ReplaceAt",
1199
+ "Partition",
1200
+ "Chunk",
1201
+ "GroupBy",
1202
+ "ChunkBy",
1203
+ "Tally",
1204
+ "Union",
1205
+ "Intersection",
1206
+ "SetMinus",
1207
+ "SymmetricDifference",
1208
+ "Subset",
1209
+ "SubsetEqual",
1210
+ "Superset",
1211
+ "SupersetEqual",
1212
+ "NotSubset",
1213
+ "NotSuperset",
1214
+ "Interval",
1215
+ "Open",
1704
1216
  ]
1705
1217
  if isinstance(s, str):
1706
1218
  if s in ignore_list:
1707
1219
  return li
1708
- if s not in constructs:
1220
+ # "True"/"False" are boolean literals (see `f`'s handling of them),
1221
+ # not solver-parameter references, so they're never free variables.
1222
+ if s not in constructs and s not in ("True", "False"):
1709
1223
  li.add(s)
1710
1224
  return li
1711
1225
  elif isinstance(s, list):
@@ -1721,11 +1235,7 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1721
1235
  # ["If", [cond, val], ..., else_val].
1722
1236
  is_cortexjs_form = len(s) > 1 and (
1723
1237
  not isinstance(s[1], list)
1724
- or (
1725
- bool(s[1])
1726
- and isinstance(s[1][0], str)
1727
- and s[1][0] in constructs
1728
- )
1238
+ or (bool(s[1]) and isinstance(s[1][0], str) and s[1][0] in constructs)
1729
1239
  )
1730
1240
  if is_cortexjs_form:
1731
1241
  for x in s[1:]:
@@ -1746,6 +1256,27 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1746
1256
  ignore_list.add("_")
1747
1257
  if len(s) > 1:
1748
1258
  li.update(extract_variables(s[1], li, ignore_list))
1259
+ elif s[0] in ("Head", "Tail", "Hold", "IsSame", "Same"):
1260
+ # These deliberately never evaluate their arguments either
1261
+ # (Head/Tail/Hold work on the raw, unevaluated expression
1262
+ # tree; IsSame/Same do a pure structural comparison of the
1263
+ # two raw trees) - same reasoning as the unrecognized-
1264
+ # construct case below, just for constructs that *are*
1265
+ # recognized. A bare name inside their arguments is never
1266
+ # resolved as a parameter reference, so it's not a free
1267
+ # variable to supply.
1268
+ pass
1269
+ elif s[0] not in constructs:
1270
+ # Unrecognized construct (e.g. "Color", "Quantity" - anything
1271
+ # this solver doesn't implement): f() never evaluates or
1272
+ # substitutes into such expressions either (its fallback for
1273
+ # an unknown head is to return the whole list unchanged), so
1274
+ # none of its arguments are free variables to supply. Treat
1275
+ # the whole thing as opaque data rather than recursing into
1276
+ # it, so a decorative/unrelated subtree (e.g. a color literal
1277
+ # meant for something else downstream) doesn't get reported
1278
+ # as a required parameter.
1279
+ pass
1749
1280
  else:
1750
1281
  for x in s[1:]:
1751
1282
  li.update(extract_variables(x, li, ignore_list))